[mapserver] 02/08: Imported Upstream version 6.4.2

Sebastiaan Couwenberg sebastic at moszumanska.debian.org
Tue Jul 7 19:34:32 UTC 2015


This is an automated email from the git hooks/post-receive script.

sebastic pushed a commit to branch master
in repository mapserver.

commit c0620105b128d3888b1ae220cdf52894070b6cd6
Author: Bas Couwenberg <sebastic at xs4all.nl>
Date:   Tue Jul 7 19:24:29 2015 +0200

    Imported Upstream version 6.4.2
---
 .gitattributes                           |   2 -
 .gitignore                               |   6 -
 .travis.yml                              |   7 +-
 CMakeLists.txt                           |   6 +-
 Vagrantfile                              |  79 ++++
 cgiutil.c                                |  24 +-
 cgiutil.h                                |   1 -
 cmake/FindAPACHE.cmake                   |   5 +-
 cmake/FindOracle.cmake                   |   4 +-
 hittest.c                                |   2 +-
 mapagg.cpp                               |  31 +-
 mapcairo.c                               |   9 +-
 mapcontext.c                             |   3 +-
 mapcontour.c                             |   4 +
 mapcopy.c                                |   3 -
 mapdebug.c                               |  20 +-
 mapdraw.c                                |  57 ++-
 mapfile.c                                | 213 +++++-----
 mapgd.c                                  |  10 +-
 mapgeos.c                                |  12 +-
 mapgml.c                                 |  28 +-
 mapgraticule.c                           |  35 +-
 maphash.c                                |   1 -
 maphttp.c                                |   6 +
 mapimageio.c                             |   8 +-
 mapimagemap.c                            | 124 +++---
 mapio.c                                  |  18 +
 mapio.h                                  |   1 +
 mapkmlrenderer.cpp                       |  19 +-
 maplabel.c                               |   9 +-
 maplayer.c                               | 227 +++++-----
 maplegend.c                              |  19 +-
 maplexer.c                               | 687 ++++++++++++++++---------------
 maplexer.l                               |   1 +
 maplibxml2.c                             |  12 +-
 maplibxml2.h                             |   2 +-
 mapogcfilter.c                           |  53 +--
 mapogcfiltercommon.c                     |  10 +-
 mapogcsld.c                              |  91 ++--
 mapogcsld.h                              |   2 +-
 mapogcsos.c                              |  41 +-
 mapogr.cpp                               |   7 +-
 mapogroutput.c                           |  13 +-
 mapoutput.c                              |  63 +--
 mapows.c                                 |  97 +++--
 mappostgis.c                             | 110 ++---
 mappostgresql.c                          |   9 +-
 mapprimitive.c                           |  14 +-
 mapproject.c                             |   2 +-
 mapquantization.c                        |  22 +-
 mapquery.c                               |  12 +-
 maprasterquery.c                         |   2 +-
 maprendering.c                           |  19 +-
 mapresample.c                            |   6 +-
 mapscript/csharp/CMakeLists.txt          |   4 +-
 mapscript/java/.gitignore                |   1 -
 mapscript/perl/.gitignore                |   5 -
 mapscript/php/owsrequest.c               |  23 ++
 mapserv.c                                |  16 +-
 mapservutil.c                            | 151 ++++---
 mapshape.c                               | 196 ++++++---
 mapsmoothing.c                           |   5 +-
 mapstring.c                              |  18 +-
 mapsymbol.c                              |   4 +-
 maptemplate.c                            | 101 +++--
 maptile.c                                |   4 +-
 maptime.c                                |  11 +-
 maptree.c                                |   1 +
 maputil.c                                |  36 +-
 mapuvraster.c                            |  17 +-
 mapwcs.c                                 |  41 +-
 mapwcs11.c                               |  49 ++-
 mapwcs20.c                               |  46 ++-
 mapwfs.c                                 |  49 +--
 mapwfs11.c                               |   5 +-
 mapwfslayer.c                            |  14 +-
 mapwms.c                                 |  96 +++--
 mapwmslayer.c                            |   2 +-
 mapxbase.c                               |   5 +-
 renderers/agg/include/agg_conv_clipper.h |   4 +
 renderers/agg/src/agg_vcgen_dash.cpp     |   2 +-
 scripts/vagrant/mapserver.sh             |  33 ++
 scripts/vagrant/postgis.sh               |   8 +
 shptreevis.c                             |   1 +
 tile4ms.c                                |   1 +
 85 files changed, 1885 insertions(+), 1332 deletions(-)

diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 5966153..0000000
--- a/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-.gitattributes export-ignore
-.gitignore export-ignore
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 741a9e7..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-build
-*.swp
-nbproject
-tags
-tests/map.png
-
diff --git a/.travis.yml b/.travis.yml
index 62781fc..6ae41df 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,7 @@
 language: php
 php:
   - 5.5
+  - 5.6
 
 env:
   global:
@@ -42,10 +43,10 @@ compiler:
 before_install:
   - git submodule update --init --recursive
   - sudo mv /etc/apt/sources.list.d/pgdg-source.list* /tmp
-  - sudo apt-get -qq remove postgis
+  - sudo apt-get  remove postgis libpq5 libpq-dev postgresql-9.1-postgis postgresql-9.2-postgis postgresql-9.3-postgis postgresql-9.1 postgresql-9.2 postgresql-9.3 libgdal1
   - sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable
-  - sudo apt-get update -qq
-  - sudo apt-get install -qq bison flex swig cmake librsvg2-dev colordiff postgis postgresql-9.1-postgis-2.0-scripts libpq-dev libpng12-dev libjpeg-dev libgif-dev libgeos-dev libgd2-xpm-dev libfreetype6-dev libfcgi-dev libcurl4-gnutls-dev libcairo2-dev libgdal1-dev libproj-dev libxml2-dev python-dev php5-dev libexempi-dev lcov lftp
+  - sudo apt-get update 
+  - sudo apt-get install  bison flex swig cmake librsvg2-dev colordiff postgis postgresql-9.1 postgresql-9.1-postgis-2.1 postgresql-9.1-postgis-2.1-scripts libpq-dev libpng12-dev libjpeg-dev libgif-dev libgeos-dev libgd2-xpm-dev libfreetype6-dev libfcgi-dev libcurl4-gnutls-dev libcairo2-dev libgdal1-dev libproj-dev libxml2-dev python-dev php5-dev libexempi-dev lcov lftp
   - sudo pip install git+git://github.com/tbonfort/cpp-coveralls.git@extensions
   - cd msautotest
   - ./create_postgis_test_data.sh
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5837920..ba6c3a2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -17,7 +17,7 @@ include(CheckCSourceCompiles)
 
 set (MapServer_VERSION_MAJOR 6)
 set (MapServer_VERSION_MINOR 4)
-set (MapServer_VERSION_REVISION 1)
+set (MapServer_VERSION_REVISION 2)
 set (MapServer_VERSION_SUFFIX "")
 
 set(TARGET_VERSION_MAJOR ${MapServer_VERSION_MAJOR})
@@ -120,7 +120,7 @@ option(WITH_LIBXML2 "Choose if libxml2 support should be built in (used for sos,
 option(WITH_THREAD_SAFETY "Choose if a thread-safe version of libmapserver should be built (only recommended for some mapscripts)" OFF)
 option(WITH_GIF "Enable GIF support (for PIXMAP loading)" ON)
 option(WITH_PYTHON "Enable Python mapscript support" OFF)
-option(WITH_PHP "Enable Python mapscript support" OFF)
+option(WITH_PHP "Enable PHP mapscript support" OFF)
 option(WITH_PERL "Enable Perl mapscript support" OFF)
 option(WITH_RUBY "Enable Ruby mapscript support" OFF)
 option(WITH_JAVA "Enable Java mapscript support" OFF)
@@ -530,7 +530,7 @@ if(WITH_SVGCAIRO)
   endif(WITH_RSVG)
   find_package(SVGCairo)
   if(SVGCAIRO_FOUND)
-    include_directories(${SVGCAIRO_INCLUDE_DIR})
+    include_directories(${SVG_INCLUDE_DIR} ${SVGCAIRO_INCLUDE_DIR})
     ms_link_libraries( ${SVG_LIBRARY} ${SVGCAIRO_LIBRARY})
     set (USE_SVG_CAIRO 1)
   else(SVGCAIRO_FOUND)
diff --git a/Vagrantfile b/Vagrantfile
new file mode 100644
index 0000000..5788de6
--- /dev/null
+++ b/Vagrantfile
@@ -0,0 +1,79 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+require 'socket'
+
+# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
+VAGRANTFILE_API_VERSION = "2"
+
+Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
+  config.vm.box = "precise64"
+
+  config.vm.hostname = "mapserver-vagrant"
+  config.vm.box_url = "http://files.vagrantup.com/precise64.box"
+  config.vm.host_name = "mapserver-vagrant"
+  
+  config.vm.network :forwarded_port, guest: 80, host: 8080
+
+  config.vm.provider :virtualbox do |vb|
+     vb.customize ["modifyvm", :id, "--memory", "4096"]
+     vb.customize ["modifyvm", :id, "--cpus", "2"]
+     vb.customize ["modifyvm", :id, "--ioapic", "on"]
+     vb.name = "mapserver-vagrant"
+   end  
+
+  ppaRepos = [
+    "ppa:ubuntugis/ppa",
+  ]
+
+  packageList = [
+    "git",
+    "build-essential",
+    "pkg-config",
+    "cmake",
+    "libgeos-dev",
+    "libpq-dev",
+    "python-all-dev",
+    "libproj-dev",
+    "libxml2-dev",
+    "postgis",
+    "postgresql-server-dev-9.1",
+    "postgresql-9.1-postgis",
+    "vim",
+    "bison",
+    "flex",
+    "swig",
+    "librsvg2-dev",
+    "libpng12-dev",
+    "libjpeg-dev",
+    "libgif-dev",
+    "libgd2-xpm-dev",
+    "libfreetype6-dev",
+    "libfcgi-dev",
+    "libcurl4-gnutls-dev",
+    "libcairo2-dev",
+    "libgdal1-dev",
+    "php5-dev",
+    "libexempi-dev"
+  ];
+
+  if Dir.glob("#{File.dirname(__FILE__)}/.vagrant/machines/default/*/id").empty?
+	  pkg_cmd = "sed -i 's#deb http://us.archive.ubuntu.com/ubuntu/#deb mirror://mirrors.ubuntu.com/mirrors.txt#' /etc/apt/sources.list; "
+
+	  pkg_cmd << "apt-get update -qq; apt-get install -q -y python-software-properties; "
+
+	  if ppaRepos.length > 0
+		  ppaRepos.each { |repo| pkg_cmd << "add-apt-repository -y " << repo << " ; " }
+		  pkg_cmd << "apt-get update -qq; "
+	  end
+
+	  # install packages we need we need
+	  pkg_cmd << "apt-get install -q -y " + packageList.join(" ") << " ; "
+	  config.vm.provision :shell, :inline => pkg_cmd
+    scripts = [
+      "mapserver.sh",
+      "postgis.sh"
+    ];
+    scripts.each { |script| config.vm.provision :shell, :path => "scripts/vagrant/" << script }
+  end
+end
diff --git a/cgiutil.c b/cgiutil.c
index e2a9c63..3d44d6c 100644
--- a/cgiutil.c
+++ b/cgiutil.c
@@ -386,33 +386,15 @@ int rind(char *s, char c)
   return -1;
 }
 
-int _getline(char *s, int n, FILE *f)
-{
-  register int i=0;
-
-  while(1) {
-    s[i] = (char)fgetc(f);
-
-    if(s[i] == CR)
-      s[i] = fgetc(f);
-
-    if((s[i] == 0x4) || (s[i] == LF) || (i == (n-1))) {
-      s[i] = '\0';
-      return (feof(f) ? 1 : 0);
-    }
-    ++i;
-  }
-}
-
 void send_fd(FILE *f, FILE *fd)
 {
-  char c;
+  int c;
 
   while (1) {
     c = fgetc(f);
-    if(feof(f))
+    if(c == EOF)
       return;
-    fputc(c,fd);
+    fputc((char)c,fd);
   }
 }
 
diff --git a/cgiutil.h b/cgiutil.h
index f6cc0ca..264d13d 100644
--- a/cgiutil.h
+++ b/cgiutil.h
@@ -87,7 +87,6 @@ MS_DLL_EXPORT char x2c(char *);
 MS_DLL_EXPORT void unescape_url(char *);
 MS_DLL_EXPORT void plustospace(char *);
 MS_DLL_EXPORT int rind(char *, char);
-MS_DLL_EXPORT int _getline(char *, int, FILE *);
 MS_DLL_EXPORT void send_fd(FILE *, FILE *);
 MS_DLL_EXPORT int ind(char *, char);
 MS_DLL_EXPORT void escape_shell_cmd(char *);
diff --git a/cmake/FindAPACHE.cmake b/cmake/FindAPACHE.cmake
index 2ec4f15..eb44d48 100644
--- a/cmake/FindAPACHE.cmake
+++ b/cmake/FindAPACHE.cmake
@@ -24,9 +24,8 @@ find_program(HTTPD_EXECUTABLE NAMES httpd
 )
 
 if(APXS_BIN)
-   EXEC_PROGRAM(${APXS_BIN}
-      ARGS -q LIBEXECDIR
-      OUTPUT_VARIABLE APACHE_MODULE_DIR )
+    EXECUTE_PROCESS(COMMAND ${APXS_BIN} -q LIBEXECDIR
+	    OUTPUT_VARIABLE APACHE_MODULE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE)
 endif(APXS_BIN)
 
 include(FindPackageHandleStandardArgs)
diff --git a/cmake/FindOracle.cmake b/cmake/FindOracle.cmake
index c38f92d..18055f7 100644
--- a/cmake/FindOracle.cmake
+++ b/cmake/FindOracle.cmake
@@ -37,8 +37,8 @@ if(DEFINED ENV{ORACLE_HOME})
     ${ORACLE_HOME}/OCI/include) # Oracle XE on Windows
 
   set(ORACLE_OCI_NAMES clntsh libclntsh oci)
-  set(ORACLE_NNZ_NAMES nnz10 libnnz10 nnz11 libnnz11 ociw32)
-  set(ORACLE_OCCI_NAMES libocci occi oraocci10 oraocci11)
+  set(ORACLE_NNZ_NAMES nnz10 libnnz10 nnz11 libnnz11 nnz12 libnnz12 ociw32)
+  set(ORACLE_OCCI_NAMES libocci occi oraocci10 oraocci11 oraocci12)
 
   set(ORACLE_LIB_DIR 
     ${ORACLE_HOME}
diff --git a/hittest.c b/hittest.c
index 4c4b0a0..03f6bb6 100644
--- a/hittest.c
+++ b/hittest.c
@@ -58,7 +58,6 @@ void initClassHitTests(classObj *c, class_hittest *ch, int default_status) {
 void initLayerHitTests(layerObj *l, layer_hittest *lh) {
   int i,default_status;
   lh->classhits = msSmallCalloc(l->numclasses,sizeof(class_hittest));
-  lh->status = default_status;
 
   switch(l->type) {
     case MS_LAYER_POLYGON:
@@ -71,6 +70,7 @@ void initLayerHitTests(layerObj *l, layer_hittest *lh) {
       default_status = 1; /* no hittesting needed, use traditional mode */
       break;
   }
+  lh->status = default_status;
   for(i=0; i<l->numclasses; i++) {
     initClassHitTests(l->class[i],&lh->classhits[i], default_status);
   }
diff --git a/mapagg.cpp b/mapagg.cpp
index 9622be7..641a9a7 100644
--- a/mapagg.cpp
+++ b/mapagg.cpp
@@ -218,7 +218,6 @@ public:
   }
 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*/
@@ -562,8 +561,8 @@ int agg2RenderBitmapGlyphs(imageObj *img, double x, double y, labelStyleObj *sty
   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;
+  int numlines=1;
+  char **lines = NULL;
   /*masking out the out-of-range character codes*/
   int len;
   int cc_start = rasterfonts[size][2];
@@ -571,35 +570,32 @@ int agg2RenderBitmapGlyphs(imageObj *img, double x, double y, labelStyleObj *sty
   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]);
+    if(lines) text = lines[n];
+    len = strlen(text);
     for (int i = 0; i < len; i++)
-      if (lines[n][i] < cc_start || lines[n][i] > cc_end)
-        lines[n][i] = '.';
+      if (text[i] < cc_start || text[i] > cc_end)
+        text[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);
+            rt.render_text(x+i, y+j, text, true);
           }
         }
       }
     }
     assert(style->color);
     rt.color(aggColor(style->color));
-    rt.render_text(x, y, lines[n], true);
+    rt.render_text(x, y, text, true);
     y += glyph.height();
   }
-  if(*lines != text)
+  if(lines)
     msFreeCharArray(lines, numlines);
   return MS_SUCCESS;
-  return MS_SUCCESS;
 }
 
 int agg2RenderGlyphsLine(imageObj *img, labelPathObj *labelpath, labelStyleObj *style, char *text)
@@ -820,6 +816,10 @@ int agg2RenderTruetypeSymbol(imageObj *img, double x, double y,
 
   msUTF8ToUniChar(symbol->character, &unicode);
   const mapserver::glyph_cache* glyph = cache->m_fman.glyph(unicode);
+  if(!glyph || glyph->glyph_index == 0) {
+    msSetError(MS_TTFERR, "invalid/not-found glpyh index", "agg2RenderTruetypeSymbol()");
+    return MS_FAILURE;
+  }
   double ox = (glyph->bounds.x1 + glyph->bounds.x2) / 2.;
   double oy = (glyph->bounds.y1 + glyph->bounds.y2) / 2.;
 
@@ -994,11 +994,6 @@ int agg2GetTruetypeTextBBox(rendererVTableObj *renderer, char **fonts, int numfo
   const mapserver::glyph_cache* glyph;
   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;
diff --git a/mapcairo.c b/mapcairo.c
index 372debc..66a48a6 100644
--- a/mapcairo.c
+++ b/mapcairo.c
@@ -855,9 +855,7 @@ static void msTransformToGeospatialPDF(imageObj *img, mapObj *map, cairo_rendere
         msBufferResize(r->outputStream, nFileSize);
 
         VSIFSeekL(fp, 0, SEEK_SET);
-        VSIFReadL(r->outputStream->data, 1, nFileSize, fp);
-
-        r->outputStream->size = nFileSize;
+        r->outputStream->size = VSIFReadL(r->outputStream->data, 1, nFileSize, fp);
 
         VSIFCloseL(fp);
         fp = NULL;
@@ -990,7 +988,7 @@ int getRasterBufferCopyCairo(imageObj *img, rasterBufferObj *rb)
   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*));
+  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]);
@@ -1012,7 +1010,7 @@ int mergeRasterBufferCairo(imageObj *img, rasterBufferObj *rb, double opacity,
   cairo_surface_t *src;
   cairo_renderer *r;
   /* not implemented for src,dst,width and height */
-  if(!rb->type == MS_BUFFER_BYTE_RGBA) {
+  if(rb->type != MS_BUFFER_BYTE_RGBA) {
     return MS_FAILURE;
   }
   r = CAIRO_RENDERER(img);
@@ -1135,6 +1133,7 @@ int msPreloadSVGSymbol(symbolObj *symbol)
     cache->svgc = rsvg_handle_new_from_file(symbol->full_pixmap_path,NULL);
     if(!cache->svgc) {
       msSetError(MS_RENDERERERR,"failed to load svg file %s", "msPreloadSVGSymbol()", symbol->full_pixmap_path);
+      return MS_FAILURE;
     }
     rsvg_handle_get_dimensions_sub (cache->svgc, &dim, NULL);
     symbol->sizex = dim.width;
diff --git a/mapcontext.c b/mapcontext.c
index c0fcc24..20221a0 100644
--- a/mapcontext.c
+++ b/mapcontext.c
@@ -392,6 +392,7 @@ int msLoadMapContextLayerFormat(CPLXMLNode *psFormat, layerObj *layer)
   pszValue = msLookupHashTable(&(layer->metadata), "wms_format");
 
   if (
+    pszValue && (
 #if !(defined USE_GD_PNG || defined USE_PNG)
     strcasecmp(pszValue, "image/png") == 0 ||
     strcasecmp(pszValue, "PNG") == 0 ||
@@ -404,7 +405,7 @@ int msLoadMapContextLayerFormat(CPLXMLNode *psFormat, layerObj *layer)
     strcasecmp(pszValue, "image/gif") == 0 ||
     strcasecmp(pszValue, "GIF") == 0 ||
 #endif
-    0 ) {
+    0 )) {
     char **papszList=NULL;
     int i, numformats=0;
 
diff --git a/mapcontour.c b/mapcontour.c
index 15f3129..91f87b0 100644
--- a/mapcontour.c
+++ b/mapcontour.c
@@ -387,6 +387,10 @@ static int msContourLayerReadRaster(layerObj *layer, rectObj rect)
     src_yoff = 0;
     dst_xsize = src_xsize = MIN(map->width,src_xsize);
     dst_ysize = src_ysize = MIN(map->height,src_ysize);
+    copyRect.minx = copyRect.miny = 0;
+    copyRect.maxx = map->width;
+    copyRect.maxy = map->height;
+    dst_cellsize_y = dst_cellsize_x = 1;
   }
 
   /* -------------------------------------------------------------------- */
diff --git a/mapcopy.c b/mapcopy.c
index 1d31c0c..2e167a6 100644
--- a/mapcopy.c
+++ b/mapcopy.c
@@ -271,7 +271,6 @@ int msCopyLeader(labelLeaderObj *dst, labelLeaderObj *src)
       if( freeStyle(dst->styles[i]) == MS_SUCCESS ) msFree(dst->styles[i]);
     }
   }
-  msFree(dst->styles);
   dst->numstyles = 0;
 
   for (i = 0; i < src->numstyles; i++) {
@@ -366,7 +365,6 @@ int msCopyLabel(labelObj *dst, labelObj *src)
       if( freeStyle(dst->styles[i]) == MS_SUCCESS ) msFree(dst->styles[i]);
     }
   }
-  msFree(dst->styles);
   dst->numstyles = 0;
 
   for (i = 0; i < src->numstyles; i++) {
@@ -524,7 +522,6 @@ int msCopyClass(classObj *dst, classObj *src, layerObj *layer)
       }
     }
   }
-  msFree(dst->styles);
   dst->numstyles = 0;
 
   for (i = 0; i < src->numstyles; i++) {
diff --git a/mapdebug.c b/mapdebug.c
index 322fa6c..022febc 100644
--- a/mapdebug.c
+++ b/mapdebug.c
@@ -90,17 +90,13 @@ debugInfoObj *msGetDebugInfoObj()
   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()", (unsigned int)sizeof(debugInfoObj));
-
+    new_link = (debugInfoObj *) msSmallMalloc(sizeof(debugInfoObj));
+    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;
     debuginfo_list = new_link;
   }
 
@@ -146,7 +142,7 @@ int msSetErrorFile(const char *pszErrorFile, const char *pszRelToPath)
     pszErrorFile = extended_path;
   }
 
-  if (debuginfo && debuginfo->errorfile && pszErrorFile &&
+  if (debuginfo->errorfile && pszErrorFile &&
       strcmp(debuginfo->errorfile, pszErrorFile) == 0) {
     /* Nothing to do, already writing to the right place */
     return MS_SUCCESS;
diff --git a/mapdraw.c b/mapdraw.c
index 992838d..4869443 100644
--- a/mapdraw.c
+++ b/mapdraw.c
@@ -446,14 +446,13 @@ imageObj *msDrawMap(mapObj *map, int querymap)
           return(NULL);
         }
       }
-    }
-
-    if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
-      msGettimeofday(&endtime, NULL);
-      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) );
+      if(map->debug >= MS_DEBUGLEVEL_TUNING || lp->debug >= MS_DEBUGLEVEL_TUNING) {
+        msGettimeofday(&endtime, NULL);
+        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) );
+      }
     }
   }
 
@@ -467,6 +466,13 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
     if(MS_SUCCESS != msEmbedScalebar(map, image)) {
       msFreeImage( image );
+#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
+      /* Cleanup WMS/WFS Request stuff */
+      if (pasOWSReqInfo) {
+         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
+         msFree(pasOWSReqInfo);
+      }
+#endif
       return NULL;
     }
 
@@ -478,6 +484,13 @@ imageObj *msDrawMap(mapObj *map, int querymap)
   if(map->legend.status == MS_EMBED && !map->legend.postlabelcache) {
     if( msEmbedLegend(map, image) != MS_SUCCESS ) {
       msFreeImage( image );
+#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
+      /* Cleanup WMS/WFS Request stuff */
+      if (pasOWSReqInfo) {
+         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
+         msFree(pasOWSReqInfo);
+      }
+#endif
       return NULL;
     }
   }
@@ -565,6 +578,13 @@ imageObj *msDrawMap(mapObj *map, int querymap)
 
     if(MS_SUCCESS != msEmbedScalebar(map, image)) {
       msFreeImage( image );
+#if defined(USE_WMS_LYR) || defined(USE_WFS_LYR)
+      /* Cleanup WMS/WFS Request stuff */
+      if (pasOWSReqInfo) {
+         msHTTPFreeRequestObj(pasOWSReqInfo, numOWSRequests);
+         msFree(pasOWSReqInfo);
+      }
+#endif
       return NULL;
     }
 
@@ -1270,19 +1290,16 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
   /* 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));
-
-      if (colorbuffer == NULL || mindistancebuffer == NULL) {
-        msSetError(MS_MEMERR, "Failed to allocate memory for colorbuffer/mindistancebuffer", "msDrawQueryLayer()");
-        return MS_FAILURE;
-      }
+      colorbuffer = (colorObj*)msSmallMalloc(layer->numclasses*sizeof(colorObj));
+      mindistancebuffer = (int*)msSmallMalloc(layer->numclasses*sizeof(int));
     }
 
     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);
+          msFree(colorbuffer);
+          msFree(mindistancebuffer);
           return(MS_FAILURE);
         }
         if(MS_VALID_COLOR(layer->class[i]->styles[0]->color)) {
@@ -1368,7 +1385,11 @@ int msDrawQueryLayer(mapObj *map, layerObj *layer, imageObj *image)
     }
 
     if(cache) {
-      if(insertFeatureList(&shpcache, &shape) == NULL) return(MS_FAILURE); /* problem adding to the cache */
+      if(insertFeatureList(&shpcache, &shape) == NULL) {
+        msFree(colorbuffer);
+        msFree(mindistancebuffer);
+        return(MS_FAILURE); /* problem adding to the cache */
+      }
     }
 
     maxnumstyles = MS_MAX(maxnumstyles, layer->class[shape.classindex]->numstyles);
@@ -2229,7 +2250,7 @@ int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image,
       } else
         msOffsetPointRelativeTo(point, layer);
 
-      if(labeltext) {
+      if(label) {
         if(layer->labelcache) {
           if(msAddLabel(map, label, layer->index, classindex, NULL, point, NULL, -1) != MS_SUCCESS) return(MS_FAILURE);
         } else {
@@ -2256,7 +2277,7 @@ int msDrawPoint(mapObj *map, layerObj *layer, pointObj *point, imageObj *image,
         if(msScaleInBounds(map->scaledenom, theclass->styles[s]->minscaledenom, theclass->styles[s]->maxscaledenom))
           msDrawMarkerSymbol(&map->symbolset, image, point, theclass->styles[s], layer->scalefactor);
       }
-      if(labeltext) {
+      if(label) {
         if(layer->labelcache) {
           if(msAddLabel(map, label, layer->index, classindex, NULL, point, NULL, -1) != MS_SUCCESS) return(MS_FAILURE);
         } else
diff --git a/mapfile.c b/mapfile.c
index 6e0ae01..5f35c74 100644
--- a/mapfile.c
+++ b/mapfile.c
@@ -137,10 +137,9 @@ void msFree(void *p)
 void msFreeCharArray(char **array, int num_items)
 {
   int i;
-
+  if(!array) return;
   for(i=0; i<num_items; i++)
     msFree(array[i]);
-
   msFree(array);
 }
 
@@ -552,32 +551,38 @@ static void writeCharacter(FILE *stream, int indent, const char *name, const cha
   msIO_fprintf(stream, "%s '%c'\n", name, character);
 }
 
-static void writeString(FILE *stream, int indent, const char *name, const char *defaultString, char *string)
+static void writeStringElement(FILE *stream, char *string)
 {
-  char *string_escaped;
+    char *string_escaped;
+
+    if(strchr(string,'\\')) {
+      string_escaped = msStrdup(string);
+      string_escaped = msReplaceSubstring(string_escaped,"\\","\\\\");
+    } else {
+      string_escaped = string;
+    }
+    if ( (strchr(string_escaped, '\'') == NULL) && (strchr(string_escaped, '\"') == NULL))
+      msIO_fprintf(stream, "\"%s\"", string_escaped);
+    else if ( (strchr(string_escaped, '\"') != NULL) && (strchr(string_escaped, '\'') == NULL))
+      msIO_fprintf(stream, "'%s'", string_escaped);
+    else if ( (strchr(string_escaped, '\'') != NULL) && (strchr(string_escaped, '\"') == NULL))
+      msIO_fprintf(stream, "\"%s\"", string_escaped);
+    else {
+      char *string_tmp = msStringEscape(string_escaped);
+      msIO_fprintf(stream, "\"%s\"", string_tmp);
+      if(string_escaped!=string_tmp) free(string_tmp);
+    }
+    if(string_escaped!=string) free(string_escaped);
+}
 
+static void writeString(FILE *stream, int indent, const char *name, const char *defaultString, char *string)
+{
   if(!string) return;
   if(defaultString && strcmp(string, defaultString) == 0) return;
   writeIndent(stream, ++indent);
   if(name) msIO_fprintf(stream, "%s ", name);
-  if(strchr(string,'\\')) {
-    string_escaped = msStrdup(string);
-    string_escaped = msReplaceSubstring(string_escaped,"\\","\\\\");
-  } else {
-    string_escaped = string;
-  }
-  if ( (strchr(string_escaped, '\'') == NULL) && (strchr(string_escaped, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\n", string_escaped);
-  else if ( (strchr(string_escaped, '\"') != NULL) && (strchr(string_escaped, '\'') == NULL))
-    msIO_fprintf(stream, "'%s'\n", string_escaped);
-  else if ( (strchr(string_escaped, '\'') != NULL) && (strchr(string_escaped, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\n", string_escaped);
-  else {
-    char *string_tmp = msStringEscape(string_escaped);
-    msIO_fprintf(stream, "\"%s\"\n", string_tmp);
-    if(string_escaped!=string_tmp) free(string_tmp);
-  }
-  if(string_escaped!=string) free(string_escaped);
+  writeStringElement(stream, string);
+  writeLineFeed(stream);
 }
 
 static void writeNumberOrString(FILE *stream, int indent, const char *name, double defaultNumber, double number, char *string)
@@ -613,33 +618,13 @@ static void writeNumberOrKeyword(FILE *stream, int indent, const char *name, dou
 
 static void writeNameValuePair(FILE *stream, int indent, const char *name, const char *value)
 {
-  char *string_tmp;
   if(!name || !value) return;
   writeIndent(stream, ++indent);
 
-  if ( (strchr(name, '\'') == NULL) && (strchr(name, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\t", name);
-  else if ( (strchr(name, '\"') != NULL) && (strchr(name, '\'') == NULL))
-    msIO_fprintf(stream, "'%s'\t", name);
-  else if ( (strchr(name, '\'') != NULL) && (strchr(name, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\t", name);
-  else {
-    string_tmp = msStringEscape(name);
-    msIO_fprintf(stream, "\"%s\"\t", string_tmp);
-    if(name!=string_tmp) free(string_tmp);
-  }
-
-  if ( (strchr(value, '\'') == NULL) && (strchr(value, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\n", value);
-  else if ( (strchr(value, '\"') != NULL) && (strchr(value, '\'') == NULL))
-    msIO_fprintf(stream, "'%s'\n", value);
-  else if ( (strchr(value, '\'') != NULL) && (strchr(value, '\"') == NULL))
-    msIO_fprintf(stream, "\"%s\"\n", value);
-  else {
-    string_tmp = msStringEscape(value);
-    msIO_fprintf(stream, "\"%s\"\n", string_tmp);
-    if(value!=string_tmp) free(string_tmp);
-  }
+  writeStringElement(stream, (char*)name);
+  msIO_fprintf(stream,"\t");
+  writeStringElement(stream, (char*)value);
+  writeLineFeed(stream);
 }
 
 static void writeAttributeBinding(FILE *stream, int indent, const char *name, attributeBindingObj *binding)
@@ -824,11 +809,13 @@ featureListNodeObjPtr insertFeatureList(featureListNodeObjPtr *list, shapeObj *s
 {
   featureListNodeObjPtr node;
 
-  node = (featureListNodeObjPtr) malloc(sizeof(featureListNodeObj));
-  MS_CHECK_ALLOC(node, sizeof(featureListNodeObj), NULL);
+  node = (featureListNodeObjPtr) msSmallMalloc(sizeof(featureListNodeObj));
 
   msInitShape(&(node->shape));
-  if(msCopyShape(shape, &(node->shape)) == -1) return(NULL);
+  if(msCopyShape(shape, &(node->shape)) == -1) {
+    msFree(node);
+    return(NULL);
+  }
 
   /* AJS - alans at wunderground.com O(n^2) -> O(n) conversion, keep a pointer to the end */
 
@@ -903,7 +890,6 @@ static int loadFeature(layerObj *player, int type)
 {
   int status=MS_SUCCESS;
   featureListNodeObjPtr *list = &(player->features);
-  featureListNodeObjPtr node;
   multipointObj points= {0,NULL};
   shapeObj *shape=NULL;
 
@@ -917,13 +903,15 @@ static int loadFeature(layerObj *player, int type)
     switch(msyylex()) {
       case(EOF):
         msSetError(MS_EOFERR, NULL, "loadFeature()");
+        msFreeShape(shape); /* clean up */
+        msFree(shape);
         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)
+        if(insertFeatureList(list, shape) == NULL)
           status = MS_FAILURE;
 
         msFreeShape(shape); /* clean up */
@@ -933,17 +921,29 @@ static int loadFeature(layerObj *player, int type)
       case(FEATURE):
         break; /* for string loads */
       case(POINTS):
-        if(loadFeaturePoints(&points) == MS_FAILURE) return(MS_FAILURE); /* no clean up necessary, just return */
+        if(loadFeaturePoints(&points) == MS_FAILURE) {
+          msFreeShape(shape); /* clean up */
+          msFree(shape);
+          return(MS_FAILURE);
+        }
         status = msAddLine(shape, &points);
 
         msFree(points.point); /* clean up */
         points.numpoints = 0;
 
-        if(status == MS_FAILURE) return(MS_FAILURE);
+        if(status == MS_FAILURE) {
+          msFreeShape(shape); /* clean up */
+          msFree(shape);
+          return(MS_FAILURE);
+        }
         break;
       case(ITEMS): {
         char *string=NULL;
-        if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
+        if(getString(&string) == MS_FAILURE) {
+          msFreeShape(shape); /* clean up */
+          msFree(shape);
+          return(MS_FAILURE);
+        }
         if (string) {
           if(shape->values) msFreeCharArray(shape->values, shape->numvalues);
           shape->values = msStringSplit(string, ';', &shape->numvalues);
@@ -952,26 +952,37 @@ static int loadFeature(layerObj *player, int type)
         break;
       }
       case(TEXT):
-        if(getString(&shape->text) == MS_FAILURE) return(MS_FAILURE);
+        if(getString(&shape->text) == MS_FAILURE) {
+          msFreeShape(shape); /* clean up */
+          msFree(shape);
+          return(MS_FAILURE);
+        }
         break;
       case(WKT): {
         char *string=NULL;
 
         /* todo, what do we do with multiple WKT property occurances? */
 
-        if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
         msFreeShape(shape);
         msFree(shape);
+        if(getString(&string) == MS_FAILURE) return(MS_FAILURE);
+        
         if((shape = msShapeFromWKT(string)) == NULL)
           status = MS_FAILURE;
 
         msFree(string); /* clean up */
 
-        if(status == MS_FAILURE) return(MS_FAILURE);
+        if(status == MS_FAILURE) {
+          msFreeShape(shape); /* clean up */
+          msFree(shape);
+          return(MS_FAILURE);
+        }
         break;
       }
       default:
         msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadfeature()", msyystring_buffer, msyylineno);
+        msFreeShape(shape); /* clean up */
+        msFree(shape);
         return(MS_FAILURE);
     }
   } /* next token */
@@ -1383,7 +1394,8 @@ static int loadProjection(projectionObj *p)
 int msLoadProjectionStringEPSG(projectionObj *p, const char *value)
 {
 #ifdef USE_PROJ
-  if(p) msFreeProjection(p);
+  assert(p);
+  msFreeProjection(p);
 
   p->gt.need_geotransform = MS_FALSE;
 #ifdef USE_PROJ_FASTPATHS
@@ -1429,10 +1441,11 @@ int msLoadProjectionStringEPSG(projectionObj *p, const char *value)
 
 int msLoadProjectionString(projectionObj *p, const char *value)
 {
+  assert(p);
   p->gt.need_geotransform = MS_FALSE;
 
 #ifdef USE_PROJ
-  if(p) msFreeProjection(p);
+  msFreeProjection(p);
 
 
   /*
@@ -2428,7 +2441,6 @@ char *msGetExpressionString(expressionObj *exp)
 
 static void writeExpression(FILE *stream, int indent, const char *name, expressionObj *exp)
 {
-  char *string_tmp;
   if(!exp || !exp->string) return;
 
   writeIndent(stream, ++indent);
@@ -2440,17 +2452,8 @@ static void writeExpression(FILE *stream, int indent, const char *name, expressi
       msIO_fprintf(stream, "%s /%s/", name, exp->string);
       break;
     case(MS_STRING):
-      if ( (strchr(exp->string, '\'') == NULL) && (strchr(exp->string, '\"') == NULL))
-        msIO_fprintf(stream, "%s \"%s\"", name, exp->string);
-      else if ( (strchr(exp->string, '\"') != NULL) && (strchr(exp->string, '\'') == NULL))
-        msIO_fprintf(stream, "%s \'%s\'", name, exp->string);
-      else if ( (strchr(exp->string, '\'') != NULL) && (strchr(exp->string, '\"') == NULL))
-        msIO_fprintf(stream, "%s \"%s\"", name, exp->string);
-      else {
-        string_tmp = msStringEscape(exp->string);
-        msIO_fprintf(stream, "%s \"%s\"", name, string_tmp);
-        if(exp->string!=string_tmp) free(string_tmp);
-      }
+      msIO_fprintf(stream, "%s ", name);
+      writeStringElement(stream, exp->string);
       break;
     case(MS_EXPRESSION):
       msIO_fprintf(stream, "%s (%s)", name, exp->string);
@@ -2464,8 +2467,7 @@ static void writeExpression(FILE *stream, int indent, const char *name, expressi
 int loadHashTable(hashTableObj *ptable)
 {
   char *key=NULL, *data=NULL;
-
-  if (!ptable) ptable = msCreateHashTable();
+  assert(ptable);
 
   for(;;) {
     switch(msyylex()) {
@@ -2524,7 +2526,11 @@ static void writeHashTableInline(FILE *stream, int indent, char *name, hashTable
     if (table->items[i] != NULL) {
       for (tp=table->items[i]; tp!=NULL; tp=tp->next) {
         writeIndent(stream, indent);
-        msIO_fprintf(stream, "%s \"%s\" \"%s\"\n", name, tp->key, tp->data);
+        msIO_fprintf(stream, "%s ", name);
+        writeStringElement(stream, tp->key);
+        msIO_fprintf(stream," ");
+        writeStringElement(stream, tp->data);
+        writeLineFeed(stream);
       }
     }
   }
@@ -3398,7 +3404,7 @@ void resetClassStyle(classObj *class)
 
   /* reset labels */
   for(i=0; i<class->numlabels; i++) {
-    if(class->styles[i] != NULL) {
+    if(class->labels[i] != NULL) {
       if(freeLabel(class->labels[i]) == MS_SUCCESS ) {
         msFree(class->labels[i]);
       }
@@ -4935,7 +4941,7 @@ static int loadOutputFormat(mapObj *map)
     switch(msyylex()) {
       case(EOF):
         msSetError(MS_EOFERR, NULL, "loadOutputFormat()");
-        return(-1);
+        goto load_output_error;
 
       case(END): {
         outputFormatObj *format;
@@ -4945,29 +4951,32 @@ static int loadOutputFormat(mapObj *map)
                      "OUTPUTFORMAT clause lacks DRIVER keyword near (%s):(%d)",
                      "loadOutputFormat()",
                      msyystring_buffer, msyylineno );
-          return -1;
+          goto load_output_error;
         }
 
         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;
+                     "OUTPUTFORMAT (%s) clause references driver (%s), but this driver isn't configured.",
+                     "loadOutputFormat()", name, driver );
+          goto load_output_error;
         }
+        msFree( name );
+        name = NULL;
         msFree( driver );
+        driver = NULL;
 
         if( transparent != MS_NOOVERRIDE )
           format->transparent = transparent;
         if( extension != NULL ) {
           msFree( format->extension );
           format->extension = extension;
+          extension = NULL;
         }
         if( mimetype != NULL ) {
           msFree( format->mimetype );
           format->mimetype = mimetype;
+          mimetype = NULL;
         }
         if( imagemode != MS_NOOVERRIDE ) {
 #ifndef USE_GD
@@ -5007,14 +5016,18 @@ static int loadOutputFormat(mapObj *map)
       }
       case(NAME):
         msFree( name );
-        if((name = getToken()) == NULL) return(-1);
+        if((name = getToken()) == NULL) 
+          goto load_output_error;
         break;
       case(MIMETYPE):
-        if(getString(&mimetype) == MS_FAILURE) return(-1);
+        if(getString(&mimetype) == MS_FAILURE)
+          goto load_output_error;
         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 = getSymbol(2, MS_STRING, TEMPLATE)) == -1) /* allow the template to be quoted or not in the mapfile */
+          goto load_output_error;
+        free(driver);
         if(s == MS_STRING)
           driver = msStrdup(msyystring_buffer);
         else
@@ -5022,7 +5035,8 @@ static int loadOutputFormat(mapObj *map)
       }
       break;
       case(EXTENSION):
-        if(getString(&extension) == MS_FAILURE) return(-1);
+        if(getString(&extension) == MS_FAILURE)
+          goto load_output_error;
         if( extension[0] == '.' ) {
           char *temp = msStrdup(extension+1);
           free( extension );
@@ -5030,7 +5044,8 @@ static int loadOutputFormat(mapObj *map)
         }
         break;
       case(FORMATOPTION):
-        if(getString(&value) == MS_FAILURE) return(-1);
+        if(getString(&value) == MS_FAILURE)
+          goto load_output_error;
         if( numformatoptions < MAX_FORMATOPTIONS )
           formatoptions[numformatoptions++] = msStrdup(value);
         free(value);
@@ -5056,20 +5071,28 @@ static int loadOutputFormat(mapObj *map)
           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;
+          goto load_output_error;
         }
         free(value);
         value=NULL;
         break;
       case(TRANSPARENT):
-        if((transparent = getSymbol(2, MS_ON,MS_OFF)) == -1) return(-1);
+        if((transparent = getSymbol(2, MS_ON,MS_OFF)) == -1)
+          goto load_output_error;
         break;
       default:
         msSetError(MS_IDENTERR, "Parsing error near (%s):(line %d)", "loadOutputFormat()",
                    msyystring_buffer, msyylineno);
-        return(-1);
+        goto load_output_error;
     }
   } /* next token */
+load_output_error:
+  msFree( driver );
+  msFree( extension );
+  msFree( mimetype );
+  msFree( name );
+  msFree( value );
+  return -1;
 }
 
 /*
@@ -5464,7 +5487,7 @@ int loadQueryMap(queryMapObj *querymap)
       case(QUERYMAP):
         break; /* for string loads */
       case(COLOR):
-        loadColor(&(querymap->color), NULL);
+        if(loadColor(&(querymap->color), NULL) != MS_SUCCESS) return MS_FAILURE;
         break;
       case(EOF):
         msSetError(MS_EOFERR, NULL, "loadQueryMap()");
@@ -6521,11 +6544,11 @@ mapObj *msLoadMap(char *filename, char *new_mappath)
   }
 
   if (new_mappath)
-    map->mappath = msStrdup(msBuildPath(szPath, szCWDPath, msStrdup(new_mappath)));
+    map->mappath = msStrdup(msBuildPath(szPath, szCWDPath, new_mappath));
   else {
     char *path = msGetPath(filename);
     map->mappath = msStrdup(msBuildPath(szPath, szCWDPath, path));
-    if( path ) free( path );
+    free( path );
   }
 
   msyybasepath = map->mappath; /* for INCLUDEs */
@@ -7100,8 +7123,12 @@ static char **tokenizeMapInternal(char *filename, int *ret_numtokens)
     }
 
     if(tokens[numtokens] == NULL) {
+      int i;
       msSetError(MS_MEMERR, NULL, "msTokenizeMap()");
       fclose(msyyin);
+      for(i=0; i<numtokens; i++)
+        msFree(tokens[i]);
+      msFree(tokens);
       return NULL;
     }
 
diff --git a/mapgd.c b/mapgd.c
index 3d304c8..55db072 100644
--- a/mapgd.c
+++ b/mapgd.c
@@ -582,7 +582,7 @@ symbolObj* rotateVectorSymbolPoints(symbolObj *symbol, double 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) ) {
+    if ((symbol->points[i].x == -99.0) && (symbol->points[i].y == -99.0) ) {
       newSymbol->points[i].x = -99.0;
       newSymbol->points[i].y = -99.0;
       continue;
@@ -598,7 +598,7 @@ symbolObj* rotateVectorSymbolPoints(symbolObj *symbol, double angle_rad)
     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))
+      if ((newSymbol->points[i].x == -99.0) && (newSymbol->points[i].y == -99.0))
         continue;
       newSymbol->points[i].x = newSymbol->points[i].x + xcor;
       newSymbol->points[i].y = newSymbol->points[i].y + ycor;
@@ -651,7 +651,7 @@ int renderVectorSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, s
 
     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((symbol->points[j].x == -99) && (symbol->points[j].y == -99)) { /* new polygon (PENUP) */
         if(k>2) {
           if(fc >= 0)
             gdImageFilledPolygon(ip, mPoints, k, fc);
@@ -681,7 +681,7 @@ int renderVectorSymbolGD(imageObj *img, double x, double y, symbolObj *symbol, s
     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].x != -99) || (symbol->points[j].y != -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);
@@ -1010,7 +1010,7 @@ int renderBitmapGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style
   }
 
 
-  if(*lines != text)
+  if(lines != &text)
     msFreeCharArray(lines, numlines);
   return MS_SUCCESS;
 }
diff --git a/mapgeos.c b/mapgeos.c
index c319a66..e06c4d6 100644
--- a/mapgeos.c
+++ b/mapgeos.c
@@ -269,14 +269,17 @@ static GEOSGeom msGEOSShape2Geometry_simplepolygon(shapeObj *shape, int r, int *
   if(numInnerRings > 0) {
     k = 0; /* inner ring counter */
 
-    innerRings = malloc(numInnerRings*sizeof(GEOSGeom));
-    if(!innerRings) return NULL; /* todo, this will leak memory (outerRing) */
+    innerRings = msSmallMalloc(numInnerRings*sizeof(GEOSGeom));
 
     for(j=0; j<shape->numlines; j++) {
       if(innerList[j] == MS_FALSE) continue;
 
       coords = GEOSCoordSeq_create_r(handle,shape->line[j].numpoints, 2); /* todo handle z's */
-      if(!coords) return NULL; /* todo, this will leak memory (shell + allocated holes) */
+      if(!coords) {
+        free(innerRings);
+        free(innerList);
+        return NULL; /* todo, this will leak memory (shell + allocated holes) */
+      }
 
       for(i=0; i<shape->line[j].numpoints; i++) {
         GEOSCoordSeq_setX_r(handle,coords, i, shape->line[j].point[i].x);
@@ -316,8 +319,7 @@ static GEOSGeom msGEOSShape2Geometry_polygon(shapeObj *shape)
   if(numOuterRings == 1) {
     g = msGEOSShape2Geometry_simplepolygon(shape, lastOuterRing, outerList);
   } else { /* a true multipolygon */
-    polygons = malloc(numOuterRings*sizeof(GEOSGeom));
-    if(!polygons) return NULL;
+    polygons = msSmallMalloc(numOuterRings*sizeof(GEOSGeom));
 
     j = 0; /* part counter */
     for(i=0; i<shape->numlines; i++) {
diff --git a/mapgml.c b/mapgml.c
index dcbd271..5011349 100644
--- a/mapgml.c
+++ b/mapgml.c
@@ -123,7 +123,7 @@ static void gmlEndGeometryContainer(FILE *stream, char *name, char *namespace, c
 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;
+  int *innerlist, *outerlist=NULL, numouters;
   char *srsname_encoded = NULL;
 
   int geometry_aggregate_index, geometry_simple_index;
@@ -311,6 +311,7 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
           gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
         }
         free(outerlist);
+        outerlist = NULL;
       } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiPolygon */
         gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
@@ -362,6 +363,7 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
         msIO_fprintf(stream, "%s</gml:MultiPolygon>\n", tab);
 
         free(outerlist);
+        outerlist = NULL;
 
         gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
       } else {
@@ -375,6 +377,7 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
 
   /* clean-up */
   msFree(srsname_encoded);
+  msFree(outerlist);
 
   return(MS_SUCCESS);
 }
@@ -383,7 +386,7 @@ static int gmlWriteGeometry_GML2(FILE *stream, gmlGeometryListObj *geometryList,
 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;
+  int *innerlist, *outerlist=NULL, numouters;
   char *srsname_encoded = NULL;
 
   int geometry_aggregate_index, geometry_simple_index;
@@ -571,6 +574,7 @@ static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList,
           gmlEndGeometryContainer(stream, geometry_simple_name, namespace, tab);
         }
         free(outerlist);
+        outerlist = NULL;
       } else if(geometry_aggregate_index != -1 || (geometryList->numgeometries == 0)) { /* write a MultiSurface */
         gmlStartGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
 
@@ -624,6 +628,7 @@ static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList,
         msIO_fprintf(stream, "%s  </gml:MultiSurface>\n", tab);
 
         free(outerlist);
+        outerlist = NULL;
 
         gmlEndGeometryContainer(stream, geometry_aggregate_name, namespace, tab);
       } else {
@@ -636,6 +641,7 @@ static int gmlWriteGeometry_GML3(FILE *stream, gmlGeometryListObj *geometryList,
   }
 
   /* clean-up */
+  msFree(outerlist);
   msFree(srsname_encoded);
 
   return(MS_SUCCESS);
@@ -767,6 +773,7 @@ gmlGeometryListObj *msGMLGetGeometries(layerObj *layer, const char *metadata_nam
           else
             geometry->occurmax = atof(occur[1]);
         }
+        msFreeCharArray(occur,numoccur);
       }
     }
 
@@ -1117,6 +1124,7 @@ static void msGMLWriteGroup(FILE *stream, gmlGroupObj *group, shapeObj *shape, g
   else
     msIO_fprintf(stream, "%s</%s>\n", tab, group->name);
 
+  free(itemtab);
   return;
 }
 #endif
@@ -1211,7 +1219,13 @@ int msGMLWriteQuery(mapObj *map, char *filename, const char *namespaces)
 
       for(j=0; j<lp->resultcache->numresults; j++) {
         status = msLayerGetShape(lp, &shape, &(lp->resultcache->results[j]));
-        if(status != MS_SUCCESS) return(status);
+        if(status != MS_SUCCESS) {
+           msGMLFreeGroups(groupList);
+           msGMLFreeConstants(constantList);
+           msGMLFreeItems(itemList);
+           msGMLFreeGeometries(geometryList);
+           return(status);
+        }
 
 #ifdef USE_PROJ
         /* project the shape into the map projection (if necessary), note that this projects the bounds as well */
@@ -1446,8 +1460,14 @@ int msGMLWriteWFSQuery(mapObj *map, FILE *stream, char *default_namespace_prefix
       for(j=0; j<lp->resultcache->numresults; j++) {
 
         status = msLayerGetShape(lp, &shape, &(lp->resultcache->results[j]));
-        if(status != MS_SUCCESS)
+        if(status != MS_SUCCESS) {
+          msGMLFreeGroups(groupList);
+          msGMLFreeConstants(constantList);
+          msGMLFreeItems(itemList);
+          msGMLFreeGeometries(geometryList);
+          msFree(layerName);
           return(status);
+        }
 
 #ifdef USE_PROJ
         /* project the shape into the map projection (if necessary), note that this projects the bounds as well */
diff --git a/mapgraticule.c b/mapgraticule.c
index 60e114b..498e454 100644
--- a/mapgraticule.c
+++ b/mapgraticule.c
@@ -661,7 +661,9 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
     msProjectRect(&map->projection, &layer->projection, &searchrect); /* project the searchrect to source coords */
 #endif
 
-  msLayerOpen(layer);
+ status =  msLayerOpen(layer);
+ if(status != MS_SUCCESS)
+   return NULL;
 
   status = msLayerWhichShapes(layer, searchrect, MS_FALSE);
   if(status == MS_DONE) { /* no overlap */
@@ -783,8 +785,10 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
               if (psValues->pasBottom[i].x == oFirstPoint.x)
                 break;
             }
-            if (i  < psValues->nBottom)
+            if (i  < psValues->nBottom) {
+              msFree(pszLabel);
               continue;
+            }
           }
           if (psValues->pasBottom == NULL) {
             psValues->pasBottom = (pointObj *)msSmallMalloc(sizeof(pointObj));
@@ -798,9 +802,7 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
 
           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);
+          psValues->papszBottomLabels[psValues->nBottom-1] = pszLabel;
 
         }
         /*first point should cross the TOP base where y==0*/
@@ -831,8 +833,10 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
                   strcasecmp(pszLabel, psValues->papszTopLabels[i]) == 0)
                 break;
             }
-            if (i < psValues->nTop)
+            if (i < psValues->nTop) {
+              msFree(pszLabel);
               continue;
+            }
           }
 
 
@@ -848,9 +852,7 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
 
           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);
+          psValues->papszTopLabels[psValues->nTop-1] = pszLabel;
         }
       } else { /*horzontal*/
         /*Normally lines are drawn from left to right but not always for some reason, so
@@ -893,8 +895,10 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
               if (psValues->pasLeft[i].y == oFirstPoint.y)
                 break;
             }
-            if (i < psValues->nLeft)
+            if (i < psValues->nLeft) {
+              msFree(pszLabel);
               continue;
+            }
           }
           if (psValues->pasLeft == NULL) {
             psValues->pasLeft = (pointObj *)msSmallMalloc(sizeof(pointObj));
@@ -908,8 +912,7 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
 
           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);
+          psValues->papszLeftLabels[psValues->nLeft-1] = pszLabel; /* takes ownership of allocated pszLabel */
         }
         /*first point should cross the RIGHT base where x=map=>width axis*/
         if (abs((int)oLastPoint.x - map->width) <=1) {
@@ -938,8 +941,10 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
               if (psValues->pasRight[i].y == oLastPoint.y)
                 break;
             }
-            if (i < psValues->nRight)
+            if (i < psValues->nRight) {
+              msFree(pszLabel);
               continue;
+            }
           }
           if (psValues->pasRight == NULL) {
             psValues->pasRight = (pointObj *)msSmallMalloc(sizeof(pointObj));
@@ -953,9 +958,7 @@ graticuleIntersectionObj *msGraticuleLayerGetIntersectionPoints(mapObj *map,
 
           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);
+          psValues->papszRightLabels[psValues->nRight-1] = pszLabel;
         }
       }
       msFreeShape(&shapegrid);
diff --git a/maphash.c b/maphash.c
index d6dd3e0..c548602 100644
--- a/maphash.c
+++ b/maphash.c
@@ -105,7 +105,6 @@ void msFreeHashItems( hashTableObj *table )
             msFree(tp->data);
           }
         }
-        if (tp) free(tp);
       }
       free(table->items);
       table->items = NULL;
diff --git a/maphttp.c b/maphttp.c
index 9f21a5b..e7a1801 100644
--- a/maphttp.c
+++ b/maphttp.c
@@ -373,6 +373,8 @@ int msHTTPAuthProxySetup(hashTableObj *mapmd, hashTableObj *lyrmd,
                                      "proxy_password")) != NULL) {
     pszProxyPassword = msDecryptStringTokens(map, pszTmp);
     if (pszProxyPassword == NULL) {
+      msFree(pszProxyHost);
+      msFree(pszProxyUsername);
       return(MS_FAILURE);  /* An error should already have been produced */
     }
   }
@@ -405,6 +407,10 @@ int msHTTPAuthProxySetup(hashTableObj *mapmd, hashTableObj *lyrmd,
                                      "auth_password")) != NULL) {
     pszHttpAuthPassword = msDecryptStringTokens(map, pszTmp);
     if (pszHttpAuthPassword == NULL) {
+      msFree(pszHttpAuthUsername);
+      msFree(pszProxyHost);
+      msFree(pszProxyUsername);
+      msFree(pszProxyPassword);
       return(MS_FAILURE);  /* An error should already have been produced */
     }
   }
diff --git a/mapimageio.c b/mapimageio.c
index 08b4d6f..35d134f 100644
--- a/mapimageio.c
+++ b/mapimageio.c
@@ -741,17 +741,21 @@ int readPNG(char *path, rasterBufferObj *rb)
 
   /* 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)
+  if (!png_ptr) {
+    fclose(stream);
     return MS_FAILURE;   /* out of memory */
+  }
 
   info_ptr = png_create_info_struct(png_ptr);
   if (!info_ptr) {
     png_destroy_read_struct(&png_ptr, NULL, NULL);
+    fclose(stream);
     return MS_FAILURE;   /* out of memory */
   }
 
   if(setjmp(png_jmpbuf(png_ptr))) {
     png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
+    fclose(stream);
     return MS_FAILURE;
   }
 
@@ -1120,7 +1124,7 @@ int readGIF(char *path, rasterBufferObj *rb)
   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*));
+  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];
diff --git a/mapimagemap.c b/mapimagemap.c
index 5f38436..f233403 100644
--- a/mapimagemap.c
+++ b/mapimagemap.c
@@ -260,73 +260,69 @@ imageObj *msImageCreateIM(int width, int height, outputFormatObj *format,
   };
   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, "");
-      }
+    image = (imageObj *)msSmallCalloc(1,sizeof(imageObj));
+    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;
 
-      /* 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;
-      }
+    if( strcasecmp("ON",msGetOutputFormatOption( format, "SCRIPT", "OFF" )) == 0) {
+      dxf = 2;
+      im_iprintf(&layerStr, "");
+    }
 
-      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);
-      }
+    /* 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;
+    }
 
-      return image;
-    } else
-      free( image );
+    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 {
     msSetError(MS_IMGERR,
                "Cannot create IM image of size %d x %d.",
diff --git a/mapio.c b/mapio.c
index 0861213..88782bc 100644
--- a/mapio.c
+++ b/mapio.c
@@ -145,6 +145,23 @@ static msIOContextGroup *msIO_GetContextGroup()
   return group;
 }
 
+/* returns MS_TRUE if the msIO standard output hasn't been redirected */
+int msIO_isStdContext() {
+  msIOContextGroup *group = io_context_list;
+  int nThreadId = msGetThreadId();
+  if(!group || group->thread_id != nThreadId) {
+    group = msIO_GetContextGroup();
+    if(!group) {
+      return MS_FALSE; /* probably a bug */
+    }
+  }
+  if(group->stderr_context.cbData == (void*)stderr &&
+      group->stdin_context.cbData == (void*)stdin &&
+      group->stdout_context.cbData == (void*)stdout)
+    return MS_TRUE;
+  return MS_FALSE;
+}
+
 /************************************************************************/
 /*                          msIO_getHandler()                           */
 /************************************************************************/
@@ -201,6 +218,7 @@ void msIO_setHeader (const char *header, const char* value, ...)
 #ifdef MOD_WMS_ENABLED
   }
 #endif
+  va_end( args );
 }
 
 void msIO_sendHeaders ()
diff --git a/mapio.h b/mapio.h
index b5faef2..b6fe137 100644
--- a/mapio.h
+++ b/mapio.h
@@ -108,6 +108,7 @@ extern "C" {
   void MS_DLL_EXPORT msIO_Cleanup(void);
   char MS_DLL_EXPORT *msIO_stripStdoutBufferContentType(void);
   void MS_DLL_EXPORT msIO_stripStdoutBufferContentHeaders(void);
+  int MS_DLL_EXPORT msIO_isStdContext(void);
 
   /* this is just for setting normal stdout's to binary mode on windows */
 
diff --git a/mapkmlrenderer.cpp b/mapkmlrenderer.cpp
index 9192749..3c1e198 100644
--- a/mapkmlrenderer.cpp
+++ b/mapkmlrenderer.cpp
@@ -373,6 +373,7 @@ int KmlRenderer::startNewLayer(imageObj *img, layerObj *layer)
   if (!msLayerIsOpen(layer)) {
     if (msLayerOpen(layer) != MS_SUCCESS) {
       msSetError(MS_MISCERR, "msLayerOpen failed", "KmlRenderer::startNewLayer" );
+      return MS_FAILURE;
     }
   }
 
@@ -404,7 +405,9 @@ int KmlRenderer::startNewLayer(imageObj *img, layerObj *layer)
     pszLayerNameAttributeMetadata = msLookupHashTable(&layer->metadata, "kml_name_item");
 
   /*get all attributes*/
-  msLayerWhichItems(layer, MS_TRUE, NULL);
+  if(msLayerWhichItems(layer, MS_TRUE, NULL) != MS_SUCCESS) {
+    return MS_FAILURE;
+  }
 
 
   NumItems = layer->numitems;
@@ -900,14 +903,12 @@ void KmlRenderer::startShape(imageObj *, shapeObj *shape)
     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;
-        }
+  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;
       }
     }
   }
diff --git a/maplabel.c b/maplabel.c
index dbda6d6..7641715 100644
--- a/maplabel.c
+++ b/maplabel.c
@@ -334,7 +334,7 @@ int msAddLabelGroup(mapObj *map, int layerindex, int classindex, shapeObj *shape
     }
   }
 
-  if (layerPtr->type == MS_LAYER_ANNOTATION && (cachePtr->numlabels > 1 || classPtr->leader.maxdistance)) {
+  if (layerPtr->type == MS_LAYER_ANNOTATION && (classPtr->numlabels > 1 || classPtr->leader.maxdistance)) {
     msSetError(MS_MISCERR, "Multiple Labels and/or LEADERs are not supported with annotation layers", "msAddLabelGroup()");
     return MS_FAILURE;
   }
@@ -1025,7 +1025,7 @@ int msGetTruetypeTextBBox(rendererVTableObj *renderer, char* fontstring, fontSet
   char *lookedUpFonts[MS_MAX_LABEL_FONTS];
   int numfonts;
   if(!renderer) {
-    outputFormatObj *format = msCreateDefaultOutputFormat(NULL,"AGG/PNG","tmp");
+    format = msCreateDefaultOutputFormat(NULL,"AGG/PNG","tmp");
     if(!format) {
       goto tt_cleanup;
     }
@@ -1158,6 +1158,11 @@ int msGetLabelSize(mapObj *map, labelObj *label, char *string, double size, rect
   if (map)
     renderer =MS_MAP_RENDERER(map);
 
+  if(!renderer) {
+    msSetError(MS_MISCERR, "cannot compute label size without valid map and renderer", "msGetLabelSize()");
+    return MS_FAILURE;
+  }
+
   if(label->type == MS_TRUETYPE) {
     if(!label->font) {
       msSetError(MS_MISCERR, "label has no true type font", "msGetLabelSize()");
diff --git a/maplayer.c b/maplayer.c
index 93c562f..bab99c4 100644
--- a/maplayer.c
+++ b/maplayer.c
@@ -684,14 +684,14 @@ 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)) {
-    msLayerGetItems(layer);
+    rv = 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));
   } else {
     rv = layer->vtable->LayerCreateItems(layer, nt);
-    if(rv != MS_SUCCESS)
-      return rv;
   }
+  if(rv != MS_SUCCESS)
+    return rv;
 
   /*
   ** build layer item list, compute item indexes for explicity item references (e.g. classitem) or item bindings
@@ -1089,100 +1089,39 @@ makeTimeFilter(layerObj *lp,
   }
 
   atimes = msStringSplit(timestring, ',', &numtimes);
-  if (atimes == NULL || numtimes < 1)
+  if (atimes == NULL || numtimes < 1) {
+    msFreeCharArray(atimes,numtimes);
     return MS_FALSE;
+  }
 
-  if (numtimes >= 1) {
-    if (&lp->filter && lp->filter.string && lp->filter.type == MS_STRING) {
-      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;
-
+  if (&lp->filter && lp->filter.string && lp->filter.type == MS_STRING) {
+    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, "(");
-          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 ");
+        bOnlyExistingFilter = 0;
 
         pszBuffer = msStringConcatenate(pszBuffer, "(");
         if (addtimebacktics)
-          pszBuffer = msStringConcatenate(pszBuffer, "`");
+          pszBuffer = msStringConcatenate(pszBuffer,  "`");
 
         if (addtimebacktics)
           pszBuffer = msStringConcatenate(pszBuffer, "[");
@@ -1191,50 +1130,108 @@ makeTimeFilter(layerObj *lp,
           pszBuffer = msStringConcatenate(pszBuffer, "]");
 
         if (addtimebacktics)
-          pszBuffer = msStringConcatenate(pszBuffer, "`");
+          pszBuffer = msStringConcatenate(pszBuffer,  "`");
 
-        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, "`");
+          pszBuffer = msStringConcatenate(pszBuffer,  "`");
         else
           pszBuffer = msStringConcatenate(pszBuffer,  "'");
-        pszBuffer = msStringConcatenate(pszBuffer, atimes[i]);
+        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, ")");
       }
-      pszBuffer = msStringConcatenate(pszBuffer, ")");
-    } else {
-      msFreeCharArray(atimes, numtimes);
-      return MS_FALSE;
+
+      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(tokens, ntmp);
     msFreeCharArray(atimes, numtimes);
+    msFree(pszBuffer);
+    return MS_FALSE;
+  }
 
-    /* load the string to the filter */
-    if (pszBuffer && strlen(pszBuffer) > 0) {
-      if(&lp->filter && lp->filter.string && lp->filter.type == MS_STRING)
-        pszBuffer = msStringConcatenate(pszBuffer, ")");
-      /*
-      if(lp->filteritem)
-        free(lp->filteritem);
-      lp->filteritem = msStrdup(timefield);
-      */
-
-      loadExpressionString(&lp->filter, pszBuffer);
+  msFreeCharArray(atimes, numtimes);
 
-      if (pszBuffer)
-        msFree(pszBuffer);
-    }
+  /* load the string to the filter */
+  if (pszBuffer && strlen(pszBuffer) > 0) {
+    if(&lp->filter && lp->filter.string && lp->filter.type == MS_STRING)
+      pszBuffer = msStringConcatenate(pszBuffer, ")");
+    /*
+    if(lp->filteritem)
+      free(lp->filteritem);
+    lp->filteritem = msStrdup(timefield);
+    */
 
-    return MS_TRUE;
+    loadExpressionString(&lp->filter, pszBuffer);
 
   }
-
-  return MS_FALSE;
+  msFree(pszBuffer);
+  return MS_TRUE;
 }
 
 /**
diff --git a/maplegend.c b/maplegend.c
index d8b82f7..39002b9 100644
--- a/maplegend.c
+++ b/maplegend.c
@@ -220,7 +220,7 @@ int msDrawLegendIcon(mapObj *map, layerObj *lp, classObj *theclass,
           imgStyle.maxsize = imgStyle.size;
 
         imgStyle.symbol = symbolNum;
-        msDrawMarkerSymbol(&map->symbolset,image_draw,&marker,&imgStyle,lp->scalefactor * image_draw->resolutionfactor);
+        msDrawMarkerSymbol(&map->symbolset,image_draw,&marker,&imgStyle,1.0);
         /* 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++) {
@@ -677,8 +677,16 @@ imageObj *msDrawLegend(mapObj *map, int scale_independent, map_hittest *hittest)
     if(hittest) {
       ch = &hittest->layerhits[cur->layerindex].classhits[cur->classindex];
     }
-    if(msDrawLegendIcon(map, map->layers[cur->layerindex], map->layers[cur->layerindex]->class[cur->classindex],  map->legend.keysizex,  map->legend.keysizey, image, HMARGIN, (int) pnt.y, scale_independent, ch) != MS_SUCCESS)
-      return NULL;
+    if(msDrawLegendIcon(map, map->layers[cur->layerindex], map->layers[cur->layerindex]->class[cur->classindex],  map->legend.keysizex,  map->legend.keysizey, image, HMARGIN, (int) pnt.y, scale_independent, ch) != MS_SUCCESS) {
+      while(cur) {
+        /* clean up */
+        free(cur->transformedText);
+        head = cur;
+        cur = cur->pred;
+        free(head);
+        return NULL;
+      }
+    }
 
     /*
      * adjust the baseline for multiline truetype labels. the label point is the bottom left
@@ -747,7 +755,10 @@ int msEmbedLegend(mapObj *map, imageObj *img)
 
   /* render the legend. */
   image = msDrawLegend(map, MS_FALSE, NULL);
-  if( image == NULL ) return -1;
+  if( image == NULL ) {
+    msFree(imageType);
+    return -1;
+  }
 
   if (imageType) {
     map->outputformat = msSelectOutputFormat( map, imageType ); /* restore format */
diff --git a/maplexer.c b/maplexer.c
index 8b54b19..5da14f5 100644
--- a/maplexer.c
+++ b/maplexer.c
@@ -1,6 +1,6 @@
-#line 2 "/home/even/mapserver/git/mapserver/maplexer.c"
+#line 2 "/home/tbonfort/dev/mapserver/maplexer.c"
 
-#line 4 "/home/even/mapserver/git/mapserver/maplexer.c"
+#line 4 "/home/tbonfort/dev/mapserver/maplexer.c"
 
 #define  YY_INT_ALIGNED short int
 
@@ -2106,8 +2106,8 @@ int msyy_flex_debug = 0;
 #define YY_MORE_ADJ 0
 #define YY_RESTORE_YY_MORE_OFFSET
 char *msyytext;
-#line 1 "/home/even/mapserver/git/mapserver/maplexer.l"
-#line 2 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 1 "/home/tbonfort/dev/mapserver/maplexer.l"
+#line 2 "/home/tbonfort/dev/mapserver/maplexer.l"
 /*
 ** READ ME FIRST!
 **
@@ -2188,7 +2188,7 @@ char path[MS_MAXPATHLEN];
 
 
 
-#line 2192 "/home/even/mapserver/git/mapserver/maplexer.c"
+#line 2192 "/home/tbonfort/dev/mapserver/maplexer.c"
 
 #define INITIAL 0
 #define URL_VARIABLE 1
@@ -2372,7 +2372,7 @@ YY_DECL
 	register char *yy_cp, *yy_bp;
 	register int yy_act;
     
-#line 85 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 85 "/home/tbonfort/dev/mapserver/maplexer.l"
 
        if (msyystring_buffer == NULL)
            msyystring_buffer = (char*) msSmallMalloc(sizeof(char) * msyystring_buffer_size);
@@ -2446,7 +2446,7 @@ YY_DECL
          break;
        }
 
-#line 2450 "/home/even/mapserver/git/mapserver/maplexer.c"
+#line 2450 "/home/tbonfort/dev/mapserver/maplexer.c"
 
 	if ( !(yy_init) )
 		{
@@ -2531,1532 +2531,1532 @@ do_action:	/* This label is used only to access EOF actions. */
 
 case 1:
 YY_RULE_SETUP
-#line 158 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 158 "/home/tbonfort/dev/mapserver/maplexer.l"
 ;
 	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 160 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 160 "/home/tbonfort/dev/mapserver/maplexer.l"
 { if (msyyreturncomments) return(MS_COMMENT); }
 	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 162 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 162 "/home/tbonfort/dev/mapserver/maplexer.l"
 ;
 	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 164 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 164 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_LOGICAL_OR); }
 	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 165 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 165 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_LOGICAL_AND); }
 	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 166 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 166 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_LOGICAL_NOT); }
 	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 167 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 167 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_EQ); }
 	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 168 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 168 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_NE); }
 	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 169 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 169 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_GT); }
 	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 170 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 170 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_LT); }
 	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 171 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 171 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_GE); }
 	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 172 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 172 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_LE); }
 	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 173 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 173 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_RE); }
 	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 175 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 175 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_IEQ); }
 	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 176 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 176 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_IRE); }
 	YY_BREAK
 case 16:
 YY_RULE_SETUP
-#line 178 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 178 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IN); }
 	YY_BREAK
 case 17:
 YY_RULE_SETUP
-#line 180 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 180 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_AREA); }
 	YY_BREAK
 case 18:
 YY_RULE_SETUP
-#line 181 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 181 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_LENGTH); }
 	YY_BREAK
 case 19:
 YY_RULE_SETUP
-#line 182 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 182 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_TOSTRING); }
 	YY_BREAK
 case 20:
 YY_RULE_SETUP
-#line 183 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 183 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_COMMIFY); }
 	YY_BREAK
 case 21:
 YY_RULE_SETUP
-#line 184 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 184 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_ROUND); }
 	YY_BREAK
 case 22:
 YY_RULE_SETUP
-#line 186 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 186 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_BUFFER); }
 	YY_BREAK
 case 23:
 YY_RULE_SETUP
-#line 187 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 187 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_DIFFERENCE); }
 	YY_BREAK
 case 24:
 YY_RULE_SETUP
-#line 188 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 188 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_SIMPLIFY); }
 	YY_BREAK
 case 25:
 YY_RULE_SETUP
-#line 189 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 189 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_SIMPLIFYPT); }
 	YY_BREAK
 case 26:
 YY_RULE_SETUP
-#line 190 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 190 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_GENERALIZE); }
 	YY_BREAK
 case 27:
 YY_RULE_SETUP
-#line 191 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 191 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_SMOOTHSIA); }
 	YY_BREAK
 case 28:
 YY_RULE_SETUP
-#line 193 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 193 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_INTERSECTS); }
 	YY_BREAK
 case 29:
 YY_RULE_SETUP
-#line 194 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 194 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DISJOINT); }
 	YY_BREAK
 case 30:
 YY_RULE_SETUP
-#line 195 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 195 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_TOUCHES); }
 	YY_BREAK
 case 31:
 YY_RULE_SETUP
-#line 196 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 196 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_OVERLAPS); }
 	YY_BREAK
 case 32:
 YY_RULE_SETUP
-#line 197 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 197 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CROSSES); }
 	YY_BREAK
 case 33:
 YY_RULE_SETUP
-#line 198 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 198 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_WITHIN); }
 	YY_BREAK
 case 34:
 YY_RULE_SETUP
-#line 199 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 199 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_CONTAINS); }
 	YY_BREAK
 case 35:
 YY_RULE_SETUP
-#line 200 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 200 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_BEYOND); }
 	YY_BREAK
 case 36:
 YY_RULE_SETUP
-#line 201 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 201 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_COMPARISON_DWITHIN); }
 	YY_BREAK
 case 37:
 YY_RULE_SETUP
-#line 203 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 203 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TOKEN_FUNCTION_FROMTEXT); }
 	YY_BREAK
 case 38:
 YY_RULE_SETUP
-#line 205 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 205 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(COLORRANGE); }
 	YY_BREAK
 case 39:
 YY_RULE_SETUP
-#line 206 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 206 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DATARANGE); }
 	YY_BREAK
 case 40:
 YY_RULE_SETUP
-#line 207 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 207 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(RANGEITEM); }
 	YY_BREAK
 case 41:
 YY_RULE_SETUP
-#line 209 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 209 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ALIGN); }
 	YY_BREAK
 case 42:
 YY_RULE_SETUP
-#line 210 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 210 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ANCHORPOINT); }
 	YY_BREAK
 case 43:
 YY_RULE_SETUP
-#line 211 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 211 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ANGLE); }
 	YY_BREAK
 case 44:
 YY_RULE_SETUP
-#line 212 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 212 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ANTIALIAS); }
 	YY_BREAK
 case 45:
 YY_RULE_SETUP
-#line 213 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 213 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(BACKGROUNDCOLOR); }
 	YY_BREAK
 case 46:
 YY_RULE_SETUP
-#line 214 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 214 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(BANDSITEM); }
 	YY_BREAK
 case 47:
 YY_RULE_SETUP
-#line 215 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 215 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(BINDVALS); }
 	YY_BREAK
 case 48:
 YY_RULE_SETUP
-#line 216 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 216 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(BROWSEFORMAT); }
 	YY_BREAK
 case 49:
 YY_RULE_SETUP
-#line 217 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 217 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(BUFFER); }
 	YY_BREAK
 case 50:
 YY_RULE_SETUP
-#line 218 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 218 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CHARACTER); }
 	YY_BREAK
 case 51:
 YY_RULE_SETUP
-#line 219 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 219 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CLASS); }
 	YY_BREAK
 case 52:
 YY_RULE_SETUP
-#line 220 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 220 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CLASSITEM); }
 	YY_BREAK
 case 53:
 YY_RULE_SETUP
-#line 221 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 221 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CLASSGROUP); }
 	YY_BREAK
 case 54:
 YY_RULE_SETUP
-#line 222 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 222 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CLUSTER); }
 	YY_BREAK
 case 55:
 YY_RULE_SETUP
-#line 223 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 223 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(COLOR); }
 	YY_BREAK
 case 56:
 YY_RULE_SETUP
-#line 224 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 224 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CONFIG); }
 	YY_BREAK
 case 57:
 YY_RULE_SETUP
-#line 225 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 225 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CONNECTION); }
 	YY_BREAK
 case 58:
 YY_RULE_SETUP
-#line 226 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 226 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(CONNECTIONTYPE); }
 	YY_BREAK
 case 59:
 YY_RULE_SETUP
-#line 227 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 227 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DATA); }
 	YY_BREAK
 case 60:
 YY_RULE_SETUP
-#line 228 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 228 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DATAPATTERN); }
 	YY_BREAK
 case 61:
 YY_RULE_SETUP
-#line 229 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 229 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DEBUG); }
 	YY_BREAK
 case 62:
 YY_RULE_SETUP
-#line 230 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 230 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DRIVER); }
 	YY_BREAK
 case 63:
 YY_RULE_SETUP
-#line 231 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 231 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DUMP); }
 	YY_BREAK
 case 64:
 YY_RULE_SETUP
-#line 232 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 232 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(EMPTY); }
 	YY_BREAK
 case 65:
 YY_RULE_SETUP
-#line 233 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 233 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ENCODING); }
 	YY_BREAK
 case 66:
 YY_RULE_SETUP
-#line 234 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 234 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(END); }
 	YY_BREAK
 case 67:
 YY_RULE_SETUP
-#line 235 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 235 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ERROR); }
 	YY_BREAK
 case 68:
 YY_RULE_SETUP
-#line 236 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 236 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(EXPRESSION); }
 	YY_BREAK
 case 69:
 YY_RULE_SETUP
-#line 237 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 237 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(EXTENT); }
 	YY_BREAK
 case 70:
 YY_RULE_SETUP
-#line 238 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 238 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(EXTENSION); }
 	YY_BREAK
 case 71:
 YY_RULE_SETUP
-#line 239 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 239 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FEATURE); }
 	YY_BREAK
 case 72:
 YY_RULE_SETUP
-#line 240 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 240 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FILLED); }
 	YY_BREAK
 case 73:
 YY_RULE_SETUP
-#line 241 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 241 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FILTER); }
 	YY_BREAK
 case 74:
 YY_RULE_SETUP
-#line 242 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 242 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FILTERITEM); }
 	YY_BREAK
 case 75:
 YY_RULE_SETUP
-#line 243 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 243 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FOOTER); }
 	YY_BREAK
 case 76:
 YY_RULE_SETUP
-#line 244 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 244 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FONT); }
 	YY_BREAK
 case 77:
 YY_RULE_SETUP
-#line 245 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 245 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FONTSET); }
 	YY_BREAK
 case 78:
 YY_RULE_SETUP
-#line 246 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 246 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FORCE); }
 	YY_BREAK
 case 79:
 YY_RULE_SETUP
-#line 247 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 247 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FORMATOPTION); }
 	YY_BREAK
 case 80:
 YY_RULE_SETUP
-#line 248 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 248 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(FROM); }
 	YY_BREAK
 case 81:
 YY_RULE_SETUP
-#line 249 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 249 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GAP); }
 	YY_BREAK
 case 82:
 YY_RULE_SETUP
-#line 250 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 250 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GEOMTRANSFORM); }
 	YY_BREAK
 case 83:
 YY_RULE_SETUP
-#line 251 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 251 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GRID); }
 	YY_BREAK
 case 84:
 YY_RULE_SETUP
-#line 252 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 252 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GRIDSTEP); }
 	YY_BREAK
 case 85:
 YY_RULE_SETUP
-#line 253 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 253 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GRATICULE); }
 	YY_BREAK
 case 86:
 YY_RULE_SETUP
-#line 254 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 254 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(GROUP); }
 	YY_BREAK
 case 87:
 YY_RULE_SETUP
-#line 255 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 255 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(HEADER); }
 	YY_BREAK
 case 88:
 YY_RULE_SETUP
-#line 256 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 256 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGE); }
 	YY_BREAK
 case 89:
 YY_RULE_SETUP
-#line 257 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 257 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGECOLOR); }
 	YY_BREAK
 case 90:
 YY_RULE_SETUP
-#line 258 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 258 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGETYPE); }
 	YY_BREAK
 case 91:
 YY_RULE_SETUP
-#line 259 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 259 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGEQUALITY); }
 	YY_BREAK
 case 92:
 YY_RULE_SETUP
-#line 260 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 260 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGEMODE); }
 	YY_BREAK
 case 93:
 YY_RULE_SETUP
-#line 261 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 261 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGEPATH); }
 	YY_BREAK
 case 94:
 YY_RULE_SETUP
-#line 262 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 262 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TEMPPATH); }
 	YY_BREAK
 case 95:
 YY_RULE_SETUP
-#line 263 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 263 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(IMAGEURL); }
 	YY_BREAK
 case 96:
 YY_RULE_SETUP
-#line 264 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 264 "/home/tbonfort/dev/mapserver/maplexer.l"
 { BEGIN(INCLUDE); }
 	YY_BREAK
 case 97:
 YY_RULE_SETUP
-#line 265 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 265 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(INDEX); }
 	YY_BREAK
 case 98:
 YY_RULE_SETUP
-#line 266 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 266 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(INITIALGAP); }
 	YY_BREAK
 case 99:
 YY_RULE_SETUP
-#line 267 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 267 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(INTERLACE); }
 	YY_BREAK
 case 100:
 YY_RULE_SETUP
-#line 268 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 268 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(INTERVALS); } 
 	YY_BREAK
 case 101:
 YY_RULE_SETUP
-#line 269 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 269 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(JOIN); }
 	YY_BREAK
 case 102:
 YY_RULE_SETUP
-#line 270 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 270 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(KEYIMAGE); }
 	YY_BREAK
 case 103:
 YY_RULE_SETUP
-#line 271 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 271 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(KEYSIZE); }
 	YY_BREAK
 case 104:
 YY_RULE_SETUP
-#line 272 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 272 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(KEYSPACING); }
 	YY_BREAK
 case 105:
 YY_RULE_SETUP
-#line 273 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 273 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABEL); }
 	YY_BREAK
 case 106:
 YY_RULE_SETUP
-#line 274 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 274 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELCACHE); }
 	YY_BREAK
 case 107:
 YY_RULE_SETUP
-#line 275 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 275 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELFORMAT); }
 	YY_BREAK
 case 108:
 YY_RULE_SETUP
-#line 276 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 276 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELITEM); }
 	YY_BREAK
 case 109:
 YY_RULE_SETUP
-#line 277 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 277 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELMAXSCALE); }
 	YY_BREAK
 case 110:
 YY_RULE_SETUP
-#line 278 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 278 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELMAXSCALEDENOM); }
 	YY_BREAK
 case 111:
 YY_RULE_SETUP
-#line 279 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 279 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELMINSCALE); }
 	YY_BREAK
 case 112:
 YY_RULE_SETUP
-#line 280 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 280 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELMINSCALEDENOM); }
 	YY_BREAK
 case 113:
 YY_RULE_SETUP
-#line 281 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 281 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LABELREQUIRES); }
 	YY_BREAK
 case 114:
 YY_RULE_SETUP
-#line 282 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 282 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LATLON); }
 	YY_BREAK
 case 115:
 YY_RULE_SETUP
-#line 283 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 283 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LAYER); }
 	YY_BREAK
 case 116:
 YY_RULE_SETUP
-#line 284 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 284 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LEADER); }
 	YY_BREAK
 case 117:
 YY_RULE_SETUP
-#line 285 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 285 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LEGEND); }
 	YY_BREAK
 case 118:
 YY_RULE_SETUP
-#line 286 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 286 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LEGENDFORMAT); }
 	YY_BREAK
 case 119:
 YY_RULE_SETUP
-#line 287 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 287 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LINECAP); }
 	YY_BREAK
 case 120:
 YY_RULE_SETUP
-#line 288 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 288 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LINEJOIN); }
 	YY_BREAK
 case 121:
 YY_RULE_SETUP
-#line 289 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 289 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LINEJOINMAXSIZE); }
 	YY_BREAK
 case 122:
 YY_RULE_SETUP
-#line 290 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 290 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(LOG); }
 	YY_BREAK
 case 123:
 YY_RULE_SETUP
-#line 291 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 291 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAP); }
 	YY_BREAK
 case 124:
 YY_RULE_SETUP
-#line 292 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 292 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MARKER); }
 	YY_BREAK
 case 125:
 YY_RULE_SETUP
-#line 293 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 293 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MARKERSIZE); }
 	YY_BREAK
 case 126:
 YY_RULE_SETUP
-#line 294 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 294 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MASK); }
 	YY_BREAK
 case 127:
 YY_RULE_SETUP
-#line 295 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 295 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXARCS); }
 	YY_BREAK
 case 128:
 YY_RULE_SETUP
-#line 296 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 296 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXBOXSIZE); }
 	YY_BREAK
 case 129:
 YY_RULE_SETUP
-#line 297 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 297 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXDISTANCE); }
 	YY_BREAK
 case 130:
 YY_RULE_SETUP
-#line 298 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 298 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXFEATURES); }
 	YY_BREAK
 case 131:
 YY_RULE_SETUP
-#line 299 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 299 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXINTERVAL); }
 	YY_BREAK
 case 132:
 YY_RULE_SETUP
-#line 300 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 300 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXSCALE); }
 	YY_BREAK
 case 133:
 YY_RULE_SETUP
-#line 301 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 301 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXSCALEDENOM); }
 	YY_BREAK
 case 134:
 YY_RULE_SETUP
-#line 302 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 302 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXGEOWIDTH); }
 	YY_BREAK
 case 135:
 YY_RULE_SETUP
-#line 303 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 303 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXLENGTH); }
 	YY_BREAK
 case 136:
 YY_RULE_SETUP
-#line 304 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 304 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXSIZE); }
 	YY_BREAK
 case 137:
 YY_RULE_SETUP
-#line 305 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 305 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXSUBDIVIDE); }
 	YY_BREAK
 case 138:
 YY_RULE_SETUP
-#line 306 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 306 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXTEMPLATE); }
 	YY_BREAK
 case 139:
 YY_RULE_SETUP
-#line 307 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 307 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXWIDTH); }
 	YY_BREAK
 case 140:
 YY_RULE_SETUP
-#line 308 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 308 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(METADATA); }
 	YY_BREAK
 case 141:
 YY_RULE_SETUP
-#line 309 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 309 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MIMETYPE); }
 	YY_BREAK
 case 142:
 YY_RULE_SETUP
-#line 310 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 310 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINARCS); }
 	YY_BREAK
 case 143:
 YY_RULE_SETUP
-#line 311 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 311 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINBOXSIZE); }
 	YY_BREAK
 case 144:
 YY_RULE_SETUP
-#line 312 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 312 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINDISTANCE); }
 	YY_BREAK
 case 145:
 YY_RULE_SETUP
-#line 313 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 313 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(REPEATDISTANCE); }
 	YY_BREAK
 case 146:
 YY_RULE_SETUP
-#line 314 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 314 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MAXOVERLAPANGLE); } 
 	YY_BREAK
 case 147:
 YY_RULE_SETUP
-#line 315 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 315 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINFEATURESIZE); }
 	YY_BREAK
 case 148:
 YY_RULE_SETUP
-#line 316 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 316 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MININTERVAL); }
 	YY_BREAK
 case 149:
 YY_RULE_SETUP
-#line 317 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 317 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINSCALE); }
 	YY_BREAK
 case 150:
 YY_RULE_SETUP
-#line 318 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 318 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINSCALEDENOM); }
 	YY_BREAK
 case 151:
 YY_RULE_SETUP
-#line 319 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 319 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINGEOWIDTH); }
 	YY_BREAK
 case 152:
 YY_RULE_SETUP
-#line 320 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 320 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINLENGTH); }
 	YY_BREAK
 case 153:
 YY_RULE_SETUP
-#line 321 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 321 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINSIZE); }
 	YY_BREAK
 case 154:
 YY_RULE_SETUP
-#line 322 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 322 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINSUBDIVIDE); }
 	YY_BREAK
 case 155:
 YY_RULE_SETUP
-#line 323 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 323 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINTEMPLATE); }
 	YY_BREAK
 case 156:
 YY_RULE_SETUP
-#line 324 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 324 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MINWIDTH); }
 	YY_BREAK
 case 157:
 YY_RULE_SETUP
-#line 325 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 325 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(NAME); }
 	YY_BREAK
 case 158:
 YY_RULE_SETUP
-#line 326 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 326 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OFFSET); }
 	YY_BREAK
 case 159:
 YY_RULE_SETUP
-#line 327 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 327 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OFFSITE); }
 	YY_BREAK
 case 160:
 YY_RULE_SETUP
-#line 328 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 328 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OPACITY); }
 	YY_BREAK
 case 161:
 YY_RULE_SETUP
-#line 329 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 329 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OUTLINECOLOR); }
 	YY_BREAK
 case 162:
 YY_RULE_SETUP
-#line 330 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 330 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OUTLINEWIDTH); }
 	YY_BREAK
 case 163:
 YY_RULE_SETUP
-#line 331 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 331 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OUTPUTFORMAT); }
 	YY_BREAK
 case 164:
 YY_RULE_SETUP
-#line 332 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 332 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYBACKGROUNDCOLOR); }
 	YY_BREAK
 case 165:
 YY_RULE_SETUP
-#line 333 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 333 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYCOLOR); }
 	YY_BREAK
 case 166:
 YY_RULE_SETUP
-#line 334 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 334 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYMAXSIZE); }
 	YY_BREAK
 case 167:
 YY_RULE_SETUP
-#line 335 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 335 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYMINSIZE); }
 	YY_BREAK
 case 168:
 YY_RULE_SETUP
-#line 336 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 336 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYOUTLINECOLOR); }
 	YY_BREAK
 case 169:
 YY_RULE_SETUP
-#line 337 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 337 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYSIZE); }
 	YY_BREAK
 case 170:
 YY_RULE_SETUP
-#line 338 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 338 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(OVERLAYSYMBOL); }
 	YY_BREAK
 case 171:
 YY_RULE_SETUP
-#line 339 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 339 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(PARTIALS); }
 	YY_BREAK
 case 172:
 YY_RULE_SETUP
-#line 340 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 340 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(PATTERN); }
 	YY_BREAK
 case 173:
 YY_RULE_SETUP
-#line 341 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 341 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(POINTS); }
 	YY_BREAK
 case 174:
 YY_RULE_SETUP
-#line 342 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 342 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(ITEMS); }
 	YY_BREAK
 case 175:
 YY_RULE_SETUP
-#line 343 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 343 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(POSITION); }
 	YY_BREAK
 case 176:
 YY_RULE_SETUP
-#line 344 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 344 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(POSTLABELCACHE); }
 	YY_BREAK
 case 177:
 YY_RULE_SETUP
-#line 345 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 345 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(PRIORITY); }
 	YY_BREAK
 case 178:
 YY_RULE_SETUP
-#line 346 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 346 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(PROCESSING); }
 	YY_BREAK
 case 179:
 YY_RULE_SETUP
-#line 347 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 347 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(PROJECTION); }
 	YY_BREAK
 case 180:
 YY_RULE_SETUP
-#line 348 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 348 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(QUERYFORMAT); }
 	YY_BREAK
 case 181:
 YY_RULE_SETUP
-#line 349 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 349 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(QUERYMAP); }
 	YY_BREAK
 case 182:
 YY_RULE_SETUP
-#line 350 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 350 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(REFERENCE); }
 	YY_BREAK
 case 183:
 YY_RULE_SETUP
-#line 351 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 351 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(REGION); }
 	YY_BREAK
 case 184:
 YY_RULE_SETUP
-#line 352 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 352 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(RELATIVETO); }
 	YY_BREAK
 case 185:
 YY_RULE_SETUP
-#line 353 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 353 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(REQUIRES); }
 	YY_BREAK
 case 186:
 YY_RULE_SETUP
-#line 354 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 354 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(RESOLUTION); }
 	YY_BREAK
 case 187:
 YY_RULE_SETUP
-#line 355 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 355 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(DEFRESOLUTION); }
 	YY_BREAK
 case 188:
 YY_RULE_SETUP
-#line 356 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 356 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SCALE); }
 	YY_BREAK
 case 189:
 YY_RULE_SETUP
-#line 357 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 357 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SCALEDENOM); }
 	YY_BREAK
 case 190:
 YY_RULE_SETUP
-#line 358 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 358 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SCALEBAR); }
 	YY_BREAK
 case 191:
 YY_RULE_SETUP
-#line 359 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 359 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SCALETOKEN); }
 	YY_BREAK
 case 192:
 YY_RULE_SETUP
-#line 360 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 360 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SHADOWCOLOR); }
 	YY_BREAK
 case 193:
 YY_RULE_SETUP
-#line 361 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 361 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SHADOWSIZE); }
 	YY_BREAK
 case 194:
 YY_RULE_SETUP
-#line 362 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 362 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SHAPEPATH); }
 	YY_BREAK
 case 195:
 YY_RULE_SETUP
-#line 363 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 363 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SIZE); }
 	YY_BREAK
 case 196:
 YY_RULE_SETUP
-#line 364 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 364 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SIZEUNITS); }
 	YY_BREAK
 case 197:
 YY_RULE_SETUP
-#line 365 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 365 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(STATUS); }
 	YY_BREAK
 case 198:
 YY_RULE_SETUP
-#line 366 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 366 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(STYLE); }
 	YY_BREAK
 case 199:
 YY_RULE_SETUP
-#line 367 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 367 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(STYLEITEM); }
 	YY_BREAK
 case 200:
 YY_RULE_SETUP
-#line 368 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 368 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SYMBOL); }
 	YY_BREAK
 case 201:
 YY_RULE_SETUP
-#line 369 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 369 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SYMBOLSCALE); }
 	YY_BREAK
 case 202:
 YY_RULE_SETUP
-#line 370 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 370 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SYMBOLSCALEDENOM); }
 	YY_BREAK
 case 203:
 YY_RULE_SETUP
-#line 371 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 371 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(SYMBOLSET); }
 	YY_BREAK
 case 204:
 YY_RULE_SETUP
-#line 372 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 372 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TABLE); }
 	YY_BREAK
 case 205:
 YY_RULE_SETUP
-#line 373 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 373 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TEMPLATE); }
 	YY_BREAK
 case 206:
 YY_RULE_SETUP
-#line 374 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 374 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TEMPLATEPATTERN); }
 	YY_BREAK
 case 207:
 YY_RULE_SETUP
-#line 375 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 375 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TEXT); }
 	YY_BREAK
 case 208:
 YY_RULE_SETUP
-#line 376 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 376 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TILEINDEX); }
 	YY_BREAK
 case 209:
 YY_RULE_SETUP
-#line 377 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 377 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TILEITEM); }
 	YY_BREAK
 case 210:
 YY_RULE_SETUP
-#line 378 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 378 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TILESRS); }
 	YY_BREAK
 case 211:
 YY_RULE_SETUP
-#line 379 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 379 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TITLE); }
 	YY_BREAK
 case 212:
 YY_RULE_SETUP
-#line 380 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 380 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TO); }
 	YY_BREAK
 case 213:
 YY_RULE_SETUP
-#line 381 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 381 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TOLERANCE); }
 	YY_BREAK
 case 214:
 YY_RULE_SETUP
-#line 382 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 382 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TOLERANCEUNITS); }
 	YY_BREAK
 case 215:
 YY_RULE_SETUP
-#line 383 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 383 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TRANSPARENCY); }
 	YY_BREAK
 case 216:
 YY_RULE_SETUP
-#line 384 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 384 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TRANSPARENT); }
 	YY_BREAK
 case 217:
 YY_RULE_SETUP
-#line 385 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 385 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TRANSFORM); }
 	YY_BREAK
 case 218:
 YY_RULE_SETUP
-#line 386 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 386 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(TYPE); }
 	YY_BREAK
 case 219:
 YY_RULE_SETUP
-#line 387 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 387 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(UNITS); }
 	YY_BREAK
 case 220:
 YY_RULE_SETUP
-#line 388 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 388 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(VALIDATION); }
 	YY_BREAK
 case 221:
 YY_RULE_SETUP
-#line 389 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 389 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(VALUES); }
 	YY_BREAK
 case 222:
 YY_RULE_SETUP
-#line 390 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 390 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(WEB); }
 	YY_BREAK
 case 223:
 YY_RULE_SETUP
-#line 391 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 391 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(WIDTH); }
 	YY_BREAK
 case 224:
 YY_RULE_SETUP
-#line 392 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 392 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(WKT); }
 	YY_BREAK
 case 225:
 YY_RULE_SETUP
-#line 393 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 393 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(WRAP); }
 	YY_BREAK
 case 226:
 YY_RULE_SETUP
-#line 395 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 395 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_ANNOTATION); }
 	YY_BREAK
 case 227:
 YY_RULE_SETUP
-#line 396 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 396 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_AUTO); }
 	YY_BREAK
 case 228:
 YY_RULE_SETUP
-#line 397 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 397 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_AUTO2); }
 	YY_BREAK
 case 229:
 YY_RULE_SETUP
-#line 398 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 398 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_BEVEL); }
 	YY_BREAK
 case 230:
 YY_RULE_SETUP
-#line 399 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 399 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_BITMAP); }
 	YY_BREAK
 case 231:
 YY_RULE_SETUP
-#line 400 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 400 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_BUTT); }
 	YY_BREAK
 case 232:
 YY_RULE_SETUP
-#line 401 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 401 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CC); }
 	YY_BREAK
 case 233:
 YY_RULE_SETUP
-#line 402 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 402 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_ALIGN_CENTER); }
 	YY_BREAK
 case 234:
 YY_RULE_SETUP
-#line 403 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 403 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_CHART); }
 	YY_BREAK
 case 235:
 YY_RULE_SETUP
-#line 404 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 404 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_CIRCLE); }
 	YY_BREAK
 case 236:
 YY_RULE_SETUP
-#line 405 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 405 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CL); }
 	YY_BREAK
 case 237:
 YY_RULE_SETUP
-#line 406 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 406 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CR); }
 	YY_BREAK
 case 238:
 YY_RULE_SETUP
-#line 407 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 407 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_DB_CSV); }
 	YY_BREAK
 case 239:
 YY_RULE_SETUP
-#line 408 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 408 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_DB_POSTGRES); }
 	YY_BREAK
 case 240:
 YY_RULE_SETUP
-#line 409 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 409 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_DB_MYSQL); }
 	YY_BREAK
 case 241:
 YY_RULE_SETUP
-#line 410 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 410 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_DEFAULT); }
 	YY_BREAK
 case 242:
 YY_RULE_SETUP
-#line 411 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 411 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_DD); }
 	YY_BREAK
 case 243:
 YY_RULE_SETUP
-#line 412 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 412 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_ELLIPSE); }
 	YY_BREAK
 case 244:
 YY_RULE_SETUP
-#line 413 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 413 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_EMBED); }
 	YY_BREAK
 case 245:
 YY_RULE_SETUP
-#line 414 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 414 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_FALSE); }
 	YY_BREAK
 case 246:
 YY_RULE_SETUP
-#line 415 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 415 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_FEET); }
 	YY_BREAK
 case 247:
 YY_RULE_SETUP
-#line 416 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 416 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_FOLLOW); }
 	YY_BREAK
 case 248:
 YY_RULE_SETUP
-#line 417 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 417 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_GIANT); }
 	YY_BREAK
 case 249:
 YY_RULE_SETUP
-#line 418 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 418 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_HATCH); }
 	YY_BREAK
 case 250:
 YY_RULE_SETUP
-#line 419 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 419 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_HILITE); }
 	YY_BREAK
 case 251:
 YY_RULE_SETUP
-#line 420 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 420 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_INCHES); }
 	YY_BREAK
 case 252:
 YY_RULE_SETUP
-#line 421 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 421 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_KILOMETERS); }
 	YY_BREAK
 case 253:
 YY_RULE_SETUP
-#line 422 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 422 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LARGE); }
 	YY_BREAK
 case 254:
 YY_RULE_SETUP
-#line 423 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 423 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LC); }
 	YY_BREAK
 case 255:
 YY_RULE_SETUP
-#line 424 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 424 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_ALIGN_LEFT); }
 	YY_BREAK
 case 256:
 YY_RULE_SETUP
-#line 425 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 425 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_LINE); }
 	YY_BREAK
 case 257:
 YY_RULE_SETUP
-#line 426 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 426 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LL); }
 	YY_BREAK
 case 258:
 YY_RULE_SETUP
-#line 427 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 427 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LR); }
 	YY_BREAK
 case 259:
 YY_RULE_SETUP
-#line 428 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 428 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_MEDIUM); }
 	YY_BREAK
 case 260:
 YY_RULE_SETUP
-#line 429 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 429 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_METERS); }
 	YY_BREAK
 case 261:
 YY_RULE_SETUP
-#line 430 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 430 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_NAUTICALMILES); }
 	YY_BREAK
 case 262:
 YY_RULE_SETUP
-#line 431 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 431 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_MILES); }
 	YY_BREAK
 case 263:
 YY_RULE_SETUP
-#line 432 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 432 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_MITER); }
 	YY_BREAK
 case 264:
 YY_RULE_SETUP
-#line 433 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 433 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_MULTIPLE); }
 	YY_BREAK
 case 265:
 YY_RULE_SETUP
-#line 434 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 434 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_NONE); }
 	YY_BREAK
 case 266:
 YY_RULE_SETUP
-#line 435 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 435 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_NORMAL); }
 	YY_BREAK
 case 267:
 YY_RULE_SETUP
-#line 436 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 436 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_OFF); }
 	YY_BREAK
 case 268:
 YY_RULE_SETUP
-#line 437 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 437 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_OGR); }
 	YY_BREAK
 case 269:
 YY_RULE_SETUP
-#line 438 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 438 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_ON); }
 	YY_BREAK
 case 270:
 YY_RULE_SETUP
-#line 439 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 439 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_ONE); }
 	YY_BREAK
 case 271:
 YY_RULE_SETUP
-#line 440 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 440 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_JOIN_ONE_TO_MANY); }
 	YY_BREAK
 case 272:
 YY_RULE_SETUP
-#line 441 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 441 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_ORACLESPATIAL); }
 	YY_BREAK
 case 273:
 YY_RULE_SETUP
-#line 442 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 442 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_PERCENTAGES); }
 	YY_BREAK
 case 274:
 YY_RULE_SETUP
-#line 443 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 443 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_PIXMAP); }
 	YY_BREAK
 case 275:
 YY_RULE_SETUP
-#line 444 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 444 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_PIXELS); }
 	YY_BREAK
 case 276:
 YY_RULE_SETUP
-#line 445 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 445 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_POINT); }
 	YY_BREAK
 case 277:
 YY_RULE_SETUP
-#line 446 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 446 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_POLYGON); }
 	YY_BREAK
 case 278:
 YY_RULE_SETUP
-#line 447 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 447 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_POSTGIS); }
 	YY_BREAK
 case 279:
 YY_RULE_SETUP
-#line 448 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 448 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_PLUGIN); }
 	YY_BREAK
 case 280:
 YY_RULE_SETUP
-#line 449 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 449 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_QUERY); }
 	YY_BREAK
 case 281:
 YY_RULE_SETUP
-#line 450 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 450 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_LAYER_RASTER); }
 	YY_BREAK
 case 282:
 YY_RULE_SETUP
-#line 451 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 451 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_ALIGN_RIGHT); }
 	YY_BREAK
 case 283:
 YY_RULE_SETUP
-#line 452 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 452 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_ROUND); }
 	YY_BREAK
 case 284:
 YY_RULE_SETUP
-#line 453 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 453 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SDE); }
 	YY_BREAK
 case 285:
 YY_RULE_SETUP
-#line 454 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 454 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SELECTED); }
 	YY_BREAK
 case 286:
 YY_RULE_SETUP
-#line 455 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 455 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SIMPLE); }
 	YY_BREAK
 case 287:
 YY_RULE_SETUP
-#line 456 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 456 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SINGLE); }
 	YY_BREAK
 case 288:
 YY_RULE_SETUP
-#line 457 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 457 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SMALL); }
 	YY_BREAK
 case 289:
 YY_RULE_SETUP
-#line 458 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 458 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_SQUARE); }
 	YY_BREAK
 case 290:
 YY_RULE_SETUP
-#line 459 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 459 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_SVG); }
 	YY_BREAK
 case 291:
 YY_RULE_SETUP
-#line 460 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 460 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(POLAROFFSET); }
 	YY_BREAK
 case 292:
 YY_RULE_SETUP
-#line 461 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 461 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TINY); }
 	YY_BREAK
 case 293:
 YY_RULE_SETUP
-#line 462 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 462 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CJC_TRIANGLE); }
 	YY_BREAK
 case 294:
 YY_RULE_SETUP
-#line 463 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 463 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TRUE); }
 	YY_BREAK
 case 295:
 YY_RULE_SETUP
-#line 464 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 464 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_TRUETYPE); }
 	YY_BREAK
 case 296:
 YY_RULE_SETUP
-#line 465 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 465 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_UC); }
 	YY_BREAK
 case 297:
 YY_RULE_SETUP
-#line 466 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 466 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_UL); }
 	YY_BREAK
 case 298:
 YY_RULE_SETUP
-#line 467 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 467 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_UR); }
 	YY_BREAK
 case 299:
 YY_RULE_SETUP
-#line 468 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 468 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_UNION); }
 	YY_BREAK
 case 300:
 YY_RULE_SETUP
-#line 469 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 469 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_UVRASTER); }
 	YY_BREAK
 case 301:
 YY_RULE_SETUP
-#line 470 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 470 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_CONTOUR); }
 	YY_BREAK
 case 302:
 YY_RULE_SETUP
-#line 471 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 471 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_SYMBOL_VECTOR); }
 	YY_BREAK
 case 303:
 YY_RULE_SETUP
-#line 472 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 472 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_WFS); }
 	YY_BREAK
 case 304:
 YY_RULE_SETUP
-#line 473 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 473 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_WMS); }
 	YY_BREAK
 case 305:
 YY_RULE_SETUP
-#line 474 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 474 "/home/tbonfort/dev/mapserver/maplexer.l"
 { MS_LEXER_RETURN_TOKEN(MS_GD_ALPHA); }
 	YY_BREAK
 case 306:
 YY_RULE_SETUP
-#line 476 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 476 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4068,7 +4068,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 307:
 YY_RULE_SETUP
-#line 484 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 484 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4082,7 +4082,7 @@ YY_RULE_SETUP
 case 308:
 /* rule 308 can match eol */
 YY_RULE_SETUP
-#line 494 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 494 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4094,7 +4094,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 309:
 YY_RULE_SETUP
-#line 503 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 503 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
   /* attribute binding - shape (fixed value) */
   return(MS_TOKEN_BINDING_SHAPE);
@@ -4102,7 +4102,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 310:
 YY_RULE_SETUP
-#line 507 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 507 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
   /* attribute binding - map cellsize */
   return(MS_TOKEN_BINDING_MAP_CELLSIZE);
@@ -4110,7 +4110,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 311:
 YY_RULE_SETUP
-#line 511 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 511 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
   /* attribute binding - data cellsize */
   return(MS_TOKEN_BINDING_DATA_CELLSIZE);
@@ -4119,7 +4119,7 @@ YY_RULE_SETUP
 case 312:
 /* rule 312 can match eol */
 YY_RULE_SETUP
-#line 515 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 515 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   /* attribute binding - numeric (no quotes) */
   msyytext++;
@@ -4133,7 +4133,7 @@ YY_RULE_SETUP
 case 313:
 /* rule 313 can match eol */
 YY_RULE_SETUP
-#line 524 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 524 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   /* attribute binding - string (single or double quotes) */
   msyytext+=2;
@@ -4147,7 +4147,7 @@ YY_RULE_SETUP
 case 314:
 /* rule 314 can match eol */
 YY_RULE_SETUP
-#line 533 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 533 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   /* attribute binding - time */
   msyytext+=2;
@@ -4160,7 +4160,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 315:
 YY_RULE_SETUP
-#line 543 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 543 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4171,7 +4171,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 316:
 YY_RULE_SETUP
-#line 551 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 551 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4183,7 +4183,7 @@ YY_RULE_SETUP
 case 317:
 /* rule 317 can match eol */
 YY_RULE_SETUP
-#line 559 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 559 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   msyytext++;
   msyytext[strlen(msyytext)-1] = '\0';
@@ -4196,7 +4196,7 @@ YY_RULE_SETUP
 case 318:
 /* rule 318 can match eol */
 YY_RULE_SETUP
-#line 568 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 568 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-2] = '\0';
@@ -4209,7 +4209,7 @@ YY_RULE_SETUP
 case 319:
 /* rule 319 can match eol */
 YY_RULE_SETUP
-#line 577 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 577 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4221,7 +4221,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 320:
 YY_RULE_SETUP
-#line 586 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 586 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4233,7 +4233,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 321:
 YY_RULE_SETUP
-#line 595 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 595 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4245,7 +4245,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 322:
 YY_RULE_SETUP
-#line 604 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 604 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyystring_return_state = MS_STRING;
                                                  msyystring_begin = msyytext[0]; 
@@ -4256,7 +4256,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 323:
 YY_RULE_SETUP
-#line 612 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 612 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                 MS_LEXER_STRING_REALLOC(msyystring_buffer, msyystring_size, 
                                                                                            msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4289,7 +4289,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 324:
 YY_RULE_SETUP
-#line 642 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 642 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
                                                 MS_LEXER_STRING_REALLOC(msyystring_buffer, msyystring_size, 
                                                                                            msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4304,7 +4304,7 @@ YY_RULE_SETUP
 case 325:
 /* rule 325 can match eol */
 YY_RULE_SETUP
-#line 653 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 653 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  char *yptr = msyytext;
                                                  while ( *yptr ) { 
@@ -4318,7 +4318,7 @@ YY_RULE_SETUP
 case 326:
 /* rule 326 can match eol */
 YY_RULE_SETUP
-#line 663 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 663 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyytext++;
                                                  msyytext[strlen(msyytext)-1] = '\0';
@@ -4335,6 +4335,7 @@ YY_RULE_SETUP
                                                  msyyin = fopen(msBuildPath(path, msyybasepath, msyytext), "r");
                                                  if(!msyyin) {
                                                    msSetError(MS_IOERR, "Error opening included file \"%s\".", "msyylex()", msyytext);
+                                                   msyyin = YY_CURRENT_BUFFER->yy_input_file;
                                                    return(-1);
                                                  }
 
@@ -4346,7 +4347,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 327:
 YY_RULE_SETUP
-#line 688 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 689 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                  msyystring_return_state = MS_TOKEN_LITERAL_STRING;
                                                  msyystring_begin = msyytext[0]; 
@@ -4357,7 +4358,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 328:
 YY_RULE_SETUP
-#line 696 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 697 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
                                                     MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                                                                             msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4368,11 +4369,11 @@ YY_RULE_SETUP
 case 329:
 /* rule 329 can match eol */
 YY_RULE_SETUP
-#line 703 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 704 "/home/tbonfort/dev/mapserver/maplexer.l"
 { msyylineno++; }
 	YY_BREAK
 case YY_STATE_EOF(INITIAL):
-#line 705 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 706 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
                                                   if( --include_stack_ptr < 0 )
                                                     return(EOF); /* end of main file */
@@ -4387,14 +4388,14 @@ case YY_STATE_EOF(INITIAL):
 case 330:
 /* rule 330 can match eol */
 YY_RULE_SETUP
-#line 716 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 717 "/home/tbonfort/dev/mapserver/maplexer.l"
 {
   return(0); 
 }
 	YY_BREAK
 case 331:
 YY_RULE_SETUP
-#line 720 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 721 "/home/tbonfort/dev/mapserver/maplexer.l"
 { 
                                                   MS_LEXER_STRING_REALLOC(msyystring_buffer, strlen(msyytext), 
                                                                           msyystring_buffer_size, msyystring_buffer_ptr);
@@ -4404,15 +4405,15 @@ YY_RULE_SETUP
 	YY_BREAK
 case 332:
 YY_RULE_SETUP
-#line 726 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 727 "/home/tbonfort/dev/mapserver/maplexer.l"
 { return(msyytext[0]); }
 	YY_BREAK
 case 333:
 YY_RULE_SETUP
-#line 727 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 728 "/home/tbonfort/dev/mapserver/maplexer.l"
 ECHO;
 	YY_BREAK
-#line 4416 "/home/even/mapserver/git/mapserver/maplexer.c"
+#line 4417 "/home/tbonfort/dev/mapserver/maplexer.c"
 case YY_STATE_EOF(URL_VARIABLE):
 case YY_STATE_EOF(URL_STRING):
 case YY_STATE_EOF(EXPRESSION_STRING):
@@ -5414,7 +5415,7 @@ void msyyfree (void * ptr )
 
 #define YYTABLES_NAME "yytables"
 
-#line 727 "/home/even/mapserver/git/mapserver/maplexer.l"
+#line 728 "/home/tbonfort/dev/mapserver/maplexer.l"
 
 
 
diff --git a/maplexer.l b/maplexer.l
index 7f7f574..31845c8 100644
--- a/maplexer.l
+++ b/maplexer.l
@@ -676,6 +676,7 @@ char path[MS_MAXPATHLEN];
                                                  msyyin = fopen(msBuildPath(path, msyybasepath, msyytext), "r");
                                                  if(!msyyin) {
                                                    msSetError(MS_IOERR, "Error opening included file \"%s\".", "msyylex()", msyytext);
+                                                   msyyin = YY_CURRENT_BUFFER->yy_input_file;
                                                    return(-1);
                                                  }
 
diff --git a/maplibxml2.c b/maplibxml2.c
index c869431..012448d 100644
--- a/maplibxml2.c
+++ b/maplibxml2.c
@@ -57,12 +57,10 @@ void msLibXml2GenerateList(xmlNodePtr psParent, xmlNsPtr psNs, const char *elnam
   int n = 0;
   int i = 0;
   tokens = msStringSplit(values, delim, &n);
-  if (tokens && n > 0) {
-    for (i=0; i<n; i++) {
-      xmlNewChild(psParent, psNs, BAD_CAST elname, BAD_CAST tokens[i]);
-    }
-    msFreeCharArray(tokens, n);
+  for (i=0; i<n; i++) {
+    xmlNewChild(psParent, psNs, BAD_CAST elname, BAD_CAST tokens[i]);
   }
+  msFreeCharArray(tokens, n);
 }
 
 /**
@@ -104,10 +102,10 @@ xmlXPathObjectPtr msLibXml2GetXPath(xmlDocPtr doc, xmlXPathContextPtr context, x
  *
  */
 
-const char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath)
+char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath)
 {
   xmlBufferPtr xbuf;
-  const char *result = NULL;
+  char *result = NULL;
 
   xbuf = xmlBufferCreate();
 
diff --git a/maplibxml2.h b/maplibxml2.h
index 019f0d8..0ba9072 100644
--- a/maplibxml2.h
+++ b/maplibxml2.h
@@ -43,7 +43,7 @@ xmlXPathObjectPtr msLibXml2GetXPath(xmlDocPtr doc, xmlXPathContextPtr context, x
 
 void msLibXml2GenerateList(xmlNodePtr psParent, xmlNsPtr psNs, const char *elname, const char *values, char delim);
 
-const char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath);
+char *msLibXml2GetXPathTree(xmlDocPtr doc, xmlXPathObjectPtr xpath);
 
 #endif /* defined(USE_LIBXML2) */
 
diff --git a/mapogcfilter.c b/mapogcfilter.c
index ad14159..e9948c5 100644
--- a/mapogcfilter.c
+++ b/mapogcfilter.c
@@ -66,8 +66,7 @@ int FLTIsNumeric(char *pszValue)
       return MS_TRUE;
 #else
     char * p;
-    strtod (pszValue, &p);
-    if (*p == '\0') return MS_TRUE;
+    if (strtod(pszValue, &p) != 0  || *p == '\0') return MS_TRUE;
 #endif
   }
 
@@ -210,8 +209,8 @@ char *FLTGetExpressionForValuesRanges(layerObj *lp, char *item, char *value,  in
           pszTmpExpression = NULL;
         }
         pszExpression = msStringConcatenate(pszExpression, ")");
-        msFreeCharArray(paszElements, numelements);
       }
+      msFreeCharArray(paszElements, numelements);
     } else {
       /*range(s)*/
       paszElements = msStringSplit (value, ',', &numelements);
@@ -286,14 +285,15 @@ char *FLTGetExpressionForValuesRanges(layerObj *lp, char *item, char *value,  in
             msFree(pszTmpExpression);
             pszTmpExpression = NULL;
 
-            msFreeCharArray(papszRangeElements, nrangeelements);
           }
+          msFreeCharArray(papszRangeElements, nrangeelements);
         }
         pszExpression = msStringConcatenate(pszExpression, ")");
-        msFreeCharArray(paszElements, numelements);
       }
+      msFreeCharArray(paszElements, numelements);
     }
   }
+  msFree(pszTmpExpression);
   return pszExpression;
 }
 
@@ -430,11 +430,11 @@ int FLTGML2Shape_XMLNode(CPLXMLNode *psNode, shapeObj *psShp)
   CPLXMLNode *psCoordinates = NULL;
   char *pszTmpCoord = NULL;
   char **szCoords = NULL;
-  int nCoords = 0;
+  int nCoords = 0, status = MS_FALSE;
 
 
   if (!psNode || !psShp)
-    return MS_FALSE;
+    return status;
 
 
   if( strcasecmp(psNode->pszValue,"PointType") == 0
@@ -459,12 +459,13 @@ int FLTGML2Shape_XMLNode(CPLXMLNode *psNode, shapeObj *psShp)
         msAddLine(psShp, &line);
         free(line.point);
 
-        return MS_TRUE;
+        status = MS_TRUE;
       }
+      msFreeCharArray(szCoords, nCoords);
     }
   }
 
-  return MS_FALSE;
+  return status;
 }
 
 
@@ -813,8 +814,10 @@ FilterEncodingNode *FLTParseFilterEncoding(char *szXMLString)
   /* -------------------------------------------------------------------- */
   /*      validate the node tree to make sure that all the nodes are valid.*/
   /* -------------------------------------------------------------------- */
-  if (!FLTValidFilterNode(psFilterNode))
+  if (!FLTValidFilterNode(psFilterNode)) {
+    FLTFreeFilterEncodingNode(psFilterNode);
     return NULL;
+  }
 
 
   return psFilterNode;
@@ -1138,6 +1141,8 @@ void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
           ((rectObj *)psFilterNode->psRightNode->pOther)->miny = sBox.miny;
           ((rectObj *)psFilterNode->psRightNode->pOther)->maxx = sBox.maxx;
           ((rectObj *)psFilterNode->psRightNode->pOther)->maxy =  sBox.maxy;
+        } else {
+          msFree(pszSRS);
         }
       } else if (strcasecmp(psXMLNode->pszValue, "DWithin") == 0 ||
                  strcasecmp(psXMLNode->pszValue, "Beyond") == 0)
@@ -1545,10 +1550,6 @@ void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
     /* -------------------------------------------------------------------- */
     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;
@@ -1915,11 +1916,10 @@ shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
               else if (strcasecmp(szUnit,"px") == 0)
                 *pnUnit = MS_PIXELS;
 
-              msFreeCharArray(tokens, nTokens);
             }
           }
-        }
-
+        } 
+        msFreeCharArray(tokens, nTokens);
       }
 
       return (shapeObj *)psNode->pOther;
@@ -2224,8 +2224,10 @@ char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
 
     nTmp = strlen(pszBuffer);
     pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
-    if (!pszTmp)
+    if (!pszTmp) {
+      free(pszBuffer);
       return NULL;
+    }
 
     pszBuffer = (char *)realloc(pszBuffer,
                                 sizeof(char) * (strlen(pszTmp) + nTmp +3));
@@ -2333,8 +2335,10 @@ char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layer
     free(pszTmp);
 
     pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
-    if (!pszTmp)
+    if (!pszTmp) {
+      msFree(pszBuffer);
       return NULL;
+    }
 
     nTmp = strlen(pszBuffer);
     pszBuffer = (char *)realloc(pszBuffer,
@@ -2615,8 +2619,10 @@ char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
   /*      Get the bounds value which are stored like boundmin;boundmax    */
   /* -------------------------------------------------------------------- */
   aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
-  if (nBounds != 2)
+  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.        */
@@ -2682,6 +2688,7 @@ char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
   /*closing paranthesis*/
   strlcat(szBuffer, ")", bufferSize);
 
+  msFreeCharArray(aszBounds, nBounds);
 
   return msStrdup(szBuffer);
 }
@@ -3247,11 +3254,10 @@ int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS)
           if (tokens && n >= 2) {
             psBbox->maxx = atof(tokens[0]);
             psBbox->maxy = atof(tokens[1]);
-            msFreeCharArray(tokens, n);
-
             bValid = 1;
           }
         }
+        msFreeCharArray(tokens, n);
       }
     }
   }
@@ -3302,8 +3308,7 @@ static void FLTStripNameSpacesFromPropertyName(FilterEncodingNode *psFilterNode)
           msFree(psFilterNode->pszValue);
           psFilterNode->pszValue = msStrdup(tokens[1]);
         }
-        if (tokens && n>0)
-          msFreeCharArray(tokens, n);
+        msFreeCharArray(tokens, n);
       }
     }
     if (psFilterNode->psLeftNode)
diff --git a/mapogcfiltercommon.c b/mapogcfiltercommon.c
index 7d00d74..cb4c3f8 100644
--- a/mapogcfiltercommon.c
+++ b/mapogcfiltercommon.c
@@ -156,8 +156,7 @@ char *FLTGetIsBetweenComparisonCommonExpresssion(FilterEncodingNode *psFilterNod
   /* -------------------------------------------------------------------- */
   aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
   if (nBounds != 2) {
-    if (aszBounds)
-      msFreeCharArray(aszBounds, nBounds);
+    msFreeCharArray(aszBounds, nBounds);
     return NULL;
   }
   /* -------------------------------------------------------------------- */
@@ -252,8 +251,7 @@ char *FLTGetIsBetweenComparisonCommonExpresssion(FilterEncodingNode *psFilterNod
   sprintf(szBuffer, "%s", ")");
   pszExpression = msStringConcatenate(pszExpression, szBuffer);
 
-  if (aszBounds)
-    msFreeCharArray(aszBounds, nBounds);
+  msFreeCharArray(aszBounds, nBounds);
 
   return pszExpression;
 }
@@ -389,8 +387,10 @@ char *FLTGetLogicalComparisonCommonExpression(FilterEncodingNode *psFilterNode,
 
 
     pszTmp = FLTGetCommonExpression(psFilterNode->psRightNode, lp);
-    if (!pszTmp)
+    if (!pszTmp) {
+      msFree(pszExpression);
       return NULL;
+    }
 
     pszExpression = msStringConcatenate(pszExpression, pszTmp);
     msFree(pszTmp);
diff --git a/mapogcsld.c b/mapogcsld.c
index 9f019e2..d6782dd 100644
--- a/mapogcsld.c
+++ b/mapogcsld.c
@@ -92,11 +92,15 @@ int msSLDApplySLDURL(mapObj *map, char *szURL, int iLayer,
           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);
+          if(nBufsize > 0) {
+            rewind(fp);
+            pszSLDbuf = (char*)malloc((nBufsize+1)*sizeof(char));
+            fread(pszSLDbuf, 1, nBufsize, fp);
+            pszSLDbuf[nBufsize] = '\0';
+          } else {
+            msSetError(MS_WMSERR, "Could not open SLD %s as it appears empty", "msSLDApplySLDURL", szURL);
+          }
           fclose(fp);
-          pszSLDbuf[nBufsize] = '\0';
           unlink(pszSLDTmpFile);
         }
       } else {
@@ -202,9 +206,6 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
         }
       }
     }
-  }
-
-  if (pasLayers && nLayers > 0) {
     for (i=0; i<map->numlayers; i++) {
       if (iLayer >=0 && iLayer< map->numlayers) {
         i = iLayer;
@@ -231,7 +232,8 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
           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;
+            nsStatus = MS_FAILURE;
+            goto sld_cleanup;
           }
 #endif
 
@@ -392,8 +394,9 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
 
             pasLayers[j].layerinfo=NULL;
 
-            if( nStatus != MS_SUCCESS )
-              return nStatus;
+            if( nStatus != MS_SUCCESS ) {
+              goto sld_cleanup;
+            }
           } 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
@@ -474,10 +477,15 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
       *ppszLayerNames = pszTmp;
 
     }
-    for (i=0; i<nLayers; i++)
-      freeLayer(&pasLayers[i]);
-    msFree(pasLayers);
   }
+  
+  nStatus = MS_SUCCESS;
+
+sld_cleanup:
+  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) {
@@ -489,7 +497,7 @@ int msSLDApplySLD(mapObj *map, char *psSLDXML, int iLayer,
       msFree(tmpfilename);
     }
   }
-  return MS_SUCCESS;
+  return nStatus;
 
 
 #else
@@ -1207,6 +1215,7 @@ int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
           int nDash = 0, i;
           char **aszValues = NULL;
           int nMaxDash;
+          if(pszDashValue) free(pszDashValue); /* free previous if multiple stroke-dasharray attributes were found */
           pszDashValue =
             msStrdup(psCssParam->psChild->psNext->pszValue);
           aszValues = msStringSplit(pszDashValue, ' ', &nDash);
@@ -1219,10 +1228,9 @@ int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
             for (i=0; i<nMaxDash; i++)
               psStyle->pattern[i] = atof(aszValues[i]);
 
-            msFreeCharArray(aszValues, nDash);
             psStyle->linecap = MS_CJC_BUTT;
           }
-
+          msFreeCharArray(aszValues, nDash);
         }
       } else if (strcasecmp(psStrkName, "stroke-opacity") == 0) {
         if(psCssParam->psChild &&  psCssParam->psChild->psNext &&
@@ -1247,10 +1255,10 @@ int msSLDParseStroke(CPLXMLNode *psStroke, styleObj *psStyle,
   /* then again the fill parameter can be used inside both elements. */
   psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicFill");
   if (psGraphicFill)
-    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
+    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map);
   psGraphicFill =  CPLGetXMLNode(psStroke, "GraphicStroke");
   if (psGraphicFill)
-    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map, 0);
+    msSLDParseGraphicFillOrStroke(psGraphicFill, pszDashValue, psStyle, map);
 
   if (pszDashValue)
     free(pszDashValue);
@@ -1486,10 +1494,10 @@ int msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle,
   /* then again the fill parameter can be used inside both elements. */
   psGraphicFill =  CPLGetXMLNode(psFill, "GraphicFill");
   if (psGraphicFill)
-    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
+    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map);
   psGraphicFill =  CPLGetXMLNode(psFill, "GraphicStroke");
   if (psGraphicFill)
-    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map, 0);
+    msSLDParseGraphicFillOrStroke(psGraphicFill, NULL, psStyle, map);
 
 
   return MS_SUCCESS;
@@ -1504,8 +1512,7 @@ int msSLDParsePolygonFill(CPLXMLNode *psFill, styleObj *psStyle,
 /************************************************************************/
 int msSLDParseGraphicFillOrStroke(CPLXMLNode *psRoot,
                                   char *pszDashValue,
-                                  styleObj *psStyle, mapObj *map,
-                                  int bPointLayer)
+                                  styleObj *psStyle, mapObj *map)
 {
   CPLXMLNode  *psCssParam, *psGraphic, *psExternalGraphic, *psMark, *psSize;
   CPLXMLNode *psWellKnownName, *psStroke, *psFill;
@@ -1518,8 +1525,6 @@ int msSLDParseGraphicFillOrStroke(CPLXMLNode *psRoot,
   CPLXMLNode *psPropertyName=NULL;
   char szTmp[256];
 
-  bPointLayer=0;
-
   if (!psRoot || !psStyle || !map)
     return MS_FAILURE;
   /* ==================================================================== */
@@ -2059,7 +2064,7 @@ int msSLDParsePointSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer,
 
   msSLDParseGraphicFillOrStroke(psRoot, NULL,
                                 psLayer->class[nClassId]->styles[iStyle],
-                                psLayer->map, 1);
+                                psLayer->map);
 
   return MS_SUCCESS;
 }
@@ -2556,7 +2561,7 @@ int msSLDParseRasterSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer)
         psNode = psNode->psNext;
       }
 
-      if (nValues == nThresholds+1) {
+      if (nThresholds > 0 && nValues == nThresholds+1) {
         /*free existing classes*/
         for(i=0; i<psLayer->numclasses; i++) {
           if (psLayer->class[i] != NULL) {
@@ -3604,6 +3609,7 @@ char *msSLDGenerateLineSLD(styleObj *psStyle, layerObj *psLayer, int nVersion)
              "<%s name=\"stroke-dasharray\">%s</%s>\n",
              sCssParam, pszDashArray, sCssParam);
     pszSLD = msStringConcatenate(pszSLD, szTmp);
+    msFree(pszDashArray);
   }
 
   snprintf(szTmp, sizeof(szTmp), "</%sStroke>\n",  sNameSpace);
@@ -3881,9 +3887,8 @@ char *msSLDGenerateTextSLD(classObj *psClass, layerObj *psLayer, int nVersion)
         }
         snprintf(szTmp, sizeof(szTmp), "</%sFont>\n",  sNameSpace);
         pszSLD = msStringConcatenate(pszSLD, szTmp);
-
-        msFreeCharArray(aszFontsParts, nFontParts);
       }
+      msFreeCharArray(aszFontsParts, nFontParts);
     }
 
 
@@ -4410,8 +4415,10 @@ char *msSLDGetLeftExpressionOfOperator(char *pszExpression)
       }
       pszReturn[iReturn] = '\0';
     }
-  } else
+  } else {
+    msFree(pszReturn);
     return NULL;
+  }
 
   return pszReturn;
 }
@@ -4551,7 +4558,6 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
     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));
@@ -4572,9 +4578,8 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
         }
         pszAttributeName[iValue] = '\0';
       }
-
-
     }
+    msFreeCharArray(aszValues, nTokens);
   } else if (bOneCharCompare == 0) {
     nLength = strlen(pszExpression);
     pszAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
@@ -4608,8 +4613,10 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
   /*      inside []                                                       */
   /* -------------------------------------------------------------------- */
   if (bReturnName) {
-    if (!pszAttributeName)
+    if (!pszAttributeName) {
+      msFree(pszAttributeValue);
       return NULL;
+    }
 
     nLength = strlen(pszAttributeName);
     pszFinalAttributeName = (char *)malloc(sizeof(char)*(nLength+1));
@@ -4631,13 +4638,18 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
       pszFinalAttributeName[iAtt] = '\0';
     }
 
+    msFree(pszAttributeName);
+    msFree(pszAttributeValue);
     return pszFinalAttributeName;
   } else {
 
-    if (!pszAttributeValue)
+    if (!pszAttributeValue) {
+      msFree(pszAttributeName);
       return NULL;
+    }
     nLength = strlen(pszAttributeValue);
     pszFinalAttributeValue = (char *)malloc(sizeof(char)*(nLength+1));
+    pszFinalAttributeValue[0] = '\0';
     bStartCopy= 0;
     iAtt = 0;
     for (i=0; i<nLength; i++) {
@@ -4668,8 +4680,7 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
     }
 
     /*trim  for regular expressions*/
-    if (pszFinalAttributeValue && strlen(pszFinalAttributeValue) > 2 &&
-        strcasecmp(pszComparionValue, "PropertyIsLike") == 0) {
+    if (strlen(pszFinalAttributeValue) > 2 && strcasecmp(pszComparionValue, "PropertyIsLike") == 0) {
       int len = strlen(pszFinalAttributeValue);
       msStringTrimBlanks(pszFinalAttributeValue);
       if (pszFinalAttributeValue[0] == '/' &&
@@ -4688,6 +4699,8 @@ char *msSLDGetAttributeNameOrValue(char *pszExpression,
         pszFinalAttributeValue = msReplaceSubstring(pszFinalAttributeValue, ".*", "*");
       }
     }
+    msFree(pszAttributeName);
+    msFree(pszAttributeValue);
     return pszFinalAttributeValue;
   }
 }
@@ -4853,8 +4866,10 @@ FilterEncodingNode *BuildExpressionTree(char *pszExpression,
     }
 
     return psNode;
-  } else
+  } else {
+    msFree(pszFinalExpression);
     return NULL;
+  }
 }
 
 char *msSLDBuildFilterEncoding(FilterEncodingNode *psNode)
@@ -5014,10 +5029,12 @@ char *msSLDParseExpression(char *pszExpression)
       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);
+        msFree(pszFilter); /*FIXME: we are possibly discarding a previously set pszFilter */
         pszFilter = msStrdup(szBuffer);
       }
     }
   }
+  msFreeCharArray(aszElements, nElements);
 
   return pszFilter;
 }
diff --git a/mapogcsld.h b/mapogcsld.h
index a6a5f4b..f70f813 100644
--- a/mapogcsld.h
+++ b/mapogcsld.h
@@ -63,7 +63,7 @@ int msSLDParseRasterSymbolizer(CPLXMLNode *psRoot, layerObj *psLayer);
 
 int msSLDParseGraphicFillOrStroke(CPLXMLNode *psGraphicFill,
                                   char *pszDashValue,
-                                  styleObj *psStyle, mapObj *map, int bPointLayer);
+                                  styleObj *psStyle, mapObj *map);
 int msSLDParseExternalGraphic(CPLXMLNode *psExternalGraphic, styleObj *psStyle,
                               mapObj *map);
 
diff --git a/mapogcsos.c b/mapogcsos.c
index 43a321a..dd54935 100644
--- a/mapogcsos.c
+++ b/mapogcsos.c
@@ -426,12 +426,14 @@ void  msSOSAddGeometryNode(xmlNsPtr psNsGml, xmlNsPtr psNsMs, xmlNodePtr psParen
 
           pszTmp = NULL;
           for(j=0; j<psShape->line[i].numpoints; j++) {
-            pszTmp = msStringConcatenate(pszTmp,
-                                         msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
+            char *doubleTmp = msDoubleToString(psShape->line[i].point[j].x, MS_TRUE);
+            pszTmp = msStringConcatenate(pszTmp, doubleTmp);
             pszTmp = msStringConcatenate(pszTmp, ",");
-            pszTmp = msStringConcatenate(pszTmp,
-                                         msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
-            pszTmp = msStringConcatenate(pszTmp, " ");
+            free(doubleTmp);
+            doubleTmp = msDoubleToString(psShape->line[i].point[j].y, MS_TRUE);
+            pszTmp = msStringConcatenate(pszTmp, doubleTmp);
+            pszTmp = msStringConcatenate(pszTmp, ",");
+            free(doubleTmp);
           }
           psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
           xmlSetNs(psNode,xmlNewNs(psNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
@@ -486,15 +488,15 @@ void  msSOSAddGeometryNode(xmlNsPtr psNsGml, xmlNsPtr psNsMs, xmlNodePtr psParen
 
           pszTmp = NULL;
           for(j=0; j<psShape->line[i].numpoints; j++) {
-
-            pszTmp =
-              msStringConcatenate(pszTmp,
-                                  msDoubleToString(psShape->line[i].point[j].x, MS_TRUE));
+            char *doubleTmp;
+            doubleTmp = msDoubleToString(psShape->line[i].point[j].x, MS_TRUE);
+            pszTmp = msStringConcatenate(pszTmp, doubleTmp);
             pszTmp = msStringConcatenate(pszTmp, ",");
-            pszTmp =
-              msStringConcatenate(pszTmp,
-                                  msDoubleToString(psShape->line[i].point[j].y, MS_TRUE));
+            free(doubleTmp);
+            doubleTmp = msDoubleToString(psShape->line[i].point[j].y, MS_TRUE);
+            pszTmp = msStringConcatenate(pszTmp, doubleTmp);
             pszTmp = msStringConcatenate(pszTmp, " ");
+            free(doubleTmp);
           }
           psNode = xmlNewChild(psNode, NULL, BAD_CAST "coordinates", BAD_CAST pszTmp);
           xmlSetNs(psNode,xmlNewNs(psNode,
@@ -851,9 +853,8 @@ void msSOSAddMemberNode(xmlNsPtr psNsGml, xmlNsPtr psNsOm, xmlNsPtr psNsSwe, xml
       if (lp->index != lpfirst->index)
         msLayerClose(lpfirst);
     }
+    msFreeShape(&sShape);
   }
-
-  msFreeShape(&sShape);
 }
 
 /************************************************************************/
@@ -2711,8 +2712,11 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request)
   int returnvalue = MS_DONE;
   sosParamsObj *paramsObj = (sosParamsObj *)calloc(1, sizeof(sosParamsObj));
 
-  if (msSOSParseRequest(map, req, paramsObj) == MS_FAILURE)
+  if (msSOSParseRequest(map, req, paramsObj) == MS_FAILURE) {
+    msSOSFreeParamsObj(paramsObj);
+    free(paramsObj);
     return MS_FAILURE;
+  }
 
   /* SERVICE must be specified and be SOS */
   if (paramsObj->pszService && strcasecmp(paramsObj->pszService, "SOS") == 0) { /* this is an SOS request */
@@ -2782,8 +2786,11 @@ int msSOSDispatch(mapObj *map, cgiRequestObj *req, owsRequestObj *ows_request)
       paramsObj = NULL;
       return msSOSException(map, "request", "InvalidParameterValue");
     }
-  } else
+  } else {
+    msSOSFreeParamsObj(paramsObj);
+    free(paramsObj);
     return MS_DONE;  /* Not an SOS request */
+  }
 #else
   msSetError(MS_SOSERR, "SOS support is not available.", "msSOSDispatch()");
   return(MS_FAILURE);
@@ -3014,7 +3021,7 @@ int msSOSParseRequest(mapObj *map, cgiRequestObj *request, sosParamsObj *sospara
     psXPathTmp = msLibXml2GetXPath(doc, context, (xmlChar *)"/sos:GetObservation/sos:result/child::*");
 
     if (psXPathTmp) {
-      sosparams->pszResult = msStrdup(msLibXml2GetXPathTree(doc, psXPathTmp));
+      sosparams->pszResult = msLibXml2GetXPathTree(doc, psXPathTmp);
       pszTmp = msStringConcatenate(pszTmp, "<ogc:Filter>");
       pszTmp = msStringConcatenate(pszTmp, sosparams->pszResult);
       pszTmp = msStringConcatenate(pszTmp, "</ogc:Filter>");
diff --git a/mapogr.cpp b/mapogr.cpp
index 7f51961..1961f7a 100644
--- a/mapogr.cpp
+++ b/mapogr.cpp
@@ -1261,7 +1261,6 @@ static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
   // Make sure we aren't holding the lock when the callback may need it.
   RELEASE_OGR_LOCK;
   msConnPoolRelease( layer, psInfo->hDS );
-  ACQUIRE_OGR_LOCK;
 
   // Free current tile if there is one.
   if( psInfo->poCurTile != NULL )
@@ -1269,8 +1268,6 @@ static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
 
   CPLFree(psInfo);
 
-  RELEASE_OGR_LOCK;
-
   return MS_SUCCESS;
 }
 
@@ -2333,9 +2330,7 @@ int msOGRLayerNextShape(layerObj *layer, shapeObj *shape)
     if( status != MS_SUCCESS )
       return status;
   } while( status == MS_SUCCESS );
-
-  return status;
-
+  return status; //make compiler happy. this is never reached however
 #else
   /* ------------------------------------------------------------------
    * OGR Support not included...
diff --git a/mapogroutput.c b/mapogroutput.c
index a0949d9..5e2f6ba 100644
--- a/mapogroutput.c
+++ b/mapogroutput.c
@@ -536,6 +536,12 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
   /*      Determine the output datasource name to use.                    */
   /* ==================================================================== */
   storage = msGetOutputFormatOption( format, "STORAGE", "filesystem" );
+  if( EQUAL(storage,"stream") && !msIO_isStdContext() ) {
+    /* bug #4858, streaming output won't work if standard output has been
+     * redirected, we switch to memory output in this case
+     */
+    storage = "memory";
+  }
 
   /* -------------------------------------------------------------------- */
   /*      Where are we putting stuff?                                     */
@@ -804,6 +810,7 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
         if(status != MS_SUCCESS) {
           OGR_DS_Destroy( hDS );
           msOGRCleanupDS( datasource_name );
+          msGMLFreeItems(item_list);
           return status;
         }
       }
@@ -825,6 +832,8 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
       if(status != MS_SUCCESS) {
         OGR_DS_Destroy( hDS );
         msOGRCleanupDS( datasource_name );
+        msGMLFreeItems(item_list);
+        msFreeShape(&resultshape);
         return status;
       }
 
@@ -874,6 +883,8 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
       if(status != MS_SUCCESS) {
         OGR_DS_Destroy( hDS );
         msOGRCleanupDS( datasource_name );
+        msGMLFreeItems(item_list);
+        msFreeShape(&resultshape);
         return status;
       }
     }
@@ -901,7 +912,7 @@ int msOGRWriteFromQuery( mapObj *map, outputFormatObj *format, int sendheaders )
   } else {
     char datasource_path[MS_MAXPATHLEN];
 
-    strcpy( datasource_path, CPLGetPath( datasource_name ) );
+    strncpy( datasource_path, CPLGetPath( datasource_name ), MS_MAXPATHLEN-1 );
     file_list = msOGRRecursiveFileList( datasource_path );
   }
 
diff --git a/mapoutput.c b/mapoutput.c
index a1d6878..5cbb92c 100644
--- a/mapoutput.c
+++ b/mapoutput.c
@@ -165,7 +165,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     return msCreateDefaultOutputFormat( map, "GD/PNG", "gdpng" );
   }
 
-  if( strcasecmp(driver,"GD/GIF") == 0 ) {
+  else if( strcasecmp(driver,"GD/GIF") == 0 ) {
     if(!name) name="gif";
 #ifdef USE_GD_GIF
     format = msAllocOutputFormat( map, name, driver );
@@ -178,7 +178,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 #endif
   }
 
-  if( strcasecmp(driver,"GD/PNG") == 0 ) {
+  else if( strcasecmp(driver,"GD/PNG") == 0 ) {
     if(!name) name="gdpng";
 #ifdef USE_GD_PNG
     format = msAllocOutputFormat( map, name, driver );
@@ -191,7 +191,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 #endif /* USE_GD_PNG */
   }
 
-  if( strcasecmp(driver,"AGG/PNG") == 0 ) {
+  else if( strcasecmp(driver,"AGG/PNG") == 0 ) {
     if(!name) name="png24";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/png");
@@ -200,7 +200,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->renderer = MS_RENDER_WITH_AGG;
   }
 
-  if( strcasecmp(driver,"AGG/PNG8") == 0 ) {
+  else if( strcasecmp(driver,"AGG/PNG8") == 0 ) {
     if(!name) name="png8";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/png; mode=8bit");
@@ -211,7 +211,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     msSetOutputFormatOption( format, "QUANTIZE_COLORS", "256");
   }
 
-  if( strcasecmp(driver,"AGG/JPEG") == 0 ) {
+  else if( strcasecmp(driver,"AGG/JPEG") == 0 ) {
     if(!name) name="jpeg";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/jpeg");
@@ -221,7 +221,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
   }
 
 #if defined(USE_CAIRO)
-  if( strcasecmp(driver,"CAIRO/PNG") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/PNG") == 0 ) {
     if(!name) name="cairopng";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/png; mode=24bit");
@@ -229,7 +229,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->extension = msStrdup("png");
     format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
   }
-  if( strcasecmp(driver,"CAIRO/JPEG") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/JPEG") == 0 ) {
     if(!name) name="cairojpeg";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/jpeg");
@@ -237,7 +237,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->extension = msStrdup("jpg");
     format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
   }
-  if( strcasecmp(driver,"CAIRO/PDF") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/PDF") == 0 ) {
     if(!name) name="pdf";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("application/x-pdf");
@@ -245,7 +245,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->extension = msStrdup("pdf");
     format->renderer = MS_RENDER_WITH_CAIRO_PDF;
   }
-  if( strcasecmp(driver,"CAIRO/SVG") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/SVG") == 0 ) {
     if(!name) name="svg";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/svg+xml");
@@ -254,7 +254,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->renderer = MS_RENDER_WITH_CAIRO_SVG;
   }
 #ifdef _WIN32
-  if( strcasecmp(driver,"CAIRO/WINGDI") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/WINGDI") == 0 ) {
     if(!name) name="cairowinGDI";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("");
@@ -262,7 +262,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->extension = msStrdup("");
     format->renderer = MS_RENDER_WITH_CAIRO_RASTER;
   }
-  if( strcasecmp(driver,"CAIRO/WINGDIPRINT") == 0 ) {
+  else if( strcasecmp(driver,"CAIRO/WINGDIPRINT") == 0 ) {
     if(!name) name="cairowinGDIPrint";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("");
@@ -274,7 +274,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 #endif
 
 #if defined(USE_OGL)
-  if( strcasecmp(driver,"OGL/PNG") == 0 ) {
+  else if( strcasecmp(driver,"OGL/PNG") == 0 ) {
     if(!name) name="oglpng24";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("image/png; mode=24bit");
@@ -285,7 +285,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 #endif
 
 #if defined(USE_KML)
-  if( strcasecmp(driver,"KML") == 0 ) {
+  else if( strcasecmp(driver,"KML") == 0 ) {
     if(!name) name="kml";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("application/vnd.google-earth.kml+xml");
@@ -294,7 +294,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->renderer = MS_RENDER_WITH_KML;
     msSetOutputFormatOption( format, "ATTACHMENT", "mapserver.kml");
   }
-  if( strcasecmp(driver,"KMZ") == 0 ) {
+  else if( strcasecmp(driver,"KMZ") == 0 ) {
     if(!name) name="kmz";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = strdup("application/vnd.google-earth.kmz");
@@ -308,7 +308,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
 
 
 #ifdef USE_GDAL
-  if( strncasecmp(driver,"gdal/",5) == 0 ) {
+  else if( strncasecmp(driver,"gdal/",5) == 0 ) {
     if(!name) name=driver+5;
     format = msAllocOutputFormat( map, name, driver );
     if( msInitDefaultGDALOutputFormat( format ) == MS_FAILURE ) {
@@ -323,7 +323,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
   }
 #endif
 #ifdef USE_OGR
-  if( strncasecmp(driver,"ogr/",4) == 0 ) {
+  else if( strncasecmp(driver,"ogr/",4) == 0 ) {
     if(!name) name=driver+4;
     format = msAllocOutputFormat( map, name, driver );
     if( msInitDefaultOGROutputFormat( format ) == MS_FAILURE ) {
@@ -337,7 +337,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     }
   }
 #endif
-  if( strcasecmp(driver,"imagemap") == 0 ) {
+  else if( strcasecmp(driver,"imagemap") == 0 ) {
     if(!name) name="imagemap";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("text/html; driver=imagemap");
@@ -346,7 +346,7 @@ outputFormatObj *msCreateDefaultOutputFormat( mapObj *map,
     format->renderer = MS_RENDER_WITH_IMAGEMAP;
   }
 
-  if( strcasecmp(driver,"template") == 0 ) {
+  else if( strcasecmp(driver,"template") == 0 ) {
     if(!name) name="template";
     format = msAllocOutputFormat( map, name, driver );
     format->mimetype = msStrdup("text/html");
@@ -473,18 +473,17 @@ 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 );
+  assert(map);
+  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;
-    MS_REFCNT_INCR(format);
-  }
+  map->outputformatlist[map->numoutputformats-1] = format;
+  MS_REFCNT_INCR(format);
 
   return map->numoutputformats;
 }
@@ -855,7 +854,6 @@ void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime )
         mime_list[mime_count++] = format->mimetype;
       }
     }
-    msFreeCharArray(tokens, numtokens);
   } else
     for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ ) {
       int  j;
@@ -880,6 +878,8 @@ void msGetOutputFormatMimeListImg( mapObj *map, char **mime_list, int max_mime )
 
   if( mime_count < max_mime )
     mime_list[mime_count] = NULL;
+  if(tokens)
+    msFreeCharArray(tokens, numtokens);
 }
 
 /************************************************************************/
@@ -905,7 +905,6 @@ void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime )
         mime_list[mime_count++] = format->mimetype;
       }
     }
-    msFreeCharArray(tokens, numtokens);
   } else {
     for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ ) {
       int  j;
@@ -935,6 +934,8 @@ void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime )
   }
   if( mime_count < max_mime )
     mime_list[mime_count] = NULL;
+  if(tokens)
+    msFreeCharArray(tokens, numtokens);
 }
 
 
diff --git a/mapows.c b/mapows.c
index cdacbb3..d07e689 100644
--- a/mapows.c
+++ b/mapows.c
@@ -79,6 +79,17 @@ static void msOWSClearRequestObj(owsRequestObj *ows_request)
   }
 }
 
+#if defined(USE_LIBXML2) && LIBXML_VERSION < 20900
+static int bExternalEntityAsked = FALSE;
+static xmlParserInputPtr  dummyEntityLoader(const char * URL, 
+                                           const char * ID, 
+                                           xmlParserCtxtPtr context )
+{
+    bExternalEntityAsked = TRUE;
+    return NULL;
+}
+#endif
+
 /*
 ** msOWSPreParseRequest() parses a cgiRequestObj either with GET/KVP
 ** or with POST/XML. Only SERVICE, VERSION (or WMTVER) and REQUEST are
@@ -117,6 +128,9 @@ static int msOWSPreParseRequest(cgiRequestObj *request,
   } else if (request->type == MS_POST_REQUEST) {
 #if defined(USE_LIBXML2)
     xmlNodePtr root = NULL;
+#if LIBXML_VERSION < 20900
+    xmlExternalEntityLoader oldExternalEntityLoader;
+#endif
 #elif defined(USE_GDAL)
     CPLXMLNode *temp;
 #endif
@@ -126,9 +140,24 @@ static int msOWSPreParseRequest(cgiRequestObj *request,
       return MS_FAILURE;
     }
 #if defined(USE_LIBXML2)
+#if LIBXML_VERSION < 20900
+    oldExternalEntityLoader = xmlGetExternalEntityLoader();
+    /* to avoid  XML External Entity vulnerability with libxml2 < 2.9 */
+    xmlSetExternalEntityLoader (dummyEntityLoader); 
+    bExternalEntityAsked = FALSE;
+#endif
     /* parse to DOM-Structure with libxml2 and get the root element */
     ows_request->document = xmlParseMemory(request->postrequest,
                                            strlen(request->postrequest));
+#if LIBXML_VERSION < 20900
+    xmlSetExternalEntityLoader (oldExternalEntityLoader); 
+    if( bExternalEntityAsked )
+    {
+        msSetError(MS_OWSERR, "XML parsing error: %s",
+                 "msOWSPreParseRequest()", "External entity fetch");
+        return MS_FAILURE;
+    }
+#endif
     if (ows_request->document == NULL
         || (root = xmlDocGetRootElement(ows_request->document)) == NULL) {
       xmlErrorPtr error = xmlGetLastError();
@@ -846,21 +875,19 @@ 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 );
+    size_t bufferSize = strlen(name)+strlen(validated_language)+2;
+    char *name2 = (char *) msSmallMalloc( bufferSize );
     snprintf(name2, bufferSize, "%s.%s", name, validated_language);
     value = msOWSLookupMetadata(metadata, namespaces, name2);
+    free(name2);
   }
 
-  if (value == NULL) {
+  if ( name && !value ) {
     value = msOWSLookupMetadata(metadata, namespaces, name);
   }
 
-  msFree( name2 );
 
   return value;
 }
@@ -1319,7 +1346,7 @@ int msOWSPrintInspireCommonMetadata(FILE *stream, mapObj *map, const char *names
     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", "");
+    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_keyword", OWS_WARN, "    <inspire_common:MandatoryKeyword>\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) {
@@ -1644,7 +1671,7 @@ int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
     value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
     if(value != NULL) {
       encoded = msEncodeHTMLEntities(value);
-      buffer_size_tmp = strlen(type_format)+strlen(encoded);
+      buffer_size_tmp = strlen(type_format)+strlen(encoded)+1;
       type = (char*)malloc(buffer_size_tmp);
       snprintf(type, buffer_size_tmp, type_format, encoded);
       msFree(encoded);
@@ -1657,7 +1684,7 @@ int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
     value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
     if(value != NULL) {
       encoded = msEncodeHTMLEntities(value);
-      buffer_size_tmp = strlen(width_format)+strlen(encoded);
+      buffer_size_tmp = strlen(width_format)+strlen(encoded)+1;
       width = (char*)malloc(buffer_size_tmp);
       snprintf(width, buffer_size_tmp, width_format, encoded);
       msFree(encoded);
@@ -1670,7 +1697,7 @@ int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
     value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
     if(value != NULL) {
       encoded = msEncodeHTMLEntities(value);
-      buffer_size_tmp = strlen(height_format)+strlen(encoded);
+      buffer_size_tmp = strlen(height_format)+strlen(encoded)+1;
       height = (char*)malloc(buffer_size_tmp);
       snprintf(height, buffer_size_tmp, height_format, encoded);
       msFree(encoded);
@@ -1683,7 +1710,7 @@ int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
     value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
     if(value != NULL) {
       encoded = msEncodeHTMLEntities(value);
-      buffer_size_tmp = strlen(urlfrmt_format)+strlen(encoded);
+      buffer_size_tmp = strlen(urlfrmt_format)+strlen(encoded)+1;
       urlfrmt = (char*)malloc(buffer_size_tmp);
       snprintf(urlfrmt, buffer_size_tmp, urlfrmt_format, encoded);
       msFree(encoded);
@@ -1696,7 +1723,7 @@ int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
     value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
     if(value != NULL) {
       encoded = msEncodeHTMLEntities(value);
-      buffer_size_tmp = strlen(href_format)+strlen(encoded);
+      buffer_size_tmp = strlen(href_format)+strlen(encoded)+1;
       href = (char*)malloc(buffer_size_tmp);
       snprintf(href, buffer_size_tmp, href_format, encoded);
       msFree(encoded);
@@ -1868,8 +1895,8 @@ int msOWSPrintMetadataList(FILE *stream, hashTableObj *metadata,
         msIO_fprintf(stream, itemFormat, keywords[kw]);
       }
       if(endTag) msIO_fprintf(stream, "%s", endTag);
-      msFreeCharArray(keywords, numkeywords);
     }
+    msFreeCharArray(keywords, numkeywords);
     return MS_TRUE;
   }
   return MS_FALSE;
@@ -1919,8 +1946,8 @@ int msOWSPrintEncodeMetadataList(FILE *stream, hashTableObj *metadata,
         msFree(encoded);
       }
       if(endTag) msIO_fprintf(stream, "%s", endTag);
-      msFreeCharArray(keywords, numkeywords);
     }
+    msFreeCharArray(keywords, numkeywords);
     return MS_TRUE;
   }
   return MS_FALSE;
@@ -1961,8 +1988,8 @@ int msOWSPrintEncodeParamList(FILE *stream, const char *name,
       msFree(encoded);
     }
     if(endTag) msIO_fprintf(stream, "%s", endTag);
-    msFreeCharArray(items, numitems);
   }
+  msFreeCharArray(items, numitems);
 
   return status;
 }
@@ -2091,24 +2118,24 @@ void msOWSPrintBoundingBox(FILE *stream, const char *tabspace,
 
   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) {
-        msProjectRect(srcproj, &proj, &ext);
-      }
-      /*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) {
-        msAxisNormalizePoints( &proj, 1, &(ext.minx), &(ext.miny) );
-        msAxisNormalizePoints( &proj, 1, &(ext.maxx), &(ext.maxy) );
+    if( value && *value) {
+      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) {
+          msProjectRect(srcproj, &proj, &ext);
+        }
+        /*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) {
+          msAxisNormalizePoints( &proj, 1, &(ext.minx), &(ext.miny) );
+          msAxisNormalizePoints( &proj, 1, &(ext.maxx), &(ext.maxy) );
+        }
       }
-    }
-    msFreeProjection( &proj );
+      msFreeProjection( &proj );
 
-    if( value != NULL ) {
       encoded = msEncodeHTMLEntities(value);
       if (wms_version >= OWS_1_3_0)
         msIO_fprintf(stream, "%s<BoundingBox CRS=\"%s\"\n"
@@ -2315,6 +2342,11 @@ void msOWSProcessException(layerObj *lp, const char *pszFname,
 
     fseek(fp, 0, SEEK_END);
     nBufSize = ftell(fp);
+    if(nBufSize < 0) {
+      msSetError(MS_IOERR, NULL, "msOWSProcessException()");
+      fclose(fp);
+      return;
+    }
     rewind(fp);
     pszBuf = (char*)malloc((nBufSize+1)*sizeof(char));
     if (pszBuf == NULL) {
@@ -2770,10 +2802,11 @@ outputFormatObj* msOwsIsOutputFormatValid(mapObj *map, const char *format,
         if (mimetype && strcasecmp(mimetype, format) == 0)
           break;
       }
-      msFreeCharArray(tokens, n);
       if (i < n)
         psFormat = msSelectOutputFormat( map, format);
     }
+    if(tokens)
+      msFreeCharArray(tokens, n);
   }
 
   return psFormat;
diff --git a/mappostgis.c b/mappostgis.c
index bfee929..7aa3149 100644
--- a/mappostgis.c
+++ b/mappostgis.c
@@ -503,7 +503,7 @@ wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
 {
   int npoints = 0;
   int type, ncomponents, i, j;
-  lineObj *line;
+  lineObj line;
   shapeObj shapebuf;
 
   /*endian = */wkbReadChar(w);
@@ -533,10 +533,8 @@ wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
   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);
+  line.numpoints = npoints;
+  line.point = msSmallMalloc(sizeof(pointObj) * npoints);
 
   /* Copy in the points */
   npoints = 0;
@@ -544,19 +542,19 @@ wkbConvCompoundCurveToShape(wkbObj *w, shapeObj *shape)
     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 ) {
+          memcmp(&(line.point[npoints - 1]),&(shapebuf.line[i].point[j]),sizeof(pointObj)) == 0 ) {
         continue;
       }
-      line->point[npoints++] = shapebuf.line[i].point[j];
+      line.point[npoints++] = shapebuf.line[i].point[j];
     }
   }
-  line->numpoints = npoints;
+  line.numpoints = npoints;
 
   /* Clean up */
   msFreeShape(&shapebuf);
 
   /* Fill in the lineObj */
-  msAddLineDirectly(shape, line);
+  msAddLineDirectly(shape, &line);
 
   return MS_SUCCESS;
 }
@@ -1109,9 +1107,6 @@ msPostGISRetrievePK(layerObj *layer)
   msPostGISLayerInfo *layerinfo = 0;
   int length;
   int pgVersion;
-  char *pos_sep;
-  char *schema = NULL;
-  char *table = NULL;
 
   if (layer->debug) {
     msDebug("msPostGISRetrievePK called.\n");
@@ -1119,21 +1114,6 @@ msPostGISRetrievePK(layerObj *layer)
 
   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);
-
-    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 (layerinfo->pgconn == NULL) {
     msSetError(MS_QUERYERR, "Layer does not have a postgis connection.", "msPostGISRetrievePK()");
@@ -1160,9 +1140,27 @@ msPostGISRetrievePK(layerObj *layer)
     ** 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));
+    sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v72sql) + 1);
     sprintf(sql, v72sql, layerinfo->fromsource);
   } else {
+    /* Attempt to separate fromsource into schema.table */
+    char *pos_sep;
+    char *schema = NULL;
+    char *table = NULL;
+    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) + 1;
+      table = (char*)msSmallMalloc(length);
+      strlcpy(table, pos_sep + 1, length);
+
+      if (layer->debug) {
+        msDebug("msPostGISRetrievePK(): Found schema %s, table %s.\n", schema, table);
+      }
+    }
     /*
     ** PostgreSQL v7.3 and later treat primary keys as constraints.
     ** We only support single column primary keys, so multicolumn
@@ -1170,15 +1168,15 @@ msPostGISRetrievePK(layerObj *layer)
     */
     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));
+      sql = msSmallMalloc(strlen(schema) + strlen(table) + strlen(v73sql) + 1);
       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));
+      sql = msSmallMalloc(strlen(layerinfo->fromsource) + strlen(v73sql) + 1);
       sprintf(sql, v73sql, layerinfo->fromsource);
     }
+    free(table);
+    free(schema);
   }
 
   if (layer->debug > 1) {
@@ -1664,7 +1662,7 @@ char *msPostGISBuildSQLItems(layerObj *layer)
       else
         force2d = "ST_Force_2D";
     }
-    strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(force2d) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid));
+    strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(force2d) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid) + 1);
     sprintf(strGeom, strGeomTemplate, force2d, layerinfo->geomcolumn, strEndian, layerinfo->uid);
   }
 
@@ -1769,9 +1767,9 @@ char *msPostGISBuildSQLSRID(layerObj *layer)
         return NULL;
       }
     }
-    strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn));
+    strSRID = msSmallMalloc(strlen(strSRIDTemplate) + strlen(f_table_name) + strlen(layerinfo->geomcolumn) + 1);
     sprintf(strSRID, strSRIDTemplate, f_table_name, layerinfo->geomcolumn);
-    if ( f_table_name ) free(f_table_name);
+    free(f_table_name);
   }
   return strSRID;
 }
@@ -1928,6 +1926,8 @@ char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
     /* We see to set the SRID on the box, but to what SRID? */
     strSRID = msPostGISBuildSQLSRID(layer);
     if ( ! strSRID ) {
+      free( strLimit );
+      free( strOffset );
       return NULL;
     }
 
@@ -1936,20 +1936,22 @@ char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
       strBoxLength = strlen(strBox);
     } else {
       msSetError(MS_MISCERR, "Unable to build box SQL.", "msPostGISBuildSQLWhere()");
+      free( strLimit );
+      free( strOffset );
       return NULL;
     }
 
-    strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn));
+    strRect = (char*)msSmallMalloc(strlen(strRectTemplate) + strBoxLength + strlen(layerinfo->geomcolumn) +1 );
     sprintf(strRect, strRectTemplate, layerinfo->geomcolumn, strBox);
     strRectLength = strlen(strRect);
-    if (strBox) free(strBox);
-    if (strSRID) free(strSRID);
+    free(strBox);
+    free(strSRID);
   }
 
   /* Populate strFilter, if necessary. */
   if ( layer->filter.string ) {
     static char *strFilterTemplate = "(%s)";
-    strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string));
+    strFilter = (char*)msSmallMalloc(strlen(strFilterTemplate) + strlen(layer->filter.string)+1);
     sprintf(strFilter, strFilterTemplate, layer->filter.string);
     strFilterLength = strlen(strFilter);
   }
@@ -1963,7 +1965,7 @@ char *msPostGISBuildSQLWhere(layerObj *layer, rectObj *rect, long *uid)
   }
 
   bufferSize = strRectLength + 5 + strFilterLength + 5 + strUidLength
-               + strLimitLength + strOffsetLength;
+               + strLimitLength + strOffsetLength + 1;
   strWhere = (char*)msSmallMalloc(bufferSize);
   *strWhere = '\0';
   if ( strRect ) {
@@ -2052,11 +2054,11 @@ char *msPostGISBuildSQL(layerObj *layer, rectObj *rect, long *uid)
 
   strSQLTemplate = strlen(strWhere) ? strSQLTemplate0 : strSQLTemplate1;
 
-  strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere));
+  strSQL = msSmallMalloc(strlen(strSQLTemplate) + strlen(strFrom) + strlen(strItems) + strlen(strWhere) + 1);
   sprintf(strSQL, strSQLTemplate, strItems, strFrom, strWhere);
-  if (strItems) free(strItems);
-  if (strFrom) free(strFrom);
-  if (strWhere) free(strWhere);
+  free(strItems);
+  free(strFrom);
+  free(strWhere);
 
   return strSQL;
 
@@ -2273,6 +2275,7 @@ int msPostGISLayerOpen(layerObj *layer)
 
     if (!layer->connection) {
       msSetError(MS_MISCERR, "Missing CONNECTION keyword.", "msPostGISLayerOpen()");
+      free(layerinfo);
       return MS_FAILURE;
     }
 
@@ -2281,6 +2284,7 @@ int msPostGISLayerOpen(layerObj *layer)
     */
     conn_decrypted = msDecryptStringTokens(layer->map, layer->connection);
     if (conn_decrypted == NULL) {
+      free(layerinfo);
       return MS_FAILURE;  /* An error should already have been produced */
     }
     layerinfo->pgconn = PQconnectdb(conn_decrypted);
@@ -2307,6 +2311,7 @@ int msPostGISLayerOpen(layerObj *layer)
 
       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);
 
+      if(layerinfo->pgconn) PQfinish(layerinfo->pgconn);
       free(maskeddata);
       free(layerinfo);
       return MS_FAILURE;
@@ -2325,6 +2330,10 @@ int msPostGISLayerOpen(layerObj *layer)
       if( PQstatus(layerinfo->pgconn) != CONNECTION_OK ) {
         /* Nope, time to bail out. */
         msSetError(MS_QUERYERR, "PostgreSQL database connection gone bad (%s)", "msPostGISLayerOpen()", PQerrorMessage(layerinfo->pgconn));
+        free(layerinfo);
+        /* FIXME: we should also release the connection from the pool in this case, but it is stale...
+         * for the time being we do not release it so it can never be used again. If this happens multiple
+         * times there will be a leak... */
         return MS_FAILURE;
       }
 
@@ -2333,7 +2342,11 @@ int msPostGISLayerOpen(layerObj *layer)
 
   /* Get the PostGIS version number from the database */
   layerinfo->version = msPostGISRetrieveVersion(layerinfo->pgconn);
-  if( layerinfo->version == MS_FAILURE ) return MS_FAILURE;
+  if( layerinfo->version == MS_FAILURE ) {
+    msConnPoolRelease(layer, layerinfo->pgconn);
+    free(layerinfo);
+    return MS_FAILURE;
+  }
   if (layer->debug)
     msDebug("msPostGISLayerOpen: Got PostGIS version %d.\n", layerinfo->version);
 
@@ -3241,8 +3254,10 @@ int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char
 
     /* multiple times, or ranges */
     atimes = msStringSplit (timestring, ',', &numtimes);
-    if (atimes == NULL || numtimes < 1)
+    if (atimes == NULL || numtimes < 1) {
+      msFreeCharArray(atimes, numtimes);
       return MS_FALSE;
+    }
 
     strlcat(buffer, "(", buffer_size);
     for(i=0; i<numtimes; i++) {
@@ -3251,7 +3266,6 @@ int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char
       }
       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);
@@ -3261,6 +3275,8 @@ int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char
         createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
         strlcat(buffer, bufferTmp, buffer_size);
       } else {
+        msFreeCharArray(aranges, numranges);
+        msFreeCharArray(atimes, numtimes);
         return MS_FALSE;
       }
       msFreeCharArray(aranges, numranges);
diff --git a/mappostgresql.c b/mappostgresql.c
index da3fcca..69b8492 100644
--- a/mappostgresql.c
+++ b/mappostgresql.c
@@ -76,7 +76,7 @@ int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join)
 {
   char *maskeddata, *temp, *sql, *column;
   char *conn_decrypted;
-  int i, count, test;
+  int i, test;
   PGresult *query_result;
   msPOSTGRESQLJoinInfo *joininfo;
 
@@ -128,11 +128,10 @@ int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join)
     maskeddata = (char *)malloc(strlen(layer->connection) + 1);
     strcpy(maskeddata, join->connection);
     temp = strstr(maskeddata, "password=");
-    if(!temp) {
+    if(temp) {
       temp = (char *)(temp + 9);
-      count = (int)(strstr(temp, " ") - temp);
-      for(i = 0; i < count; i++) {
-        strlcpy(temp, "*", (int)1);
+      while (*temp != '\0' && *temp != ' ') {
+        *temp = '*';
         temp++;
       }
     }
diff --git a/mapprimitive.c b/mapprimitive.c
index 9a02589..aea4a65 100644
--- a/mapprimitive.c
+++ b/mapprimitive.c
@@ -1299,7 +1299,9 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
   double len, max_len=0;
   double minx, maxx, maxy, miny;
 
+#ifdef notdef
   int method = 2;
+#endif
 
   msComputeBounds(p);
   minx = p->bounds.minx;
@@ -1313,6 +1315,7 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
   cp.x = (maxx+minx)/2.0;
   cp.y = (maxy+miny)/2.0;
 
+#ifdef notdef
   switch (method) {
     case 0: /* MBR */
       lp->x = cp.x;
@@ -1325,6 +1328,9 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       if(getPolygonCenterOfGravity(p, lp) != MS_SUCCESS) return(MS_FAILURE);
       break;
   }
+#else
+  if(getPolygonCenterOfGravity(p, lp) != MS_SUCCESS) return(MS_FAILURE);
+#endif
 
   if(msIntersectPointPolygon(lp, p) == MS_TRUE) {
     double dist, min_dist=-1;
@@ -1385,8 +1391,10 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       }
     }
 
-    if(min == max)
+    if(min == max) { 
+      msFree(intersect);
       return (MS_FAILURE);
+    }
     else
       y = (max + min)/2.0;
 
@@ -1459,8 +1467,10 @@ int msPolygonLabelPoint(shapeObj *p, pointObj *lp, double min_dimension)
       }
     }
 
-    if(min == max)
+    if(min == max) {
+      msFree(intersect);
       return (MS_FAILURE);
+    }
     else
       x = (max + min)/2.0;
 
diff --git a/mapproject.c b/mapproject.c
index 8d2a5f7..479a2ff 100644
--- a/mapproject.c
+++ b/mapproject.c
@@ -133,7 +133,7 @@ int msProjectPoint(projectionObj *in, projectionObj *out, pointObj *point)
   /* -------------------------------------------------------------------- */
   else {
     /* nothing to do if the other coordinate system is also lat/long */
-    if( in == NULL && out != NULL && pj_is_latlong(out->proj) )
+    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;
diff --git a/mapquantization.c b/mapquantization.c
index de923af..996b4a3 100644
--- a/mapquantization.c
+++ b/mapquantization.c
@@ -150,7 +150,7 @@ int msQuantizeRasterBuffer(rasterBufferObj *rb,
 
   *palette_scaling_maxval = 255;
 
-  apixels=(rgbaPixel**)msSmallMalloc(rb->height*sizeof(rgbaPixel**));
+  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]));
@@ -498,14 +498,18 @@ mediancut( acolorhist_vector achv, int colors, int sum, unsigned char maxval, in
       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;
+    if(sum>0) {
+      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;
+    } else {
+      r = g = b = 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*/
diff --git a/mapquery.c b/mapquery.c
index 9693ed6..f3b791f 100644
--- a/mapquery.c
+++ b/mapquery.c
@@ -239,7 +239,7 @@ static int loadQueryResults(mapObj *map, FILE *stream)
     GET_LAYER(map, j)->resultcache = (resultCacheObj *)malloc(sizeof(resultCacheObj)); /* allocate and initialize the result cache */
     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 */
+    if(1 != fread(&(GET_LAYER(map, j)->resultcache->numresults), sizeof(int), 1, stream) || (GET_LAYER(map, j)->resultcache->numresults < 0)) { /* 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;
@@ -375,7 +375,7 @@ static int loadQueryParams(mapObj *map, FILE *stream)
 
           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", &numpoints) != 1 || numpoints<0) goto parse_error;
 
             line.numpoints = numpoints;
             line.point = (pointObj *) msSmallMalloc(line.numpoints*sizeof(pointObj));
@@ -1889,7 +1889,6 @@ int msQueryByShape(mapObj *map)
     initResultCache( lp->resultcache);
 
     nclasses = 0;
-    classgroup = NULL;
     if (lp->classgroup && lp->numclasses > 0)
       classgroup = msAllocateValidClassGroups(lp, &nclasses);
 
@@ -2017,9 +2016,14 @@ int msQueryByShape(mapObj *map)
       }
     } /* next shape */
 
-    if(status != MS_DONE) return(MS_FAILURE);
+    if(status != MS_DONE) {
+      free(classgroup);
+      return(MS_FAILURE);
+    }
 
     if(lp->resultcache->numresults == 0) msLayerClose(lp); /* no need to keep the layer open */
+    free(classgroup);
+    classgroup = NULL;
   } /* next layer */
 
   /* was anything found? */
diff --git a/maprasterquery.c b/maprasterquery.c
index 17f039a..a420e0b 100644
--- a/maprasterquery.c
+++ b/maprasterquery.c
@@ -1021,7 +1021,7 @@ int msRasterQueryByPoint(mapObj *map, layerObj *layer, int mode, pointObj p,
 
   result = msRasterQueryByRect( map, layer, bufferRect );
 
-  if( rlinfo != NULL && maxresults != 0 )
+  if( maxresults != 0 )
     rlinfo->query_result_hard_max = previous_maxresults;
 
   return result;
diff --git a/maprendering.c b/maprendering.c
index 1852f62..73a2875 100644
--- a/maprendering.c
+++ b/maprendering.c
@@ -497,7 +497,7 @@ int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p,
       rendererVTableObj *renderer = image->format->vtable;
       symbolObj *symbol;
       shapeObj *offsetLine = p;
-      int i;
+      int i,ret=MS_SUCCESS;
       double width;
       double finalscalefactor;
 
@@ -546,13 +546,15 @@ int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p,
         else {
           /* msSetError(MS_MISCERR,"no color defined for line styling","msDrawLineSymbol()");
            * not really an error */
-          return MS_SUCCESS;
+          ret = MS_SUCCESS;
+          goto line_cleanup;
         }
         renderer->renderLine(image,offsetLine,&s);
       } else {
         symbolStyleObj s;
         if(preloadSymbol(symbolset, symbol, renderer) != MS_SUCCESS) {
-          return MS_FAILURE;
+          ret = MS_FAILURE;
+          goto line_cleanup;
         }
 
         INIT_SYMBOL_STYLE(s);
@@ -584,15 +586,17 @@ int msDrawLineSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p,
             renderer->renderLineTiled(image, offsetLine, tile);
           } else {
             msSetError(MS_RENDERERERR, "renderer does not support brushed lines", "msDrawLineSymbol()");
-            return MS_FAILURE;
+            ret = MS_FAILURE;
+            goto line_cleanup;
           }
         }
       }
-
+line_cleanup:
       if(offsetLine!=p) {
         msFreeShape(offsetLine);
         msFree(offsetLine);
       }
+      return ret;
     } else if( MS_RENDERER_IMAGEMAP(image->format) )
       msDrawLineSymbolIM(symbolset, image, p, style, scalefactor);
     else {
@@ -699,7 +703,8 @@ int msDrawShadeSymbol(symbolSetObj *symbolset, imageObj *image, shapeObj *p, sty
         int seamless = 0;
 
         if(preloadSymbol(symbolset,symbol,renderer) != MS_SUCCESS) {
-          return MS_FAILURE;
+          ret = MS_FAILURE;
+          goto cleanup;
         }
 
         INIT_SYMBOL_STYLE(s);
@@ -815,7 +820,7 @@ int msDrawMarkerSymbol(symbolSetObj *symbolset,imageObj *image, pointObj *p, sty
       if(symbol->anchorpoint_x != 0.5 || symbol->anchorpoint_y != 0.5) {
         double sx,sy;
         double ox, oy;
-        msGetMarkerSize(symbolset, style, &sx, &sy, scalefactor);
+        if(msGetMarkerSize(symbolset, style, &sx, &sy, scalefactor) != MS_SUCCESS) return MS_FAILURE;
         ox = (0.5 - symbol->anchorpoint_x) * sx;
         oy = (0.5 - symbol->anchorpoint_y) * sy;
         if(s.rotation != 0) {
diff --git a/mapresample.c b/mapresample.c
index 419d07b..15e939c 100644
--- a/mapresample.c
+++ b/mapresample.c
@@ -671,7 +671,7 @@ msAverageRasterResampler( imageObj *psSrcImage, rasterBufferObj *src_rb,
               alpha = (unsigned char)
                       MAX(0,MIN(255,255*dfAlpha01+0.5));
 
-              RB_SET_PIXEL(dst_rb,nDstX,nDstY,
+              RB_MIX_PIXEL(dst_rb,nDstX,nDstY,
                            red, green, blue, alpha );
             }
 #ifdef USE_GD
@@ -777,8 +777,10 @@ void *msInitProjTransformer( projectionObj *psSrc,
     psPTInfo->bSrcIsGeographic = MS_FALSE;
 
   if( !InvGeoTransform(padfSrcGeoTransform,
-                       psPTInfo->adfInvSrcGeoTransform) )
+                       psPTInfo->adfInvSrcGeoTransform) ) {
+    free(psPTInfo);
     return NULL;
+  }
 
   /* -------------------------------------------------------------------- */
   /*      Record destination image information.                           */
diff --git a/mapscript/csharp/CMakeLists.txt b/mapscript/csharp/CMakeLists.txt
index a1f03bb..27a28b9 100644
--- a/mapscript/csharp/CMakeLists.txt
+++ b/mapscript/csharp/CMakeLists.txt
@@ -18,9 +18,9 @@ if (WIN32)
     endif(CMAKE_CL_64)
 	set (KEYFILE_SPEC /keyfile:${PROJECT_SOURCE_DIR}\\mapscript\\csharp\\mapscript.snk)
   endif (NOT MSVC71)
-  if (MSVC10)
+  if (MSVC_VERSION GREATER 1500)
       set(PLATFORM_TARGET ${PLATFORM_TARGET} /define:CLR4)
-  endif (MSVC10)
+  endif (MSVC_VERSION GREATER 1500)
 endif(WIN32)
 
 MARK_AS_ADVANCED(CSHARP_COMPILER)
diff --git a/mapscript/java/.gitignore b/mapscript/java/.gitignore
deleted file mode 100644
index 6b468b6..0000000
--- a/mapscript/java/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-*.class
diff --git a/mapscript/perl/.gitignore b/mapscript/perl/.gitignore
deleted file mode 100644
index 494b952..0000000
--- a/mapscript/perl/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-blib/*
-mapscript.bs
-mapscript.pm
-mapscript_wrap.c
-pm_to_blib
diff --git a/mapscript/php/owsrequest.c b/mapscript/php/owsrequest.c
index 428c8dd..f01d361 100644
--- a/mapscript/php/owsrequest.c
+++ b/mapscript/php/owsrequest.c
@@ -32,6 +32,9 @@
 #include "php_mapscript.h"
 #include "SAPI.h"
 #include "php_variables.h"
+#if PHP_VERSION_ID >= 50600
+#include "php_streams.h"
+#endif
 
 char *owsrequest_getenv(const char *name, void *thread_context);
 
@@ -193,9 +196,29 @@ PHP_METHOD(OWSRequestObj, loadParams)
         cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv, NULL, 0, thread_context);
       }
     } else {
+#if PHP_VERSION_ID >= 50600
+      php_stream *s = php_stream_temp_new();
+      php_stream *input = php_stream_open_wrapper("php://input", "r", 0, NULL);
+
+      /* php://input does not support stat */
+      php_stream_copy_to_stream_ex(input, s, -1, NULL);
+      php_stream_close(input);
+
+      php_stream_rewind(s);
+      
+      char *raw_post_data = NULL;
+      long raw_post_data_length = 0;
+
+      raw_post_data_length = php_stream_copy_to_mem(s, raw_post_data, -1, 0);
+
+      cgirequestObj_loadParams(php_owsrequest->cgirequest, owsrequest_getenv,
+                               raw_post_data,
+                               raw_post_data_length, 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);
+#endif
     }
   }
 
diff --git a/mapserv.c b/mapserv.c
index e9499c5..84cb20e 100644
--- a/mapserv.c
+++ b/mapserv.c
@@ -263,16 +263,14 @@ int main(int argc, char *argv[])
 
 
 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);
+    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);
 #ifdef USE_FASTCGI
     /* FCGI_ --- return to top of loop */
     msResetErrorList();
diff --git a/mapservutil.c b/mapservutil.c
index bb791be..4b72d06 100644
--- a/mapservutil.c
+++ b/mapservutil.c
@@ -166,6 +166,14 @@ void msCGIWriteError(mapservObj *mapserv)
   }\
 } while (0)
 
+#define GET_NUMERIC_NO_ERROR(string,dbl) dbl = strtod((string), &strtoderr);
+
+#define FREE_TOKENS_ON_ERROR(ntok) if(!strtoderr) {\
+  msSetError(MS_TYPEERR, "invalid number", "msCGILoadForm()");\
+  msFreeCharArray(tokens,(ntok));\
+  return MS_FAILURE;\
+}
+
 static void setClassGroup(layerObj *layer, char *classgroup)
 {
   int i;
@@ -417,13 +425,18 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 4) {
         msSetError(MS_WEBERR, "Not enough arguments for imgext.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         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);
+      GET_NUMERIC_NO_ERROR(tokens[0],mapserv->ImgExt.minx);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[1],mapserv->ImgExt.miny);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[2],mapserv->ImgExt.maxx);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[3],mapserv->ImgExt.maxy);
+      FREE_TOKENS_ON_ERROR(4);
 
       msFreeCharArray(tokens, 4);
       continue;
@@ -457,13 +470,18 @@ int msCGILoadForm(mapservObj *mapserv)
 
         if(n != 4) {
           msSetError(MS_WEBERR, "Not enough arguments for mapext.", "msCGILoadForm()");
+          msFreeCharArray(tokens,n);
           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);
+        GET_NUMERIC_NO_ERROR(tokens[0],mapserv->map->extent.minx);
+        FREE_TOKENS_ON_ERROR(4);
+        GET_NUMERIC_NO_ERROR(tokens[1],mapserv->map->extent.miny);
+        FREE_TOKENS_ON_ERROR(4);
+        GET_NUMERIC_NO_ERROR(tokens[2],mapserv->map->extent.maxx);
+        FREE_TOKENS_ON_ERROR(4);
+        GET_NUMERIC_NO_ERROR(tokens[3],mapserv->map->extent.maxy);
+        FREE_TOKENS_ON_ERROR(4);
 
         msFreeCharArray(tokens, 4);
 
@@ -528,11 +546,14 @@ int msCGILoadForm(mapservObj *mapserv)
 
         if(n != 2) {
           msSetError(MS_WEBERR, "Not enough arguments for mapxy.", "msCGILoadForm()");
+          msFreeCharArray(tokens,n);
           return MS_FAILURE;
         }
 
-        GET_NUMERIC(tokens[0],mapserv->mappnt.x );
-        GET_NUMERIC(tokens[1],mapserv->mappnt.y );
+        GET_NUMERIC_NO_ERROR(tokens[0],mapserv->mappnt.x );
+        FREE_TOKENS_ON_ERROR(2);
+        GET_NUMERIC_NO_ERROR(tokens[1],mapserv->mappnt.y );
+        FREE_TOKENS_ON_ERROR(2);
 
         msFreeCharArray(tokens, 2);
 
@@ -575,19 +596,14 @@ int msCGILoadForm(mapservObj *mapserv)
 
         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()");
+          msFreeCharArray(tmp,n);
           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;
-        }
+        line.point = (pointObj *)msSmallMalloc(sizeof(pointObj)*line.numpoints);
 
-        if((mapserv->map->query.shape = (shapeObj *) malloc(sizeof(shapeObj))) == NULL) {
-          msSetError(MS_MEMERR, NULL, "msCGILoadForm()");
-          return MS_FAILURE;
-        }
+        mapserv->map->query.shape = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
         msInitShape(mapserv->map->query.shape);
         mapserv->map->query.shape->type = MS_SHAPE_POLYGON;
 
@@ -651,11 +667,14 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 2) {
         msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         return MS_FAILURE;
       }
 
-      GET_NUMERIC(tokens[0],mapserv->ImgPnt.x );
-      GET_NUMERIC(tokens[1],mapserv->ImgPnt.y );
+      GET_NUMERIC_NO_ERROR(tokens[0],mapserv->ImgPnt.x );
+      FREE_TOKENS_ON_ERROR(2);
+      GET_NUMERIC_NO_ERROR(tokens[1],mapserv->ImgPnt.y );
+      FREE_TOKENS_ON_ERROR(2);
 
       msFreeCharArray(tokens, 2);
 
@@ -681,13 +700,18 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 4) {
         msSetError(MS_WEBERR, "Not enough arguments for imgbox.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         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);
+      GET_NUMERIC_NO_ERROR(tokens[0],mapserv->ImgBox.minx);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[1],mapserv->ImgBox.miny);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[2],mapserv->ImgBox.maxx);
+      FREE_TOKENS_ON_ERROR(4);
+      GET_NUMERIC_NO_ERROR(tokens[3],mapserv->ImgBox.maxy);
+      FREE_TOKENS_ON_ERROR(4);
 
       msFreeCharArray(tokens, 4);
 
@@ -727,11 +751,14 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 2) {
         msSetError(MS_WEBERR, "Not enough arguments for imgxy.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         return MS_FAILURE;
       }
 
-      GET_NUMERIC(tokens[0],mapserv->RefPnt.x);
-      GET_NUMERIC(tokens[1],mapserv->RefPnt.y);
+      GET_NUMERIC_NO_ERROR(tokens[0],mapserv->RefPnt.x);
+      FREE_TOKENS_ON_ERROR(2);
+      GET_NUMERIC_NO_ERROR(tokens[1],mapserv->RefPnt.y);
+      FREE_TOKENS_ON_ERROR(2);
 
       msFreeCharArray(tokens, 2);
 
@@ -772,12 +799,15 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 2) {
         msSetError(MS_WEBERR, "Not enough arguments for imgsize.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         return MS_FAILURE;
       }
 
-      GET_NUMERIC(tokens[0],tmpval);
+      GET_NUMERIC_NO_ERROR(tokens[0],tmpval);
+      FREE_TOKENS_ON_ERROR(2);
       mapserv->ImgCols = (int)tmpval;
-      GET_NUMERIC(tokens[1],tmpval);
+      GET_NUMERIC_NO_ERROR(tokens[1],tmpval);
+      FREE_TOKENS_ON_ERROR(2);
       mapserv->ImgRows = (int)tmpval;
 
       msFreeCharArray(tokens, 2);
@@ -800,12 +830,15 @@ int msCGILoadForm(mapservObj *mapserv)
 
       if(n != 2) {
         msSetError(MS_WEBERR, "Not enough arguments for mapsize.", "msCGILoadForm()");
+        msFreeCharArray(tokens,n);
         return MS_FAILURE;
       }
 
-      GET_NUMERIC(tokens[0],tmpval);
+      GET_NUMERIC_NO_ERROR(tokens[0],tmpval);
+      FREE_TOKENS_ON_ERROR(2);
       mapserv->map->width = (int)tmpval;
-      GET_NUMERIC(tokens[1],tmpval);
+      GET_NUMERIC_NO_ERROR(tokens[1],tmpval);
+      FREE_TOKENS_ON_ERROR(2);
       mapserv->map->height = (int)tmpval;
 
       msFreeCharArray(tokens, 2);
@@ -820,7 +853,7 @@ int msCGILoadForm(mapservObj *mapserv)
     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) {
+      if (strcasecmp(mapserv->request->ParamValues[i], "all") == 0) {
         int l;
 
         /* Reset NumLayers=0. If individual layers were already selected then free the previous values.  */
@@ -844,8 +877,10 @@ int msCGILoadForm(mapservObj *mapserv)
 
         layers = msStringSplit(mapserv->request->ParamValues[i], ' ', &(num_layers));
         for(l=0; l<num_layers; l++) {
-          if(msGrowMapservLayers(mapserv) == MS_FAILURE)
+          if(msGrowMapservLayers(mapserv) == MS_FAILURE) {
+            msFreeCharArray(layers, num_layers);
             return MS_FAILURE;
+          }
           mapserv->Layers[mapserv->NumLayers++] = msStrdup(layers[l]);
         }
 
@@ -1248,6 +1283,7 @@ int msCGIDispatchQueryRequest(mapservObj *mapserv)
               break;
             case FROMUSERPNT:
               mapserv->map->query.type = MS_QUERY_BY_POINT;
+              break;
             default:
               if(MS_SUCCESS != setExtent(mapserv)) {
                 return MS_FAILURE;
@@ -1541,11 +1577,11 @@ int msCGIDispatchLegendRequest(mapservObj *mapserv)
 
 int msCGIDispatchLegendIconRequest(mapservObj *mapserv)
 {
-  char **tokens;
+  char **tokens = NULL;
   int numtokens=0;
   int layerindex=-1, classindex=0, status;
   outputFormatObj *format = NULL;
-  imageObj *img;
+  imageObj *img = NULL;
 
   /* TODO: do we want to set scale here? */
 
@@ -1560,29 +1596,38 @@ int msCGIDispatchLegendIconRequest(mapservObj *mapserv)
 
   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;
+    status = MS_FAILURE;
+    goto li_cleanup;
   }
 
   if((layerindex = msGetLayerIndex(mapserv->map, tokens[0])) == -1) {
     msSetError(MS_WEBERR, "Icon layer=%s not found in mapfile.", "mapserv()", tokens[0]);
-    return MS_FAILURE;
+    status = MS_FAILURE;
+    goto li_cleanup;
   }
 
   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;
+      status = MS_FAILURE;
+      goto li_cleanup;
     }
   }
 
   if(mapserv->Mode == MAPLEGENDICON) {
-    if(setExtent(mapserv) != MS_SUCCESS) return MS_FAILURE;
-    if(checkWebScale(mapserv) != MS_SUCCESS) return MS_FAILURE;
+    if(setExtent(mapserv) != MS_SUCCESS) {
+      status=MS_FAILURE;
+      goto li_cleanup;
+    }
+    if(checkWebScale(mapserv) != MS_SUCCESS) {
+      status=MS_FAILURE;
+      goto li_cleanup;
+    }
     mapserv->hittest = msSmallMalloc(sizeof(map_hittest));
     initMapHitTests(mapserv->map,mapserv->hittest);
     status = msHitTestLayer(mapserv->map, GET_LAYER(mapserv->map,layerindex),&mapserv->hittest->layerhits[layerindex]);
-    if(status != MS_SUCCESS) return MS_FAILURE;
+    if(status != MS_SUCCESS) goto li_cleanup;
   }
 
   /* ensure we have an image format representing the options for the legend. */
@@ -1591,18 +1636,25 @@ int msCGIDispatchLegendIconRequest(mapservObj *mapserv)
   /* initialize the legend image */
   if( ! MS_RENDERER_PLUGIN(format) ) {
     msSetError(MS_RENDERERERR, "unsupported renderer for legend icon", "mapserv main()");
-    return MS_FAILURE;
+    status = MS_FAILURE;
+    goto li_cleanup;
   }
   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));
+  if(!img) {
+    status = MS_FAILURE;
+    goto li_cleanup;
+  }
 
   /* 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_TRUE,
-      ((mapserv->hittest)?(&mapserv->hittest->layerhits[layerindex].classhits[classindex]):(NULL))) != MS_SUCCESS)
-    return MS_FAILURE;
+      ((mapserv->hittest)?(&mapserv->hittest->layerhits[layerindex].classhits[classindex]):(NULL))) != MS_SUCCESS) {
+    status = MS_FAILURE;
+    goto li_cleanup;
+  }
 
   if(mapserv->sendheaders) {
     msIO_setHeader("Content-Type","%s",MS_IMAGE_MIME_TYPE(mapserv->map->outputformat));
@@ -1614,12 +1666,13 @@ int msCGIDispatchLegendIconRequest(mapservObj *mapserv)
   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;
+  
+  status = msSaveImage(NULL, img, NULL);
 
+li_cleanup:
   msFreeCharArray(tokens, numtokens);
   msFreeImage(img);
-  return MS_SUCCESS;
+  return status;
 }
 
 int msCGIDispatchRequest(mapservObj *mapserv)
@@ -1758,15 +1811,15 @@ int msCGIHandler(const char *query_string, void **out_buffer, size_t *buffer_len
   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;
   }
+  
+  mapserv = msAllocMapServObj();
+  mapserv->request->type = MS_GET_REQUEST;
 
   /* don't modify the string */
   queryString = msStrdup(query_string);
diff --git a/mapshape.c b/mapshape.c
index b88ca4c..48d735a 100644
--- a/mapshape.c
+++ b/mapshape.c
@@ -283,7 +283,13 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   /*   Read the file size from the SHP file.            */
   /* -------------------------------------------------------------------- */
   pabyBuf = (uchar *) msSmallMalloc(100);
-  fread( pabyBuf, 100, 1, psSHP->fpSHP );
+  if(1 != fread( pabyBuf, 100, 1, psSHP->fpSHP )) {
+    fclose( psSHP->fpSHP );
+    fclose( psSHP->fpSHX );
+    free( psSHP );
+    free(pabyBuf);
+    return( NULL );
+  }
 
   psSHP->nFileSize = (pabyBuf[24] * 256 * 256 * 256
                       + pabyBuf[25] * 256 * 256
@@ -293,12 +299,21 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
   /* -------------------------------------------------------------------- */
   /*  Read SHX file Header info                                           */
   /* -------------------------------------------------------------------- */
-  fread( pabyBuf, 100, 1, psSHP->fpSHX );
+  if(1 != fread( pabyBuf, 100, 1, psSHP->fpSHX )) {
+    msSetError(MS_SHPERR, "Corrupted .shx file", "msSHPOpen()");
+    fclose( psSHP->fpSHP );
+    fclose( psSHP->fpSHX );
+    free( psSHP );
+    free(pabyBuf);
+    return( NULL );
+  }
 
   if( pabyBuf[0] != 0 || pabyBuf[1] != 0 || pabyBuf[2] != 0x27  || (pabyBuf[3] != 0x0a && pabyBuf[3] != 0x0d) ) {
+    msSetError(MS_SHPERR, "Corrupted .shp file", "msSHPOpen()");
     fclose( psSHP->fpSHP );
     fclose( psSHP->fpSHX );
     free( psSHP );
+    free(pabyBuf);
 
     return( NULL );
   }
@@ -313,6 +328,7 @@ SHPHandle msSHPOpen( const char * pszLayer, const char * pszAccess )
     fclose( psSHP->fpSHP );
     fclose( psSHP->fpSHX );
     free( psSHP );
+    free(pabyBuf);
     return( NULL );
   }
 
@@ -487,15 +503,23 @@ SHPHandle msSHPCreate( const char * pszLayer, int nShapeType )
   pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
   sprintf( pszFullname, "%s.shp", pszBasename );
   fpSHP = fopen(pszFullname, "wb" );
-  if( fpSHP == NULL )
+  if( fpSHP == NULL ) {
+    free( pszFullname );
+    free(pszBasename);
     return( NULL );
+  }
 
   sprintf( pszFullname, "%s.shx", pszBasename );
   fpSHX = fopen(pszFullname, "wb" );
-  if( fpSHX == NULL )
+  if( fpSHX == NULL ) {
+    fclose(fpSHP);
+    free( pszFullname );
+    free(pszBasename);
     return( NULL );
+  }
 
   free( pszFullname );
+  free(pszBasename);
 
   /* -------------------------------------------------------------------- */
   /*      Prepare header block for .shp file.                             */
@@ -656,26 +680,28 @@ int msSHPWritePoint(SHPHandle psSHP, pointObj *point )
   /* -------------------------------------------------------------------- */
   /*      Write out record.                                               */
   /* -------------------------------------------------------------------- */
-  fseek( psSHP->fpSHP, nRecordOffset, 0 );
-  fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
-  free( pabyRec );
+  if(fseek( psSHP->fpSHP, nRecordOffset, 0 ) == 0) {
+    fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
 
-  psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
-  psSHP->nFileSize += nRecordSize + 8;
+    psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
+    psSHP->nFileSize += nRecordSize + 8;
 
-  /* -------------------------------------------------------------------- */
-  /*  Expand file wide bounds based on this shape.        */
-  /* -------------------------------------------------------------------- */
-  if( psSHP->nRecords == 1 ) {
-    psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = point->x;
-    psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = point->y;
+    /* -------------------------------------------------------------------- */
+    /*  Expand file wide bounds based on this shape.        */
+    /* -------------------------------------------------------------------- */
+    if( psSHP->nRecords == 1 ) {
+      psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = point->x;
+      psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = point->y;
+    } else {
+      psSHP->adBoundsMin[0] = MS_MIN(psSHP->adBoundsMin[0], point->x);
+      psSHP->adBoundsMin[1] = MS_MIN(psSHP->adBoundsMin[1], point->y);
+      psSHP->adBoundsMax[0] = MS_MAX(psSHP->adBoundsMax[0], point->x);
+      psSHP->adBoundsMax[1] = MS_MAX(psSHP->adBoundsMax[1], point->y);
+    }
   } else {
-    psSHP->adBoundsMin[0] = MS_MIN(psSHP->adBoundsMin[0], point->x);
-    psSHP->adBoundsMin[1] = MS_MIN(psSHP->adBoundsMin[1], point->y);
-    psSHP->adBoundsMax[0] = MS_MAX(psSHP->adBoundsMax[0], point->x);
-    psSHP->adBoundsMax[1] = MS_MAX(psSHP->adBoundsMax[1], point->y);
+    psSHP->nRecords -- ;
   }
-
+  free( pabyRec );
   return( psSHP->nRecords - 1 );
 }
 
@@ -946,42 +972,46 @@ int msSHPWriteShape(SHPHandle psSHP, shapeObj *shape )
   /* -------------------------------------------------------------------- */
   /*      Write out record.                                               */
   /* -------------------------------------------------------------------- */
-  fseek( psSHP->fpSHP, nRecordOffset, 0 );
-  fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
-  free( pabyRec );
+  if(fseek( psSHP->fpSHP, nRecordOffset, 0 ) == 0) {
+    fwrite( pabyRec, nRecordSize+8, 1, psSHP->fpSHP );
 
-  psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
-  psSHP->nFileSize += nRecordSize + 8;
+    psSHP->panRecSize[psSHP->nRecords-1] = nRecordSize;
+    psSHP->nFileSize += nRecordSize + 8;
 
-  /* -------------------------------------------------------------------- */
-  /*  Expand file wide bounds based on this shape.        */
-  /* -------------------------------------------------------------------- */
-  if( psSHP->nRecords == 1 ) {
-    psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = shape->line[0].point[0].x;
-    psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = shape->line[0].point[0].y;
+    /* -------------------------------------------------------------------- */
+    /*  Expand file wide bounds based on this shape.        */
+    /* -------------------------------------------------------------------- */
+    if( psSHP->nRecords == 1 ) {
+      psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = shape->line[0].point[0].x;
+      psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = shape->line[0].point[0].y;
 #ifdef USE_POINT_Z_M
-    psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = shape->line[0].point[0].z;
-    psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = shape->line[0].point[0].m;
+      psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = shape->line[0].point[0].z;
+      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);
-      psSHP->adBoundsMin[1] = MS_MIN(psSHP->adBoundsMin[1], shape->line[i].point[j].y);
+    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);
+        psSHP->adBoundsMin[1] = MS_MIN(psSHP->adBoundsMin[1], shape->line[i].point[j].y);
 #ifdef USE_POINT_Z_M
-      psSHP->adBoundsMin[2] = MS_MIN(psSHP->adBoundsMin[2], shape->line[i].point[j].z);
-      psSHP->adBoundsMin[3] = MS_MIN(psSHP->adBoundsMin[3], shape->line[i].point[j].m);
+        psSHP->adBoundsMin[2] = MS_MIN(psSHP->adBoundsMin[2], shape->line[i].point[j].z);
+        psSHP->adBoundsMin[3] = MS_MIN(psSHP->adBoundsMin[3], shape->line[i].point[j].m);
 #endif
-      psSHP->adBoundsMax[0] = MS_MAX(psSHP->adBoundsMax[0], shape->line[i].point[j].x);
-      psSHP->adBoundsMax[1] = MS_MAX(psSHP->adBoundsMax[1], shape->line[i].point[j].y);
+        psSHP->adBoundsMax[0] = MS_MAX(psSHP->adBoundsMax[0], shape->line[i].point[j].x);
+        psSHP->adBoundsMax[1] = MS_MAX(psSHP->adBoundsMax[1], shape->line[i].point[j].y);
 #ifdef USE_POINT_Z_M
-      psSHP->adBoundsMax[2] = MS_MAX(psSHP->adBoundsMax[2], shape->line[i].point[j].z);
-      psSHP->adBoundsMax[3] = MS_MAX(psSHP->adBoundsMax[3], shape->line[i].point[j].m);
+        psSHP->adBoundsMax[2] = MS_MAX(psSHP->adBoundsMax[2], shape->line[i].point[j].z);
+        psSHP->adBoundsMax[3] = MS_MAX(psSHP->adBoundsMax[3], shape->line[i].point[j].m);
 #endif
+      }
     }
-  }
 
+  } else {
+    psSHP->nRecords --;
+    /* there was an error writing the record */
+  }
+  free( pabyRec );
   return( psSHP->nRecords - 1 );
 }
 
@@ -1055,8 +1085,15 @@ int msSHPReadPoint( SHPHandle psSHP, int hEntity, pointObj *point )
   /* -------------------------------------------------------------------- */
   /*      Read the record.                                                */
   /* -------------------------------------------------------------------- */
-  fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity), 0 );
-  fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP );
+  if( 0 != fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity), 0 )) {
+    msSetError(MS_IOERR, "failed to seek offset", "msSHPReadPoint()");
+    return(MS_FAILURE);
+  }
+  if( 1 != fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP )) {
+    msSetError(MS_IOERR, "failed to fread record", "msSHPReadPoint()");
+    return(MS_FAILURE);
+  }
+
 
   memcpy( &(point->x), psSHP->pabyRec + 12, 8 );
   memcpy( &(point->y), psSHP->pabyRec + 20, 8 );
@@ -1088,9 +1125,18 @@ int msSHXLoadPage( SHPHandle psSHP, int shxBufferPage )
   if( shxBufferPage < 0  )
     return(MS_FAILURE);
 
-  /* The SHX file starts with 100 bytes of header, skip that. */
-  fseek( psSHP->fpSHX, 100 + shxBufferPage * SHX_BUFFER_PAGE * 8, 0 );
-  fread( buffer, 8, SHX_BUFFER_PAGE, psSHP->fpSHX );
+  if( 0 != fseek( psSHP->fpSHX, 100 + shxBufferPage * SHX_BUFFER_PAGE * 8, 0 )) {
+    /*
+     * msSetError(MS_IOERR, "failed to seek offset", "msSHXLoadPage()");
+     * return(MS_FAILURE);
+    */
+  }
+  if( SHX_BUFFER_PAGE != fread( buffer, 8, SHX_BUFFER_PAGE, psSHP->fpSHX )) {
+    /*
+     * msSetError(MS_IOERR, "failed to fread SHX record", "msSHXLoadPage()");
+     * return(MS_FAILURE);
+     */
+  }
 
   /* Copy the buffer contents out into the working arrays. */
   for( i = 0; i < SHX_BUFFER_PAGE; i++ ) {
@@ -1132,7 +1178,11 @@ int msSHXLoadAll( SHPHandle psSHP )
   uchar *pabyBuf;
 
   pabyBuf = (uchar *) msSmallMalloc(8 * psSHP->nRecords );
-  fread( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX );
+  if(psSHP->nRecords != fread( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX )) {
+    msSetError(MS_IOERR, "failed to read shx records", "msSHXLoadAll()");
+    free(pabyBuf);
+    return MS_FAILURE;
+  }
   for( i = 0; i < psSHP->nRecords; i++ ) {
     ms_int32 nOffset, nLength;
 
@@ -1221,8 +1271,16 @@ void msSHPReadShape( SHPHandle psSHP, int hEntity, shapeObj *shape )
   /* -------------------------------------------------------------------- */
   /*      Read the record.                                                */
   /* -------------------------------------------------------------------- */
-  fseek( psSHP->fpSHP, msSHXReadOffset(psSHP, hEntity), 0 );
-  fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP );
+  if( 0 != fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity), 0 )) {
+    msSetError(MS_IOERR, "failed to seek offset", "msSHPReadShape()");
+    shape->type = MS_SHAPE_NULL;
+    return;
+  }
+  if( 1 != fread( psSHP->pabyRec, nEntitySize, 1, psSHP->fpSHP )) {
+    msSetError(MS_IOERR, "failed to fread record", "msSHPReadPoint()");
+    shape->type = MS_SHAPE_NULL;
+    return;
+  }
 
   /* -------------------------------------------------------------------- */
   /*  Extract vertices for a Polygon or Arc.            */
@@ -1590,8 +1648,14 @@ int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds)
     }
 
     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 );
+      if( 0 != fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity) + 12, 0 )) {
+        msSetError(MS_IOERR, "failed to seek offset", "msSHPReadBounds()");
+        return(MS_FAILURE);
+      }
+      if( 1 != fread( padBounds, sizeof(double)*4, 1, psSHP->fpSHP )) {
+        msSetError(MS_IOERR, "failed to fread record", "msSHPReadBounds()");
+        return(MS_FAILURE);
+      }
 
       if( bBigEndian ) {
         SwapWord( 8, &(padBounds->minx) );
@@ -1610,8 +1674,14 @@ int msSHPReadBounds( SHPHandle psSHP, int hEntity, rectObj *padBounds)
       /*      minimum and maximum bound.                                      */
       /* -------------------------------------------------------------------- */
 
-      fseek( psSHP->fpSHP, msSHXReadOffset(psSHP, hEntity) + 12, 0 );
-      fread( padBounds, sizeof(double)*2, 1, psSHP->fpSHP );
+      if( 0 != fseek( psSHP->fpSHP, msSHXReadOffset( psSHP, hEntity) + 12, 0 )) {
+        msSetError(MS_IOERR, "failed to seek offset", "msSHPReadBounds()");
+        return(MS_FAILURE);
+      }
+      if( 1 != fread( padBounds, sizeof(double)*2, 1, psSHP->fpSHP )) {
+        msSetError(MS_IOERR, "failed to fread record", "msSHPReadBounds()");
+        return(MS_FAILURE);
+      }
 
       if( bBigEndian ) {
         SwapWord( 8, &(padBounds->minx) );
@@ -2483,7 +2553,7 @@ void msSHPLayerFreeItemInfo(layerObj *layer)
 
 int msSHPLayerInitItemInfo(layerObj *layer)
 {
-  shapefileObj *shpfile = shpfile = layer->layerinfo;
+  shapefileObj *shpfile = layer->layerinfo;
   if( ! shpfile) {
     msSetError(MS_SHPERR, "Shapefile layer has not been opened.", "msSHPLayerInitItemInfo()");
     return MS_FAILURE;
@@ -2506,13 +2576,13 @@ int msSHPLayerOpen(layerObj *layer)
 
   if(layer->layerinfo) return MS_SUCCESS; /* layer already open */
 
+  if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
+    return MS_FAILURE;
+
   /* 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;
-
 
   layer->layerinfo = shpfile;
 
@@ -2562,12 +2632,12 @@ int msSHPLayerOpen(layerObj *layer)
 
     if( bOK != MS_TRUE )
     {
-        if( layer->debug || (layer->map && layer->map->debug) ) {
+        if( layer->debug || layer->map->debug ) {
             msDebug( "Unable to get SRS from shapefile '%s' for layer '%s'.\n", szPath, layer->name );
         }
     }
 #else /* !(defined(USE_GDAL) || defined(USE_OGR)) */
-    if( layer->debug || (layer->map && layer->map->debug) ) {
+    if( layer->debug layer->map->debug ) {
         msDebug( "Unable to get SRS from shapefile '%s' for layer '%s'. GDAL or OGR support needed\n", szPath, layer->name );
     }
 #endif /* defined(USE_GDAL) || defined(USE_OGR) */
diff --git a/mapsmoothing.c b/mapsmoothing.c
index 2ebf48c..12e32c2 100644
--- a/mapsmoothing.c
+++ b/mapsmoothing.c
@@ -227,7 +227,10 @@ shapeObj* msSmoothShapeSIA(shapeObj *shape, int ss, int si, char *preprocessing)
       for (j=0; j < newShape->numlines; ++j)
         free(newShape->line[j].point);
       newShape->numlines = 0;
-      if (newShape->line) free(newShape->line);
+      if (newShape->line) {
+        free(newShape->line);
+        newShape->line = NULL;
+      }
 
       shape = &initialShape;
     }
diff --git a/mapstring.c b/mapstring.c
index d1be3e9..16271e4 100644
--- a/mapstring.c
+++ b/mapstring.c
@@ -789,11 +789,9 @@ 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);
 
   j = 0;
   last_ch='\0';
@@ -807,7 +805,6 @@ char **msStringSplit(const char *string, char ch, int *num_tokens)
 
       k++;
       token[k] = (char *)msSmallMalloc(sizeof(char)*(length+1));
-      if(!token[k]) return(NULL);
 
       j = 0;
     } else {
@@ -859,7 +856,7 @@ char ** msStringSplitComplex( const char * pszString,
   int         bStripLeadSpaces = (nFlags & MS_STRIPLEADSPACES);
   int         bStripEndSpaces = (nFlags & MS_STRIPENDSPACES);
 
-  pszToken = (char *) msSmallMalloc(sizeof(char*)*10);;
+  pszToken = (char *) msSmallMalloc(sizeof(char)*10);;
   nTokenMax = 10;
 
   while( pszString != NULL && *pszString != '\0' ) {
@@ -925,7 +922,7 @@ char ** msStringSplitComplex( const char * pszString,
        */
       if( nTokenLen >= nTokenMax-3 ) {
         nTokenMax = nTokenMax * 2 + 10;
-        pszToken = (char *) msSmallRealloc(pszToken, sizeof(char*)*nTokenMax);
+        pszToken = (char *) msSmallRealloc(pszToken, sizeof(char)*nTokenMax);
       }
 
       pszToken[nTokenLen] = *pszString;
@@ -987,7 +984,7 @@ char **msStringTokenize( const char *pszLine, const char *pszDelim,
 {
   char **papszResult = NULL;
   int n = 1, iChar, nLength = strlen(pszLine), iTokenChar = 0, bInQuotes = MS_FALSE;
-  char *pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
+  char *pszToken = (char *) msSmallMalloc(sizeof(char)*(nLength+1));
   int nDelimLen = strlen(pszDelim);
 
   /* Compute the number of tokens */
@@ -1017,7 +1014,7 @@ char **msStringTokenize( const char *pszLine, const char *pszDelim,
     } else if( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 ) {
       pszToken[iTokenChar++] = '\0';
       papszResult[n] = pszToken;
-      pszToken = (char *) msSmallMalloc(sizeof(char*)*(nLength+1));
+      pszToken = (char *) msSmallMalloc(sizeof(char)*(nLength+1));
       iChar += nDelimLen - 1;
       iTokenChar = 0;
       n++;
@@ -1194,8 +1191,8 @@ void msDecodeHTMLEntities(const char *string)
     pszBuffer = (char*)string;
 
   bufferSize = strlen(pszBuffer);
-  pszReplace = (char*) msSmallMalloc(bufferSize);
-  pszEnd = (char*) msSmallMalloc(bufferSize);
+  pszReplace = (char*) msSmallMalloc(bufferSize+1);
+  pszEnd = (char*) msSmallMalloc(bufferSize+1);
 
   while((pszAmp = strchr(pszBuffer, '&')) != NULL) {
     /* Get the &...; */
@@ -1606,6 +1603,7 @@ char *msGetEncodedString(const char *string, const char *encoding)
   const char *inp;
   char *outp, *out = NULL;
   size_t len, bufsize, bufleft, iconv_status;
+  assert(encoding);
 
 #ifdef USE_FRIBIDI
   msAcquireLock(TLOCK_FRIBIDI);
@@ -1618,7 +1616,7 @@ char *msGetEncodedString(const char *string, const char *encoding)
 #endif
   len = strlen(string);
 
-  if (len == 0 || (encoding && strcasecmp(encoding, "UTF-8")==0))
+  if (len == 0 || strcasecmp(encoding, "UTF-8")==0)
     return msStrdup(string);    /* Nothing to do: string already in UTF-8 */
 
   cd = iconv_open("UTF-8", encoding);
diff --git a/mapsymbol.c b/mapsymbol.c
index 2fd876a..33417ca 100644
--- a/mapsymbol.c
+++ b/mapsymbol.c
@@ -981,7 +981,7 @@ symbolObj *msRotateVectorSymbol(symbolObj *symbol, double angle)
   /* 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) ) {
+    if ((symbol->points[i].x == -99.0) && (symbol->points[i].y == -99.0) ) {
       newSymbol->points[i].x = -99.0;
       newSymbol->points[i].y = -99.0;
       continue;
@@ -997,7 +997,7 @@ symbolObj *msRotateVectorSymbol(symbolObj *symbol, double angle)
     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))
+      if ((newSymbol->points[i].x == -99.0) && (newSymbol->points[i].y == -99.0))
         continue;
       newSymbol->points[i].x = newSymbol->points[i].x + xcor;
       newSymbol->points[i].y = newSymbol->points[i].y + ycor;
diff --git a/maptemplate.c b/maptemplate.c
index 4b59053..2fbc27e 100644
--- a/maptemplate.c
+++ b/maptemplate.c
@@ -907,6 +907,8 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
       status = msJoinConnect(layer, &(layer->joins[j]));
       if(status != MS_SUCCESS) {
         msFreeHashTable(tagArgs);
+        msFree(postTag);
+        msFree(tag);
         return status;
       }
     }
@@ -925,6 +927,8 @@ static int processFeatureTag(mapservObj *mapserv, char **line, layerObj *layer)
     status = msLayerGetShape(layer, &(mapserv->resultshape), &(layer->resultcache->results[i]));
     if(status != MS_SUCCESS) {
       msFreeHashTable(tagArgs);
+      msFree(postTag);
+      msFree(tag);
       return status;
     }
 
@@ -2086,14 +2090,22 @@ static int processShpxyTag(layerObj *layer, char **line, shapeObj *shape)
       shapeObj *bufferShape=NULL;
 
       bufferShape = msGEOSBuffer(shape, buffer);
-      if(!bufferShape) return(MS_FAILURE); /* buffer failed */
+      if(!bufferShape) {
+        free(pointFormat1);
+        free(pointFormat2);
+        return(MS_FAILURE); /* buffer failed */
+      }
       msCopyShape(bufferShape, &tShape);
       msFreeShape(bufferShape);
     }
 #endif
     else {
       status = msCopyShape(shape, &tShape);
-      if(status != 0) return(MS_FAILURE); /* copy failed */
+      if(status != 0) {
+        free(pointFormat1);
+        free(pointFormat2);
+        return(MS_FAILURE); /* copy failed */
+      }
     }
 
     /* no big deal to convert from file to image coordinates, but what are the image parameters */
@@ -3036,7 +3048,10 @@ char *generateLegendTemplate(mapservObj *mapserv)
   /* 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;
+    if(pszResult)
+      free(pszResult);
+    pszResult=NULL;
+    goto error;
   }
 
   fseek(stream, 0, SEEK_END);
@@ -3045,12 +3060,6 @@ char *generateLegendTemplate(mapservObj *mapserv)
 
   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
    */
@@ -3065,7 +3074,12 @@ char *generateLegendTemplate(mapservObj *mapserv)
   */
   file[length] = '\0';
 
-  if(msValidateContexts(mapserv->map) != MS_SUCCESS) return NULL; /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
+  if(msValidateContexts(mapserv->map) != MS_SUCCESS) { /* make sure there are no recursive REQUIRES or LABELREQUIRES expressions */
+    if(pszResult)
+      free(pszResult);
+    pszResult=NULL;
+    goto error;
+  }
 
   /*
    * Seperate header/footer, groups, layers and class
@@ -3080,16 +3094,28 @@ char *generateLegendTemplate(mapservObj *mapserv)
    * Retrieve arguments of all three parts
    */
   if(legGroupHtml)
-    if(getTagArgs("leg_group_html", file, &groupArgs) != MS_SUCCESS)
-      return NULL;
+    if(getTagArgs("leg_group_html", file, &groupArgs) != MS_SUCCESS) {
+      if(pszResult)
+        free(pszResult);
+      pszResult=NULL;
+      goto error;
+    }
 
   if(legLayerHtml)
-    if(getTagArgs("leg_layer_html", file, &layerArgs) != MS_SUCCESS)
-      return NULL;
+    if(getTagArgs("leg_layer_html", file, &layerArgs) != MS_SUCCESS) {
+      if(pszResult)
+        free(pszResult);
+      pszResult=NULL;
+      goto error;
+    }
 
   if(legClassHtml)
-    if(getTagArgs("leg_class_html", file, &classArgs) != MS_SUCCESS)
-      return NULL;
+    if(getTagArgs("leg_class_html", file, &classArgs) != MS_SUCCESS) {
+      if(pszResult)
+        free(pszResult);
+      pszResult=NULL;
+      goto error;
+    }
 
 
   mapserv->map->cellsize = msAdjustExtent(&(mapserv->map->extent),
@@ -3097,8 +3123,12 @@ char *generateLegendTemplate(mapservObj *mapserv)
                                           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);
+                      mapserv->map->resolution, &mapserv->map->scaledenom) != MS_SUCCESS) {
+    if(pszResult)
+      free(pszResult);
+    pszResult=NULL;
+    goto error;
+  }
 
   /* start with the header if present */
   if(legHeaderHtml) pszResult = msStringConcatenate(pszResult, legHeaderHtml);
@@ -3111,8 +3141,12 @@ char *generateLegendTemplate(mapservObj *mapserv)
    */
   pszOrderMetadata = msLookupHashTable(layerArgs, "order_metadata");
 
-  if(sortLayerByMetadata(mapserv->map, pszOrderMetadata) != MS_SUCCESS)
+  if(sortLayerByMetadata(mapserv->map, pszOrderMetadata) != MS_SUCCESS) {
+    if(pszResult)
+      free(pszResult);
+    pszResult=NULL;
     goto error;
+  }
 
   /* -------------------------------------------------------------------- */
   /*      if the order tag is set to ascending or descending, the         */
@@ -3121,8 +3155,12 @@ char *generateLegendTemplate(mapservObj *mapserv)
   pszOrder = msLookupHashTable(layerArgs, "order");
   if(pszOrder && ((strcasecmp(pszOrder, "ASCENDING") == 0) ||
                   (strcasecmp(pszOrder, "DESCENDING") == 0))) {
-    if(sortLayerByOrder(mapserv->map, pszOrder) != MS_SUCCESS)
+    if(sortLayerByOrder(mapserv->map, pszOrder) != MS_SUCCESS) {
+      if(pszResult)
+        free(pszResult);
+      pszResult=NULL;
       goto error;
+    }
   }
 
   if(legGroupHtml) {
@@ -3429,7 +3467,8 @@ error:
   msFree(legClassHtml);
   msFree(pszPrefix);
 
-  fclose(stream);
+  if(stream)
+    fclose(stream);
 
   /* -------------------------------------------------------------------- */
   /*      Reset the layerdrawing order.                                   */
@@ -3460,13 +3499,16 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
     /* want to do this if there are joined records. */
     if(records == MS_FALSE) {
       if(join->header != NULL) {
+        if(stream) fclose(stream);
         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);
+          msFree(outbuf);
           return(NULL);
         }
 
         if(isValidTemplate(stream, join->header) != MS_TRUE) {
           fclose(stream);
+          msFree(outbuf);
           return NULL;
         }
 
@@ -3474,15 +3516,18 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
         while(fgets(line, MS_BUFFER_LENGTH, stream) != NULL) outbuf = msStringConcatenate(outbuf, line);
 
         fclose(stream);
+        stream = NULL;
       }
 
       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);
+        msFree(outbuf);
         return(NULL);
       }
 
       if(isValidTemplate(stream, join->template) != MS_TRUE) {
         fclose(stream);
+        msFree(outbuf);
         return NULL;
       }
 
@@ -3492,7 +3537,11 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
     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 */
-        if(!tmpline) return NULL;
+        if(!tmpline) {
+           msFree(outbuf);
+           fclose(stream);
+           return NULL;
+        }
         outbuf = msStringConcatenate(outbuf, tmpline);
         free(tmpline);
       } else /* no subs, just echo */
@@ -3504,12 +3553,15 @@ char *processOneToManyJoin(mapservObj* mapserv, joinObj *join)
   } /* next record */
 
   if(records==MS_TRUE && join->footer) {
+    if(stream) fclose(stream);
     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);
+      msFree(outbuf);
       return(NULL);
     }
 
     if(isValidTemplate(stream, join->footer) != MS_TRUE) {
+      msFree(outbuf);
       fclose(stream);
       return NULL;
     }
@@ -3887,7 +3939,10 @@ static char *processLine(mapservObj *mapserv, char *instr, FILE *stream, int mod
   }
 
   if(mode != QUERY) {
-    if(processResultSetTag(mapserv, &outstr, stream) != MS_SUCCESS) return(NULL);
+    if(processResultSetTag(mapserv, &outstr, stream) != MS_SUCCESS) {
+      msFree(outstr);
+      return(NULL);
+    }
   }
 
   if(mode == QUERY) { /* return shape and/or values  */
diff --git a/maptile.c b/maptile.c
index 052cbb1..a53c5d7 100644
--- a/maptile.c
+++ b/maptile.c
@@ -61,6 +61,7 @@ static int msTileGetGMapCoords(const char *coordstring, int *x, int *y, int *zoo
   if( coordstring ) {
     coords = msStringSplit(coordstring, ' ', &(num_coords));
     if( num_coords != 3 ) {
+      msFreeCharArray(coords, num_coords);
       msSetError(MS_WEBERR, "Invalid number of tile coordinates (should be three).", "msTileSetup()");
       return MS_FAILURE;
     }
@@ -75,7 +76,8 @@ static int msTileGetGMapCoords(const char *coordstring, int *x, int *y, int *zoo
     *y = strtol(coords[1], NULL, 10);
   if( zoom )
     *zoom = strtol(coords[2], NULL, 10);
-
+  
+  msFreeCharArray(coords, 3);
   return MS_SUCCESS;
 }
 
diff --git a/maptime.c b/maptime.c
index 29e2b1a..a703bdb 100644
--- a/maptime.c
+++ b/maptime.c
@@ -242,9 +242,8 @@ void msSetLimitedPattersToUse(char *patternstring)
           }
         }
       }
-
-      msFreeCharArray(patterns, ntmp);
     }
+    msFreeCharArray(patterns, ntmp);
   }
 
   if (numpatterns > 0) {
@@ -383,8 +382,10 @@ int _msValidateTime(char *timestring,  const char *timeextent)
 
   numextents = 0;
   atimeextents = msStringSplit (timeextent, ',', &numextents);
-  if (atimeextents == NULL || numextents <= 0)
+  if (numextents <= 0) {
+    msFreeCharArray(atimeextents, numextents);
     return MS_FALSE;
+  }
 
   /*the time timestring should at be valid in one of the extents
     defined */
@@ -474,9 +475,9 @@ int msValidateTimeValue(char *timestring, const char *timeextent)
         msFreeCharArray(atimes, numtimes);
         return MS_TRUE;
       }
-
+    } else {
+      msFreeCharArray(atimes,numtimes);
     }
-
   }
   return MS_FALSE;
 }
diff --git a/maptree.c b/maptree.c
index 805a554..e9b5639 100644
--- a/maptree.c
+++ b/maptree.c
@@ -753,6 +753,7 @@ int msWriteTree(treeObj *tree, char *filename, int B_order)
   i = fwrite( pabyBuf, 8, 1, disktree->fp );
   if( !i ) {
     fprintf (stderr, "unable to write to index file ... exiting \n");
+    msSHPDiskTreeClose( disktree );
     return (MS_FALSE);
   }
 
diff --git a/maputil.c b/maputil.c
index ef0d309..34cba65 100644
--- a/maputil.c
+++ b/maputil.c
@@ -875,8 +875,11 @@ int msSaveImage(mapObj *map, imageObj *img, char *filename)
 
         if(renderer->supports_pixel_buffer) {
           rasterBufferObj data;
-          if(renderer->getRasterBufferHandle(img,&data) != MS_SUCCESS)
+          if(renderer->getRasterBufferHandle(img,&data) != MS_SUCCESS) {
+            if( stream != stdout )
+              fclose(stream);
             return MS_FAILURE;
+          }
 
           nReturnVal = msSaveRasterBuffer(map,&data,stream,img->format );
         } else {
@@ -1331,6 +1334,7 @@ char **msGetAllGroupNames(mapObj *map, int *numTok)
   int         nCount = 0;
   int         i = 0, j = 0;
 
+  assert(map);
   *numTok = 0;
 
   if (!map->layerorder) {
@@ -1343,7 +1347,7 @@ char **msGetAllGroupNames(mapObj *map, int *numTok)
       map->layerorder[i] = i;
   }
 
-  if (map != NULL && map->numlayers > 0) {
+  if (map->numlayers > 0) {
     nCount = map->numlayers;
     papszGroups = (char **)msSmallMalloc(sizeof(char *)*nCount);
 
@@ -2096,19 +2100,19 @@ void msAlphaBlendPM( unsigned char red_src, unsigned char green_src,
   /*      Cases with actual blending.                                     */
   /* -------------------------------------------------------------------- */
   if(!alpha_dst || *alpha_dst == 255) {
-    int weight_dst = 256 - alpha_src;
+    int weight_dst = 255 - 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;
+    *red_dst   = (alpha_src * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (alpha_src * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (alpha_src * blue_src  + *blue_dst  * weight_dst) >> 8;
   } else {
-    int   weight_dst = (256 - alpha_src);
+    int   weight_dst = (255 - 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;
+    *red_dst   = (alpha_src * red_src   + *red_dst   * weight_dst) >> 8;
+    *green_dst = (alpha_src * green_src + *green_dst * weight_dst) >> 8;
+    *blue_dst  = (alpha_src * blue_src  + *blue_dst  * weight_dst) >> 8;
 
-    *alpha_dst = (256 * alpha_src + *alpha_dst * weight_dst) >> 8;
+    *alpha_dst = (255 * alpha_src + *alpha_dst * weight_dst) >> 8;
   }
 }
 
@@ -2121,16 +2125,10 @@ int msCheckParentPointer(void* p, char *objname)
   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);
-      }
+      msSetError(MS_NULLPARENTERR, "The %s parent object is null", "msCheckParentPointer()", msg);
     } else {
-      msg="A required parent object is null";
+      msSetError(MS_NULLPARENTERR, "The parent object is null", "msCheckParentPointer()");
     }
-    msSetError(MS_NULLPARENTERR, "%s", "", msg);
     return MS_FAILURE;
   }
   return MS_SUCCESS;
diff --git a/mapuvraster.c b/mapuvraster.c
index dc7e8c2..6cbfd33 100644
--- a/mapuvraster.c
+++ b/mapuvraster.c
@@ -341,14 +341,6 @@ int msUVRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
   char   **alteredProcessing = NULL, *saved_layer_mask;
   char **savedProcessing = NULL;
 
-  /*
-  ** Allocate mapObj structure
-  */
-  map_tmp = (mapObj *)msSmallCalloc(sizeof(mapObj),1);
-  if(initMap(map_tmp) == -1) { /* initialize this map */
-    msFree(map_tmp);
-    return(MS_FAILURE);
-  }
   
   if (layer->debug)
     msDebug("Entering msUVRASTERLayerWhichShapes().\n");
@@ -368,6 +360,15 @@ int msUVRASTERLayerWhichShapes(layerObj *layer, rectObj rect, int isQuery)
                 "msUVRASTERLayerWhichShapes()" );
     return MS_FAILURE;
   }
+  
+  /*
+  ** Allocate mapObj structure
+  */
+  map_tmp = (mapObj *)msSmallCalloc(sizeof(mapObj),1);
+  if(initMap(map_tmp) == -1) { /* initialize this map */
+    msFree(map_tmp);
+    return(MS_FAILURE);
+  }
 
   /* -------------------------------------------------------------------- */
   /*      Determine desired spacing.  Default to 32 if not otherwise set  */
diff --git a/mapwcs.c b/mapwcs.c
index 2edeab6..2280b37 100644
--- a/mapwcs.c
+++ b/mapwcs.c
@@ -1641,8 +1641,10 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
     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()" );
+      free(map_original_srs);
       return msWCSException(map, NULL, NULL, params->version);
     }
+    free(map_original_srs);
   }
 
   /* we need the coverage metadata, since things like numbands may not be available otherwise */
@@ -1927,17 +1929,6 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
   msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
   free( bandlist );
 
-  /* create the image object  */
-  if(!map->outputformat) {
-    msSetError(MS_WCSERR, "The map outputformat is missing!", "msWCSGetCoverage()");
-    return msWCSException(map, NULL, NULL, params->version );
-  } else if( MS_RENDERER_RAWDATA(map->outputformat) || MS_RENDERER_PLUGIN(map->outputformat) ) {
-    image = msImageCreate(map->width, map->height, map->outputformat, map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, NULL);
-  } else {
-    msSetError(MS_WCSERR, "Map outputformat not supported for WCS!", "msWCSGetCoverage()");
-    return msWCSException(map, NULL, NULL, params->version );
-  }
-  
   if(lp->mask) {
     int maskLayerIdx = msGetLayerIndex(map,lp->mask);
     layerObj *maskLayer;
@@ -1945,7 +1936,7 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
     if(maskLayerIdx == -1) {
       msSetError(MS_MISCERR, "Layer (%s) references unknown mask layer (%s)", "msDrawLayer()",
                  lp->name,lp->mask);
-      return (MS_FAILURE);
+      return msWCSException(map, NULL, NULL, params->version );
     }
     maskLayer = GET_LAYER(map, maskLayerIdx);
     if(!maskLayer->maskimage) {
@@ -1955,11 +1946,12 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
       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);
+      maskLayer->maskimage= msImageCreate(map->width, map->height, altFormat,
+                                          map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, NULL);
       if (!maskLayer->maskimage) {
         msSetError(MS_MISCERR, "Unable to initialize mask image.", "msDrawLayer()");
-        return (MS_FAILURE);
+        msFree(origImageType);
+        return msWCSException(map, NULL, NULL, params->version );
       }
 
       /*
@@ -1977,7 +1969,10 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
       maskLayer->status = origstatus;
       maskLayer->labelcache = origlabelcache;
       if(retcode != MS_SUCCESS) {
-        return MS_FAILURE;
+        /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
+        msFree(map->imagetype);
+        map->imagetype = origImageType;
+        return msWCSException(map, NULL, NULL, params->version );
       }
       /*
        * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
@@ -2000,6 +1995,17 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
       
     }
   }
+  
+  /* create the image object  */
+  if(!map->outputformat) {
+    msSetError(MS_WCSERR, "The map outputformat is missing!", "msWCSGetCoverage()");
+    return msWCSException(map, NULL, NULL, params->version );
+  } else if( MS_RENDERER_RAWDATA(map->outputformat) || MS_RENDERER_PLUGIN(map->outputformat) ) {
+    image = msImageCreate(map->width, map->height, map->outputformat, map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, NULL);
+  } else {
+    msSetError(MS_WCSERR, "Map outputformat not supported for WCS!", "msWCSGetCoverage()");
+    return msWCSException(map, NULL, NULL, params->version );
+  }
 
   if( image == NULL )
     return msWCSException(map, NULL, NULL, params->version );
@@ -2012,6 +2018,7 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage()", par
     status = msDrawRasterLayerLow( map, lp, image, &rb );
   }
   if( status != MS_SUCCESS ) {
+    msFreeImage(image);
     return msWCSException(map, NULL, NULL, params->version );
   }
 
@@ -2122,7 +2129,7 @@ int msWCSDispatch(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_reques
       wcs20ParamsObjPtr params_tmp = msWCSCreateParamsObj20();
       status = msWCSParseRequest20(map, request, ows_request, params_tmp);
       if (status == MS_FAILURE) {
-        msWCSFreeParamsObj20(params);
+        msWCSFreeParamsObj20(params_tmp);
         return msWCSException(map, "InvalidParameterValue",
                               "request", "2.0.1");
       }
diff --git a/mapwcs11.c b/mapwcs11.c
index e49af52..2d2130d 100644
--- a/mapwcs11.c
+++ b/mapwcs11.c
@@ -57,8 +57,8 @@
 **
 */
 
-int msWCSException11(mapObj *map, const char *locator,
-                     const char *exceptionCode, const char *version)
+int msWCSException11(mapObj *map, const char *exceptionCode,
+                     const char *locator, const char *version)
 {
   int size = 0;
   char *errorString     = NULL;
@@ -399,11 +399,11 @@ int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
     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);
+      return msWCSException11(map, "CurrentUpdateSequence", "updatesequence", 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);
+      return msWCSException11(map, "InvalidUpdateSequence", "updatesequence", params->version);
     }
   }
 
@@ -490,7 +490,7 @@ int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
   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);
+    return msWCSException11(map, "NoApplicableCode", "mapserv", params->version);
   }
   free( script_url );
 
@@ -587,7 +587,10 @@ int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
 
         status = msWCSGetCapabilities11_CoverageSummary(
                    map, params, req, psDoc, psMainNode, layer );
-        if(status != MS_SUCCESS) return MS_FAILURE;
+        if(status != MS_SUCCESS) {
+          msFree(identifier_list);
+          return MS_FAILURE;
+        }
       }
     }
   }
@@ -928,7 +931,7 @@ int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params, owsRequestObj *ow
         msSetError( MS_WCSERR,
                     "COVERAGE %s cannot be opened / does not exist",
                     "msWCSDescribeCoverage()", params->coverages[j]);
-        return msWCSException11(map, "coverage", "CoverageNotDefined", params->version);
+        return msWCSException11(map, "CoverageNotDefined", "coverage", params->version);
       }
     }
   }
@@ -1077,8 +1080,11 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
   /* -------------------------------------------------------------------- */
   value = rangesubset + strlen(field_id);
 
-  if( strcasecmp(rangesubset,field_id) == 0 )
+  if( strcasecmp(rangesubset,field_id) == 0 ) {
+    free(rangesubset);
+    free(field_id);
     return MS_SUCCESS; /* we only got field ... default options */
+  }
 
   if( strlen(rangesubset) <= strlen(field_id)+1
       || strncasecmp(rangesubset,field_id,strlen(field_id)) != 0
@@ -1087,7 +1093,9 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
                 "RangeSubset field name malformed, expected '%s', got RangeSubset=%s",
                 "msWCSGetCoverageBands11()",
                 field_id, rangesubset );
-    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+    free(rangesubset);
+    free(field_id);
+    return msWCSException11(map, "NoApplicableCode", "mapserv", params->version);
   }
 
   free( field_id );
@@ -1112,8 +1120,10 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
   /* -------------------------------------------------------------------- */
   /*      Parse out the axis name, and verify.                            */
   /* -------------------------------------------------------------------- */
-  if( *value != '[' )
+  if( *value != '[' ) {
+    free(rangesubset);
     return MS_SUCCESS;
+  }
 
   value++;
 
@@ -1124,7 +1134,8 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
                 "RangeSubset axis name malformed, expected '%s', got RangeSubset=%s",
                 "msWCSGetCoverageBands11()",
                 axis_id, rangesubset );
-    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+    free(rangesubset);
+    return msWCSException11(map, "NoApplicableCode", "mapserv", params->version);
   }
 
   /* -------------------------------------------------------------------- */
@@ -1141,7 +1152,7 @@ int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
       break;
     }
   }
-
+  free(rangesubset);
   return MS_SUCCESS;
 }
 #endif
@@ -1183,7 +1194,7 @@ int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
                   "Failed to find %s driver.",
                   "msWCSReturnCoverage11()",
                   image->format->driver+5 );
-      return msWCSException11(map, "mapserv", "NoApplicableCode",
+      return msWCSException11(map, "NoApplicableCode", "mapserv",
                               params->version);
     }
 
@@ -1208,7 +1219,7 @@ int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
         msFree(filename);
         msSetError(MS_MISCERR, "msSaveImage() failed",
                    "msWCSReturnCoverage11()");
-        return msWCSException11(map, "mapserv", "NoApplicableCode",
+        return msWCSException11(map, "NoApplicableCode", "mapserv",
                                 params->version);
       }
     }
@@ -1276,7 +1287,7 @@ int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
     status = msSaveImage(map, image, NULL);
     if( status != MS_SUCCESS ) {
       msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSReturnCoverage11()");
-      return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
+      return msWCSException11(map, "NoApplicableCode", "mapserv", params->version);
     }
 
     msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
@@ -1395,7 +1406,7 @@ int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params,
   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);
+  return msWCSException11(map, "NoApplicableCode", "mapserv", params->version);
 }
 
 /* ==================================================================== */
@@ -1407,13 +1418,13 @@ int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
               "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, "NoApplicableCode", "mapserv", params->version);
 }
 
-int msWCSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version)
+int msWCSException11(mapObj *map, const char *exceptionCode, const char *locator, const char *version)
 {
   /* fallback to reporting using 1.0 style exceptions. */
-  return msWCSException( map, locator, exceptionCode, "1.0.0" );
+  return msWCSException( map, exceptionCode, locator, "1.0.0" );
 }
 
 #endif /* defined(USE_WCS_SVR) && !defined(USE_LIBXML2) */
diff --git a/mapwcs20.c b/mapwcs20.c
index 3d2d110..51bd9d7 100644
--- a/mapwcs20.c
+++ b/mapwcs20.c
@@ -1109,7 +1109,7 @@ static int msWCSValidateAndFindAxes20(
   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[2]; 
+  char **validAxisNames[2];
   int iParamAxis, iAcceptedAxis, iName, i;
 
   validAxisNames[0] = validXAxisNames;
@@ -1580,7 +1580,7 @@ static int msWCSWriteDocument20(mapObj* map, xmlDocPtr psDoc)
   xmlChar *buffer = NULL;
   int size = 0;
   msIOContext *context = NULL;
-  const char *contenttype = NULL;
+  char *contenttype = NULL;
 
   const char *encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
 
@@ -1598,6 +1598,7 @@ static int msWCSWriteDocument20(mapObj* map, xmlDocPtr psDoc)
   else
     msIO_setHeader("Content-Type","%s", contenttype);
   msIO_sendHeaders();
+  msFree(contenttype);
 
   context = msIO_getHandler(stdout);
 
@@ -1641,7 +1642,7 @@ static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr para
                   "Failed to find %s driver.",
                   "msWCSWriteFile20()",
                   image->format->driver+5 );
-      return msWCSException(map, "mapserv", "NoApplicableCode",
+      return msWCSException(map, "NoApplicableCode", "mapserv",
                             params->version);
     }
 
@@ -1665,7 +1666,7 @@ static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr para
       if( status != MS_SUCCESS ) {
         msSetError(MS_MISCERR, "msSaveImage() failed",
                    "msWCSWriteFile20()");
-        return msWCSException20(map, "mapserv", "NoApplicableCode",
+        return msWCSException20(map, "NoApplicableCode", "mapserv",
                                 params->version);
       }
     }
@@ -1715,7 +1716,7 @@ static int msWCSWriteFile20(mapObj* map, imageObj* image, wcs20ParamsObjPtr para
     status = msSaveImage(map, image, NULL);
     if( status != MS_SUCCESS ) {
       msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSWriteFile20()");
-      return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
+      return msWCSException(map, "NoApplicableCode", "mapserv", params->version);
     }
     if(multipart)
       msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
@@ -2622,15 +2623,15 @@ int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
       msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)",
                  "msWCSGetCapabilities20()", params->updatesequence, updatesequence);
       xmlFreeDoc(psDoc);
-      return msWCSException(map, "updatesequence",
-                            "CurrentUpdateSequence", params->version);
+      return msWCSException(map, "CurrentUpdateSequence", "updatesequence",
+                            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);
+      return msWCSException(map, "InvalidUpdateSequence", "updatesequence",
+                            params->version);
     }
   }
   if(updatesequence != NULL) {
@@ -2660,7 +2661,7 @@ int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
         || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
       xmlFreeDoc(psDoc);
       msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities20()");
-      return msWCSException(map, "mapserv", "NoApplicableCode", params->version);
+      return msWCSException(map, "NoApplicableCode", "mapserv", params->version);
     }
     free(script_url);
 
@@ -2714,6 +2715,9 @@ int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
   if ( MS_WCS_20_CAPABILITIES_INCLUDE_SECTION(params, "ServiceMetadata") ) {
     psNode = xmlNewChild(psRootNode, psWcsNs, BAD_CAST "ServiceMetadata", NULL);
 
+    /* Apply default formats */
+    msApplyDefaultOutputFormats(map);
+
     /* Add formats list */
     format_list = msWCSGetFormatsList20(map, NULL);
     msLibXml2GenerateList(psNode, psWcsNs, "formatSupported", format_list, ',');
@@ -2746,7 +2750,7 @@ int msWCSGetCapabilities20(mapObj *map, cgiRequestObj *req,
         if(status != MS_SUCCESS) {
           xmlFreeDoc(psDoc);
           xmlCleanupParser();
-          return msWCSException(map, "mapserv", "Internal", params->version);
+          return msWCSException(map, "Internal", "mapserv", params->version);
         }
       }
     }
@@ -2982,7 +2986,7 @@ int msWCSDescribeCoverage20(mapObj *map, wcs20ParamsObjPtr params, owsRequestObj
 static int msWCSGetCoverage20_FinalizeParamsObj(wcs20ParamsObjPtr params, wcs20AxisObjPtr *axes)
 {
   char *crs = NULL;
-  
+
   if (axes[0] != NULL) {
     if(axes[0]->subset != NULL) {
       msDebug("Subset for X-axis found: %s\n", axes[0]->subset->axis);
@@ -3538,7 +3542,10 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", p
     if(maskLayerIdx == -1) {
       msSetError(MS_MISCERR, "Layer (%s) references unknown mask layer (%s)", "msDrawLayer()",
                  layer->name,layer->mask);
-      return (MS_FAILURE);
+      msFreeImage(image);
+      msFree(bandlist);
+      msWCSClearCoverageMetadata20(&cm);
+      return msWCSException(map, NULL, NULL, params->version);
     }
     maskLayer = GET_LAYER(map, maskLayerIdx);
     if(!maskLayer->maskimage) {
@@ -3552,7 +3559,10 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", p
                                           image->imagepath, image->imageurl, map->resolution, map->defresolution, NULL);
       if (!maskLayer->maskimage) {
         msSetError(MS_MISCERR, "Unable to initialize mask image.", "msDrawLayer()");
-        return (MS_FAILURE);
+        msFreeImage(image);
+        msFree(bandlist);
+        msWCSClearCoverageMetadata20(&cm);
+        return msWCSException(map, NULL, NULL, params->version);
       }
 
       /*
@@ -3570,7 +3580,11 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", p
       maskLayer->status = origstatus;
       maskLayer->labelcache = origlabelcache;
       if(retcode != MS_SUCCESS) {
-        return MS_FAILURE;
+        free(origImageType);
+        msFreeImage(image);
+        msFree(bandlist);
+        msWCSClearCoverageMetadata20(&cm);
+        return msWCSException(map, NULL, NULL, params->version);
       }
       /*
        * hack to work around bug #3834: if we have use an alternate renderer, the symbolset may contain
@@ -3590,7 +3604,7 @@ this request. Check wcs/ows_enable_request settings.", "msWCSGetCoverage20()", p
       /* set the imagetype from the original outputformat back (it was removed by msSelectOutputFormat() */
       msFree(map->imagetype);
       map->imagetype = origImageType;
-      
+
     }
   }
 
diff --git a/mapwfs.c b/mapwfs.c
index a1c726a..57b4175 100644
--- a/mapwfs.c
+++ b/mapwfs.c
@@ -262,8 +262,8 @@ int msWFSLocateSRSInList(const char *pszList, const char *srs)
         break;
       }
     }
-    msFreeCharArray(tokens, nTokens);
   }
+  msFreeCharArray(tokens, nTokens);
 
   return bFound;
 }
@@ -403,10 +403,7 @@ static int msWFSGetFeatureApplySRS(mapObj *map, const char *srs, const char *ver
 
     /*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);
+    nTmp = msLoadProjectionString(&(sProjTmp), pszOutputSRS);
 
     if (nTmp == 0)
       msProjectRect(&(map->projection), &(sProjTmp), &map->extent);
@@ -415,10 +412,7 @@ static int msWFSGetFeatureApplySRS(mapObj *map, const char *srs, const char *ver
     msFreeProjection(&map->projection);
     msInitProjection(&map->projection);
 
-    if (nVersion >= OWS_1_1_0)
-      nTmp = msLoadProjectionStringEPSG(&(map->projection), pszOutputSRS);
-    else
-      nTmp = msLoadProjectionString(&(map->projection), pszOutputSRS);
+    nTmp = msLoadProjectionString(&(map->projection), pszOutputSRS);
 
     if (nTmp != 0) {
       msSetError(MS_WFSERR, "msLoadProjectionString() failed", "msWFSGetFeature()");
@@ -659,7 +653,7 @@ int msWFSGetCapabilities(mapObj *map, wfsParamsObj *wfsparams, cgiRequestObj *re
   updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");
 
   if (!updatesequence)
-    updatesequence = msStrdup("0");
+    updatesequence = "0";
 
   if (wfsparams->pszUpdateSequence != NULL) {
     i = msOWSNegotiateUpdateSequence(wfsparams->pszUpdateSequence, updatesequence);
@@ -991,8 +985,7 @@ static void msWFSWriteGroupElementType(FILE *stream, gmlGroupObj *group, gmlItem
   gmlConstantObj *constant=NULL;
 
   /* setup the element tab */
-  element_tab = (char *) malloc(sizeof(char)*strlen(tab)+5);
-  MS_CHECK_ALLOC_NO_RET(element_tab, sizeof(char)*strlen(tab)+5);
+  element_tab = (char *) msSmallMalloc(sizeof(char)*strlen(tab)+5);
   sprintf(element_tab, "%s    ", tab);
 
   if(group->type)
@@ -1023,6 +1016,7 @@ static void msWFSWriteGroupElementType(FILE *stream, gmlGroupObj *group, gmlItem
 
   msIO_fprintf(stream, "%s  </sequence>\n", tab);
   msIO_fprintf(stream, "%s</complexType>\n", tab);
+  free(element_tab);
 
   return;
 }
@@ -1042,7 +1036,7 @@ int msWFSDescribeFeatureType(mapObj *map, wfsParamsObj *paramsObj, owsRequestObj
   const char *user_namespace_uri = "http://mapserver.gis.umn.edu/mapserver";
   char *user_namespace_uri_encoded = NULL;
   const char *collection_name = OWS_WFS_FEATURE_COLLECTION_NAME;
-  char *encoded_name = NULL, *encoded;
+  char *encoded;
 
   int outputformat = OWS_DEFAULT_SCHEMA; /* default output is GML 2.1 compliant schema*/
 
@@ -1242,7 +1236,7 @@ this request. Check wfs/ows_enable_request settings.", "msWFSDescribeFeatureType
           gmlConstantObj *constant=NULL;
 
           const char *layer_namespace_prefix;
-          char *encoded_type=NULL;
+          char *encoded_type=NULL, *encoded_name = NULL;
 
           itemList = msGMLGetItems(lp, "G"); /* GML-related metadata */
           constantList = msGMLGetConstants(lp, "G");
@@ -1277,8 +1271,14 @@ this request. Check wfs/ows_enable_request settings.", "msWFSDescribeFeatureType
                         "           substitutionGroup=\"gml:_Feature\" />\n\n",
                         encoded_name, layer_namespace_prefix, encoded_name);
 
-          if(strcmp(layer_namespace_prefix, user_namespace_prefix) != 0)
+          if(strcmp(layer_namespace_prefix, user_namespace_prefix) != 0) {
+            msFree(encoded_name);
+            msGMLFreeItems(itemList);
+            msGMLFreeConstants(constantList);
+            msGMLFreeGroups(groupList);
+            msGMLFreeGeometries(geometryList);
             continue; /* the rest is defined in an external schema */
+          }
 
           msIO_printf("  <complexType name=\"%sType\">\n", encoded_name);
           msIO_printf("    <complexContent>\n");
@@ -1318,11 +1318,12 @@ this request. Check wfs/ows_enable_request settings.", "msWFSDescribeFeatureType
           msGMLFreeConstants(constantList);
           msGMLFreeGroups(groupList);
           msGMLFreeGeometries(geometryList);
+          msFree(encoded_name);
         }
 
         msLayerClose(lp);
       } else {
-        msIO_printf("\n\n<!-- ERROR: Failed opening layer %s -->\n\n", encoded_name);
+        msIO_printf("\n\n<!-- ERROR: Failed opening layer %s -->\n\n", lp->name);
       }
 
     }
@@ -1333,7 +1334,6 @@ this request. Check wfs/ows_enable_request settings.", "msWFSDescribeFeatureType
   */
   msIO_printf("\n</schema>\n");
 
-  msFree(encoded_name);
   msFree(user_namespace_uri_encoded);
 
   if(layers)
@@ -1758,15 +1758,13 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
                             pszTmp = msStringConcatenate(pszTmp, tokens2[1]);
                           else
                             pszTmp = msStringConcatenate(pszTmp,tokens1[l]);
-                          if (tokens2 && n2>0)
-                            msFreeCharArray(tokens2, n2);
+                          msFreeCharArray(tokens2, n2);
                         } else
                           pszTmp = msStringConcatenate(pszTmp,tokens1[l]);
                       }
                       papszPropertyName[i] = msStrdup(pszTmp);
                       msFree(pszTmp);
-                      if (tokens1 && n1>0)
-                        msFreeCharArray(tokens1, n1);
+                      msFreeCharArray(tokens1, n1);
                     } else
                       papszPropertyName[i] = msStrdup(tokens[i]);
                     /* remove trailing ) */
@@ -1944,7 +1942,7 @@ int msWFSGetFeature(mapObj *map, wfsParamsObj *paramsObj, cgiRequestObj *req, ow
     }
   }
 
-  if(strncmp(paramsObj->pszVersion,"1.0",3) == 0 ) {
+  if(paramsObj->pszVersion && strncmp(paramsObj->pszVersion,"1.0",3) == 0 ) {
     output_mime_type = "text/xml";
   }
 
@@ -2494,8 +2492,11 @@ int msWFSDispatch(mapObj *map, cgiRequestObj *requestobj, owsRequestObj *ows_req
   paramsObj = msWFSCreateParamsObj();
   /* TODO : store also parameters that are inside the map object */
   /* into the paramsObj.  */
-  if (msWFSParseRequest(map, requestobj, ows_request, paramsObj, force_wfs_mode) == MS_FAILURE)
+  if (msWFSParseRequest(map, requestobj, ows_request, paramsObj, force_wfs_mode) == MS_FAILURE) {
+    msWFSFreeParamsObj(paramsObj);
+    free(paramsObj);
     return msWFSException(map, "request", "InvalidRequest", NULL);
+  }
 
   if (force_wfs_mode) {
     /*request is always required*/
@@ -3308,7 +3309,7 @@ int msWFSParseRequest(mapObj *map, cgiRequestObj *request, owsRequestObj *ows_re
         if (pszValue)
           wfsparams->pszVersion = msStrdup(pszValue);
         else
-          wfsparams->pszVersion = msStrdup(msStrdup(msWFSGetDefaultVersion(map)));
+          wfsparams->pszVersion = msStrdup(msWFSGetDefaultVersion(map));
 
         pszValue =
           CPLGetXMLValue(psGetCapabilities, "service",
diff --git a/mapwfs11.c b/mapwfs11.c
index 93cbd4a..1cfde2c 100644
--- a/mapwfs11.c
+++ b/mapwfs11.c
@@ -156,10 +156,7 @@ static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
   value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");
 
   if (value) {
-    if (encoding)
-      encoded = msGetEncodedString(value, encoding);
-    else
-      encoded = msGetEncodedString(value, "ISO-8859-1");
+    encoded = msGetEncodedString(value, encoding);
 
     msLibXml2GenerateList(
       xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
diff --git a/mapwfslayer.c b/mapwfslayer.c
index 0b73c48..6eca05a 100644
--- a/mapwfslayer.c
+++ b/mapwfslayer.c
@@ -416,8 +416,9 @@ static char *msBuildWFSLayerGetURL(mapObj *map, layerObj *lp, rectObj *bbox,
   /*      mutually exclusive.                                             */
   /* -------------------------------------------------------------------- */
   if (psParams->pszFilter) {
-    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), "&FILTER=%s",
-             msEncodeUrl(psParams->pszFilter));
+    char *encoded_filter = msEncodeUrl(psParams->pszFilter);
+    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), "&FILTER=%s",encoded_filter);
+    free(encoded_filter);
   } else {
 	  /*
 	   * take care about the axis order for WFS 1.1
@@ -654,8 +655,13 @@ int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
   pasReqInfo[(*numRequests)].debug = lp->debug;
 
   if (msHTTPAuthProxySetup(&(map->web.metadata), &(lp->metadata),
-                           pasReqInfo, *numRequests, map, "FO") != MS_SUCCESS)
+                           pasReqInfo, *numRequests, map, "FO") != MS_SUCCESS) {
+    if (psParams) {
+      msWFSFreeParamsObj(psParams);
+      free(psParams);
+    }
     return MS_FAILURE;
+  }
   
   /* ------------------------------------------------------------------
    * Pre-Open the layer now, (i.e. alloc and fill msWFSLayerInfo inside
@@ -684,7 +690,7 @@ int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
 
   if (psParams) {
     msWFSFreeParamsObj(psParams);
-    psParams = NULL;
+    free(psParams);
   }
   return nStatus;
 
diff --git a/mapwms.c b/mapwms.c
index 5568970..5063f39 100644
--- a/mapwms.c
+++ b/mapwms.c
@@ -250,9 +250,8 @@ int msWMSSetTimePattern(const char *timepatternstring, char *timestring, int che
       }
 
       msFreeCharArray(patterns, numpatterns);
-      msFreeCharArray(atimes, numtimes);              
-
     }
+    msFreeCharArray(atimes, numtimes);              
   }
 
   return ret;
@@ -413,17 +412,16 @@ void msWMSPrepareNestedGroups(mapObj* map, int nVersion, char*** nestedGroups, i
 int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int forcecharcter)
 {
   char **extents=NULL, **ranges=NULL, **onerange=NULL;
-  int numextents;
+  int numextents, numranges, numonerange;
   char **aextentvalues = NULL;
   int nextentvalues=0;
   pointObj *aextentranges=NULL;
   int nextentranges=0;
 
   int isextentavalue = MS_FALSE, isextentarange=MS_FALSE;
-  int i,j, ntmp;
+  int i,j,status=MS_FALSE;
   char **uservalues=NULL;
   int numuservalues=0;
-  char *stmp = NULL;
   int ischaracter = MS_FALSE;
   float minval, maxval,currentval,mincurrentval,maxcurrentval, mincurrentrange, maxcurrentrange;
 
@@ -456,9 +454,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
         ischaracter= !FLTIsNumeric((char *)dimensionextent);
 
     } else {
-      ntmp = -1;
-      ranges = msStringSplit (dimensionextent, '/', &ntmp);
-      if(ranges && (ntmp == 2 || ntmp == 3)) {
+      ranges = msStringSplit (dimensionextent, '/', &numranges);
+      if(ranges && (numranges == 2 || numranges == 3)) {
         /*single range*/
         isextentarange = MS_TRUE;
         aextentranges = msSmallMalloc(sizeof(pointObj));
@@ -468,10 +465,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
         /*ranges should be numeric*/
         ischaracter = MS_FALSE;
       }
-      if (ranges && ntmp > 0) {
-        msFreeCharArray(ranges, ntmp);
-        ranges = NULL;
-      }
+      msFreeCharArray(ranges, numranges);
+      ranges = NULL;
     }
   } else if (numextents > 1) { /*check if it is muliple values or mutliple ranges*/
     if (strstr(dimensionextent, "/") == NULL) {
@@ -479,10 +474,9 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
       isextentavalue = MS_TRUE;
       aextentvalues = (char **)msSmallMalloc(sizeof(char *)*numextents);
       for (i=0; i<numextents; i++) {
-        stmp = msStrdup(extents[i]);
+        char *stmp = msStrdup(extents[i]);
         msStringTrim(stmp);
-        aextentvalues[i] = msStrdup(stmp);
-        msFree(stmp);
+        aextentvalues[i] = stmp;
       }
       nextentvalues = numextents;
       if (!forcecharcter)
@@ -496,8 +490,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
       nextentranges=0;
 
       for (i=0; i<numextents; i++) {
-        onerange = msStringSplit(extents[i], '/', &ntmp);
-        if (!onerange || (ntmp != 2 && ntmp != 3)) {
+        onerange = msStringSplit(extents[i], '/', &numonerange);
+        if (!onerange || (numonerange != 2 && numonerange != 3)) {
           isvalidextent = MS_FALSE;
           break;
         }
@@ -506,13 +500,12 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
           aextentranges[nextentranges].x = atof(onerange[0]);
           aextentranges[nextentranges++].y = atof(onerange[1]);
         }
-        if (onerange && ntmp > 0 ) {
-          msFreeCharArray(onerange, ntmp);
-          onerange = NULL;
-        }
+        msFreeCharArray(onerange, numonerange);
+        onerange = NULL;
       }
       if (!isvalidextent) {
         msFree(aextentranges);
+        aextentranges = NULL;
         nextentranges = 0;
         isextentarange = MS_FALSE;
       }
@@ -529,7 +522,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
 
   /* make sure that we got a valid extent*/
   if (!isextentavalue && !isextentarange) {
-    return MS_FALSE;
+    status = MS_FALSE;
+    goto dimension_cleanup;
   }
 
   /*for the extent of the dimesion, we support
@@ -542,8 +536,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
   if (numuservalues == 1) {
     /*user iput=single*/
     /*is it descret or range*/
-    ranges = msStringSplit(uservalues[0], '/', &ntmp);
-    if (ntmp == 1) { /*discrete*/
+    ranges = msStringSplit(uservalues[0], '/', &numranges);
+    if (numranges == 1) { /*discrete*/
       if (isextentavalue) {
         /*single user value, single/multiple values extent*/
         for (i=0; i<nextentvalues; i++) {
@@ -569,7 +563,7 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
           }
         }
       }
-    } else if (ntmp == 2 || ntmp == 3) { /*range*/
+    } else if (numranges == 2 || numranges == 3) { /*range*/
       /*user input=single range. In this case the extents must
        be of a range type.*/
       mincurrentval = atof(ranges[0]);
@@ -587,8 +581,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
         }
       }
     }
-    if (ranges && ntmp > 0)
-      msFreeCharArray(ranges, ntmp);
+    msFreeCharArray(ranges, numranges);
+    ranges = NULL;
   } else if (numuservalues > 1) { /*user input=multiple*/
     if (strstr(value, "/") == NULL) {
       /*user input=multiple value*/
@@ -635,8 +629,8 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
 
       for (i=0; i<numuservalues; i++) {
         /*each ranges should be valid*/
-        onerange = msStringSplit(uservalues[i], '/', &ntmp);
-        if (ntmp == 2 || ntmp == 3) {
+        onerange = msStringSplit(uservalues[i], '/', &numonerange);
+        if (numonerange == 2 || numonerange == 3) {
           mincurrentval = atof(onerange[0]);
           maxcurrentval = atof(onerange[1]);
 
@@ -654,36 +648,45 @@ int msWMSValidateDimensionValue(char *value, const char *dimensionextent, int fo
             }
             if (j == nextentranges) {
               valueisvalid = MS_FALSE;
-              msFreeCharArray(onerange, ntmp);
+              msFreeCharArray(onerange, numonerange);
+              onerange = NULL;
               break;
             }
           }
         } else {
           valueisvalid = MS_FALSE;
         }
-        msFreeCharArray(onerange, ntmp);
+        msFreeCharArray(onerange, numonerange);
+        onerange = NULL;
       }
       uservaluevalid = valueisvalid;
     }
 
   }
-  if(uservalues && numuservalues > 0)
+  if(uservaluevalid)
+    status = MS_TRUE;
+
+dimension_cleanup:
+  if(ranges)
+    msFreeCharArray(ranges, numranges);
+  if(onerange)
+    msFreeCharArray(onerange, numonerange);
+  if(extents)
+    msFreeCharArray(extents, numextents);
+  if(uservalues)
     msFreeCharArray(uservalues, numuservalues);
 
-  if (aextentvalues && nextentvalues > 0) {
+  if (aextentvalues) {
     for (i=0; i<nextentvalues; i++)
       msFree(aextentvalues[i]);
     msFree(aextentvalues);
   }
 
-  if(aextentranges && nextentranges > 0) {
+  if(aextentranges) {
     msFree(aextentranges);
   }
 
-  if(uservaluevalid)
-    return MS_TRUE;
-
-  return MS_FALSE;
+  return status;
 }
 
 
@@ -1407,7 +1410,7 @@ this request. Check wms/ows_enable_request settings.",
   ** 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) {
+  if (strlen(srsbuffer) > 1 || nonsquare_enabled) {
     projectionObj newProj;
 
     if (map->projection.numargs <= 0) {
@@ -1427,7 +1430,7 @@ this request. Check wms/ows_enable_request settings.",
     }
 
     msInitProjection(&newProj);
-    if (srsbuffer != NULL && strlen(srsbuffer) > 1) {
+    if (strlen(srsbuffer) > 1) {
       int nTmp;
 
       if (nVersion >= OWS_1_3_0)
@@ -1471,7 +1474,7 @@ this request. Check wms/ows_enable_request settings.",
 
   /* 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) {
+  if (strlen(srsbuffer) > 1) {
     int nTmp;
     msFreeProjection(&map->projection);
     msInitProjection(&map->projection);
@@ -2260,8 +2263,8 @@ int msDumpLayer(mapObj *map, layerObj *lp, int nVersion, const char *script_url_
         msFree(pszDimensionDefaultName);
 
       }
-      msFreeCharArray(tokens, ntokens);
     }
+    msFreeCharArray(tokens, ntokens);
   }
 
 
@@ -2784,6 +2787,8 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
   if ((script_url=msOWSGetOnlineResource2(map, "MO", "onlineresource", req, validated_language)) == NULL ||
       (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
     msFree(validated_language);
+    msFree(schemalocation);
+    msFree(dtd_url);
     return msWMSException(map, nVersion, NULL, wms_exception_format);
   }
 
@@ -3354,7 +3359,7 @@ int msWMSGetCapabilities(mapObj *map, int nVersion, cgiRequestObj *req, owsReque
 
       /* We'll use this array of booleans to track which layer/group have been */
       /* processed already */
-      pabLayerProcessed = (char *)msSmallCalloc(map->numlayers, sizeof(char*));
+      pabLayerProcessed = (char *)msSmallCalloc(map->numlayers, sizeof(char));
 
       /* Mark disabled layers as processed to prevent from being displayed in nested groups (#4533)*/
       for(i=0; i<map->numlayers; i++) {
@@ -3886,7 +3891,7 @@ int msWMSFeatureInfo(mapObj *map, int nVersion, char **names, char **values, int
   isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
   msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
 
-  for(i=0; map && i<numentries; i++) {
+  for(i=0; i<numentries; i++) {
     if(strcasecmp(names[i], "QUERY_LAYERS") == 0) {
       char **layers;
       int numlayers, j, k;
@@ -4191,6 +4196,7 @@ int msWMSDescribeLayer(mapObj *map, int nVersion, char **names,
 
   for(i=0; map && i<numentries; i++) {
     if(strcasecmp(names[i], "LAYERS") == 0) {
+      if(layers) msFreeCharArray(layers, numlayers); /* free previous occurence of layers array if more than one was provided */
       layers = msStringSplit(values[i], ',', &numlayers);
     }
     if(strcasecmp(names[i], "VERSION") == 0) {
@@ -4724,7 +4730,7 @@ int msWMSGetStyles(mapObj *map, int nVersion, char **names,
   isUsedInNestedGroup = (int*)msSmallCalloc(map->numlayers, sizeof(int));
   msWMSPrepareNestedGroups(map, nVersion, nestedGroups, numNestedGroups, isUsedInNestedGroup);
 
-  for(i=0; map && i<numentries; i++) {
+  for(i=0; i<numentries; i++) {
     /* getMap parameters */
     if (strcasecmp(names[i], "LAYERS") == 0) {
       layers = msStringSplit(values[i], ',', &numlayers);
diff --git a/mapwmslayer.c b/mapwmslayer.c
index 98e1736..afe1971 100644
--- a/mapwmslayer.c
+++ b/mapwmslayer.c
@@ -756,7 +756,7 @@ msBuildWMSLayerURL(mapObj *map, layerObj *lp, int nRequestType,
 
     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 */
+    else if (nVersion > OWS_1_0_0)  /* 1.0.1 to 1.0.7 */
       pszExceptionsParam = "SE_XML";
     else
       pszExceptionsParam = "WMS_XML";
diff --git a/mapxbase.c b/mapxbase.c
index 2800066..9df2606 100644
--- a/mapxbase.c
+++ b/mapxbase.c
@@ -183,8 +183,11 @@ DBFHandle msDBFOpen( const char * pszFilename, const char * pszAccess )
       psDBF->fp = fopen( pszDBFFilename, pszAccess );
     }
   }
-  if( psDBF->fp == NULL )
+  if( psDBF->fp == NULL ) {
+    msFree(pszDBFFilename);
+    msFree(psDBF);
     return( NULL );
+  }
 
   psDBF->bNoHeader = MS_FALSE;
   psDBF->nCurrentRecord = -1;
diff --git a/renderers/agg/include/agg_conv_clipper.h b/renderers/agg/include/agg_conv_clipper.h
index 6db881d..4095766 100644
--- a/renderers/agg/include/agg_conv_clipper.h
+++ b/renderers/agg/include/agg_conv_clipper.h
@@ -15,6 +15,10 @@
 #ifndef AGG_CONV_CLIPPER_INCLUDED
 #define AGG_CONV_CLIPPER_INCLUDED
 
+#if defined(_MSC_VER) && (_MSC_VER >= 1800)
+#include <algorithm>
+#endif
+
 #include <cmath>
 #include "agg_basics.h"
 #include "agg_array.h"
diff --git a/renderers/agg/src/agg_vcgen_dash.cpp b/renderers/agg/src/agg_vcgen_dash.cpp
index 0f5550c..75a8f76 100644
--- a/renderers/agg/src/agg_vcgen_dash.cpp
+++ b/renderers/agg/src/agg_vcgen_dash.cpp
@@ -54,7 +54,7 @@ namespace mapserver
     //------------------------------------------------------------------------
     void vcgen_dash::add_dash(double dash_len, double gap_len)
     {
-        if(m_num_dashes < max_dashes)
+        if(m_num_dashes < max_dashes-1)
         {
             m_total_dash_len += dash_len + gap_len;
             m_dashes[m_num_dashes++] = dash_len;
diff --git a/scripts/vagrant/mapserver.sh b/scripts/vagrant/mapserver.sh
new file mode 100755
index 0000000..7ffe838
--- /dev/null
+++ b/scripts/vagrant/mapserver.sh
@@ -0,0 +1,33 @@
+NUMTHREADS=2
+if [[ -f /sys/devices/system/cpu/online ]]; then
+	# Calculates 1.5 times physical threads
+	NUMTHREADS=$(( ( $(cut -f 2 -d '-' /sys/devices/system/cpu/online) + 1 ) * 15 / 10  ))
+fi
+#NUMTHREADS=1 # disable MP
+export NUMTHREADS
+
+
+git clone https://github.com/mapserver/mapserver.git mapserver
+cd mapserver
+git submodule init
+git checkout branch-6-4
+git submodule update
+cd msautotest
+python -m SimpleHTTPServer &> /dev/null &
+cd ..
+mkdir build
+touch maplexer.l
+touch mapparser.y
+flex --nounistd -Pmsyy -i -omaplexer.c maplexer.l
+yacc -d -omapparser.c mapparser.y
+cd build
+cmake   -G "Unix Makefiles"  \
+        -DWITH_GD=1 -DWITH_CLIENT_WMS=1 \
+			  -DWITH_CLIENT_WFS=1 -DWITH_KML=1 -DWITH_SOS=1 -DWITH_PHP=1 \
+			  -DWITH_PYTHON=1 -DWITH_JAVA=0 -DWITH_THREAD_SAFETY=1 -DWITH_FRIBIDI=0 -DWITH_FCGI=0 -DWITH_EXEMPI=1 \
+			  -DCMAKE_BUILD_TYPE=Release -DWITH_RSVG=1 -DWITH_CURL=1 \
+        ..
+
+make -j $NUMTHREADS
+sudo make install
+
diff --git a/scripts/vagrant/postgis.sh b/scripts/vagrant/postgis.sh
new file mode 100755
index 0000000..c4cb4fb
--- /dev/null
+++ b/scripts/vagrant/postgis.sh
@@ -0,0 +1,8 @@
+cd mapserver/msautotest
+
+sudo sed -i  's/md5/trust/' /etc/postgresql/9.1/main/pg_hba.conf
+sudo sed -i  's/peer/trust/' /etc/postgresql/9.1/main/pg_hba.conf
+
+sudo service postgresql restart
+
+./create_postgis_test_data.sh
diff --git a/shptreevis.c b/shptreevis.c
index 948222c..1e6ee7b 100644
--- a/shptreevis.c
+++ b/shptreevis.c
@@ -70,6 +70,7 @@ char* AddFileSuffix ( const char * Filename, const char * Suffix )
   pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
   sprintf( pszFullname, "%s%s", pszBasename, Suffix);
 
+  free(pszBasename);
   return (pszFullname);
 }
 
diff --git a/tile4ms.c b/tile4ms.c
index 266bf3b..10c6b26 100644
--- a/tile4ms.c
+++ b/tile4ms.c
@@ -243,6 +243,7 @@ int process_shapefiles(char *metaFileNameP, char *tileFileNameP,
   fclose(metaFP);
 
   free(line.point);
+  free(theFields);
 
 
   printf("Processed %i of %i files\n", tilesProcessed, tilesFound);

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/mapserver.git



More information about the Pkg-grass-devel mailing list