[gdal] 01/06: Imported Upstream version 1.11.1+dfsg

Bas Couwenberg sebastic at xs4all.nl
Sun Oct 12 13:59:04 UTC 2014


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

sebastic-guest pushed a commit to branch experimental
in repository gdal.

commit 1750004ae775e41b2610e6daa1d4121918159559
Author: Bas Couwenberg <sebastic at xs4all.nl>
Date:   Sat Oct 11 14:32:58 2014 +0200

    Imported Upstream version 1.11.1+dfsg
---
 GDALmake.opt.in                                    |    3 +-
 NEWS                                               |  210 +
 VERSION                                            |    2 +-
 alg/gdal_crs.c                                     |    6 +-
 alg/gdal_rpc.cpp                                   |   12 +-
 alg/gdal_tps.cpp                                   |    8 +-
 alg/gdalcutline.cpp                                |   13 +-
 alg/gdalgeoloc.cpp                                 |    6 +-
 alg/gdalgrid.cpp                                   |   38 +-
 alg/gdalgridavx.cpp                                |   10 +-
 alg/gdalsievefilter.cpp                            |    6 +-
 alg/gdaltransformer.cpp                            |   18 +-
 alg/gdaltransformgeolocs.cpp                       |    2 +-
 alg/gdalwarper.cpp                                 |   12 +-
 alg/gdalwarper.h                                   |    7 +-
 alg/gdalwarpkernel_opencl.c                        |    5 +-
 alg/llrasterize.cpp                                |    8 +-
 alg/rasterfill.cpp                                 |    8 +-
 apps/gdaldem.cpp                                   |    4 +-
 apps/ogr2ogr.cpp                                   |   11 +-
 configure                                          |   32 +-
 configure.in                                       |   29 +-
 data/nitf_spec.xml                                 |    4 +-
 data/ruian_vf_ob_v1.gfs                            |   81 +
 data/ruian_vf_st_v1.gfs                            |   92 +-
 data/{ruian_vf_st_v1.gfs => ruian_vf_v1.gfs}       |  712 +-
 frmts/aaigrid/aaigriddataset.cpp                   |    6 +-
 frmts/adrg/adrgdataset.cpp                         |    6 +-
 frmts/aigrid/aigccitt.c                            |   13 +-
 frmts/airsar/airsardataset.cpp                     |    6 +-
 frmts/arg/argdataset.cpp                           |   11 +-
 frmts/blx/blx.c                                    |    2 +-
 frmts/bmp/bmpdataset.cpp                           |   10 +-
 frmts/bsb/bsb_read.c                               |   11 +-
 frmts/bsb/bsbdataset.cpp                           |    6 +-
 frmts/ceos/ceosdataset.cpp                         |    6 +-
 frmts/ceos/ceosopen.c                              |    6 +-
 frmts/ceos2/ceossar.c                              |   13 +-
 frmts/ceos2/sar_ceosdataset.cpp                    |   13 +-
 frmts/coasp/coasp_dataset.cpp                      |    8 +-
 frmts/cosar/cosar_dataset.cpp                      |    5 +-
 frmts/ctg/ctgdataset.cpp                           |    7 +-
 frmts/dimap/dimapdataset.cpp                       |   34 +-
 frmts/dted/dted_ptstream.c                         |    6 +-
 frmts/dted/dteddataset.cpp                         |    8 +-
 frmts/e00grid/e00griddataset.cpp                   |    6 +-
 frmts/elas/elasdataset.cpp                         |    8 +-
 frmts/envisat/EnvisatFile.c                        |   18 +-
 frmts/envisat/envisatdataset.cpp                   |    6 +-
 frmts/envisat/records.c                            |    8 +-
 frmts/ers/ersdataset.cpp                           |   14 +-
 frmts/georaster/georaster_dataset.cpp              | 4228 +++++------
 frmts/georaster/georaster_priv.h                   |  942 +--
 frmts/georaster/georaster_wrapper.cpp              | 7971 ++++++++++----------
 frmts/gff/gff_dataset.cpp                          |    8 +-
 frmts/gif/biggifdataset.cpp                        |   19 +-
 frmts/gif/gifabstractdataset.cpp                   |   48 +-
 frmts/gif/gifabstractdataset.h                     |    6 +-
 frmts/gif/gifdataset.cpp                           |   39 +-
 frmts/grib/degrib18/degrib/clock.c                 |    6 +-
 frmts/grib/degrib18/degrib/degrib1.cpp             |    4 +-
 frmts/grib/degrib18/degrib/degrib2.cpp             |    4 +-
 frmts/grib/degrib18/degrib/grib1tab.cpp            |   10 +-
 frmts/grib/degrib18/degrib/grib2api.c              |   56 +-
 frmts/grib/degrib18/degrib/inventory.cpp           |    6 +-
 frmts/grib/degrib18/degrib/metaname.cpp            |   14 +-
 frmts/grib/degrib18/degrib/metaparse.cpp           |    4 +-
 frmts/grib/degrib18/degrib/myutil.c                |   10 +-
 frmts/grib/degrib18/degrib/tdlpack.cpp             |   12 +-
 frmts/grib/degrib18/g2clib-1.0.4/enc_jpeg2000.c    |   17 +-
 frmts/grib/degrib18/g2clib-1.0.4/g2_addfield.c     |    2 +-
 frmts/grib/degrib18/g2clib-1.0.4/reduce.c          |    5 +-
 frmts/grib/gribdataset.cpp                         |   15 +-
 frmts/gsg/gs7bgdataset.cpp                         |   20 +-
 frmts/gsg/gsagdataset.cpp                          |   11 +-
 frmts/gsg/gsbgdataset.cpp                          |   10 +-
 frmts/gtiff/geotiff.cpp                            |  185 +-
 frmts/gtiff/gt_jpeg_copy.cpp                       |    6 +-
 frmts/gtiff/libgeotiff/geo_print.c                 |    2 +-
 frmts/gtiff/libgeotiff/geo_set.c                   |    5 +-
 frmts/gtiff/libtiff/tif_jpeg.c                     |    1 +
 frmts/gxf/gxfdataset.cpp                           |    6 +-
 frmts/hdf5/bagdataset.cpp                          |   15 +-
 frmts/hfa/hfadataset.cpp                           |   17 +-
 frmts/hfa/hfaentry.cpp                             |   10 +-
 frmts/hfa/hfaopen.cpp                              |    6 +-
 frmts/hfa/hfatype.cpp                              |    6 +-
 frmts/ingr/GNUmakefile                             |    2 +-
 frmts/ingr/JpegHelper.cpp                          |    2 +-
 frmts/iris/irisdataset.cpp                         |    6 +-
 frmts/jaxapalsar/jaxapalsardataset.cpp             |    6 +-
 frmts/jdem/jdemdataset.cpp                         |   10 +-
 frmts/jp2kak/vsil_target.h                         |    2 +-
 frmts/jpeg/jpgdataset.cpp                          |    7 +-
 frmts/jpeg/vsidataio.cpp                           |    6 +-
 frmts/jpipkak/jpipkakdataset.cpp                   |   12 +-
 frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp   |   11 +-
 frmts/l1b/l1bdataset.cpp                           |   14 +-
 frmts/leveller/levellerdataset.cpp                 |   11 +-
 frmts/map/mapdataset.cpp                           |    6 +-
 frmts/mbtiles/mbtilesdataset.cpp                   |   40 +-
 frmts/mem/memdataset.cpp                           |   12 +-
 frmts/msg/msgcommand.cpp                           |    3 +-
 frmts/msgn/msgndataset.cpp                         |    9 +-
 frmts/ngsgeoid/ngsgeoiddataset.cpp                 |    6 +-
 frmts/nitf/GNUmakefile                             |    6 +-
 frmts/nitf/nitfaridpcm.cpp                         |    8 +-
 frmts/nitf/nitfdes.c                               |   10 +-
 frmts/nitf/nitffile.c                              |   14 +-
 frmts/nitf/nitfimage.c                             |   24 +-
 frmts/nitf/nitfrasterband.cpp                      |    6 +-
 frmts/northwood/grcdataset.cpp                     |    4 +-
 frmts/northwood/grddataset.cpp                     |    4 +-
 frmts/northwood/northwood.cpp                      |    5 +-
 frmts/openjpeg/openjpegdataset.cpp                 |   10 +-
 .../pcidsk/sdk/channel/cbandinterleavedchannel.cpp |    4 +-
 frmts/pcidsk/sdk/channel/cexternalchannel.cpp      |    4 +-
 frmts/pcidsk/sdk/channel/cpcidskchannel.cpp        |   14 +-
 .../sdk/channel/cpixelinterleavedchannel.cpp       |    4 +-
 frmts/pcidsk/sdk/channel/ctiledchannel.cpp         |    4 +-
 frmts/pcidsk/sdk/segment/cpcidsktoutinmodel.cpp    |    4 +-
 frmts/pcraster/libcsf/dumconv.c                    |    4 +-
 frmts/pcraster/libcsf/putattr.c                    |    2 +-
 frmts/pcraster/libcsf/swapio.c                     |    2 +-
 frmts/pcraster/pcrasterdataset.cpp                 |    8 +-
 frmts/pcraster/pcrasterrasterband.cpp              |    8 +-
 frmts/pdf/pdfdataset.cpp                           |   22 +-
 frmts/pdf/pdfobject.h                              |   11 +-
 frmts/pds/isis2dataset.cpp                         |   12 +-
 frmts/png/pngdataset.cpp                           |    6 +-
 frmts/postgisraster/postgisrasterdataset.cpp       |    3 +-
 frmts/r/rcreatecopy.cpp                            |    6 +-
 frmts/r/rdataset.cpp                               |    6 +-
 frmts/rasterlite/rasterlitecreatecopy.cpp          |    8 +-
 frmts/raw/btdataset.cpp                            |   20 +-
 frmts/raw/cpgdataset.cpp                           |    8 +-
 frmts/raw/ctable2dataset.cpp                       |    2 +-
 frmts/raw/envidataset.cpp                          |   18 +-
 frmts/raw/genbindataset.cpp                        |    2 +-
 frmts/raw/gtxdataset.cpp                           |    8 +-
 frmts/raw/hkvdataset.cpp                           |    6 +-
 frmts/raw/krodataset.cpp                           |   11 +-
 frmts/raw/landataset.cpp                           |    8 +-
 frmts/raw/mffdataset.cpp                           |    6 +-
 frmts/raw/ntv2dataset.cpp                          |    6 +-
 frmts/raw/rawdataset.cpp                           |   12 +-
 frmts/sdts/sdtsrasterreader.cpp                    |    7 +-
 frmts/sgi/sgidataset.cpp                           |   10 +-
 frmts/srtmhgt/srtmhgtdataset.cpp                   |    6 +-
 frmts/terragen/terragendataset.cpp                 |    6 +-
 frmts/usgsdem/usgsdem_create.cpp                   |   10 +-
 frmts/usgsdem/usgsdemdataset.cpp                   |    6 +-
 frmts/vrt/vrt_tutorial.dox                         |    4 +-
 frmts/vrt/vrtdataset.cpp                           |    8 +-
 frmts/vrt/vrtdataset.h                             |    6 +-
 frmts/vrt/vrtdriver.cpp                            |    7 +-
 frmts/vrt/vrtrawrasterband.cpp                     |   24 +-
 frmts/vrt/vrtsourcedrasterband.cpp                 |  120 +-
 frmts/vrt/vrtsources.cpp                           |   71 +-
 frmts/vrt/vrtwarped.cpp                            |    8 +-
 frmts/wcs/wcsdataset.cpp                           |    8 +-
 frmts/wms/gdalwmscache.cpp                         |    5 +-
 frmts/wms/gdalwmsdataset.cpp                       |   13 +-
 frmts/wms/gdalwmsrasterband.cpp                    |    8 +-
 frmts/wms/minidriver.cpp                           |   23 +-
 frmts/wms/minidriver_tiled_wms.cpp                 |    3 +-
 frmts/wms/minidriver_tileservice.cpp               |    9 +-
 frmts/wms/minidriver_tms.cpp                       |    5 +-
 frmts/wms/minidriver_virtualearth.cpp              |    4 +-
 frmts/wms/minidriver_wms.cpp                       |    8 +-
 frmts/wms/minidriver_worldwind.cpp                 |    5 +-
 frmts/wms/wmsdriver.cpp                            |    8 +-
 frmts/wms/wmsmetadataset.cpp                       |   20 +-
 frmts/xpm/xpmdataset.cpp                           |   15 +-
 frmts/xyz/xyzdataset.cpp                           |   14 +-
 frmts/zmap/zmapdataset.cpp                         |    8 +-
 gcore/gdal_priv.h                                  |    5 +-
 gcore/gdal_rat.cpp                                 |   24 +-
 gcore/gdal_version.h                               |    6 +-
 gcore/gdalallvalidmaskband.cpp                     |    8 +-
 gcore/gdalclientserver.cpp                         |   11 +-
 gcore/gdaldataset.cpp                              |   16 +-
 gcore/gdaldefaultasync.cpp                         |    5 +-
 gcore/gdaldefaultoverviews.cpp                     |   15 +-
 gcore/gdalexif.cpp                                 |   26 +-
 gcore/gdalmultidomainmetadata.cpp                  |    7 +-
 gcore/gdalpamrasterband.cpp                        |   17 +-
 gcore/gdalproxydataset.cpp                         |    8 +-
 gcore/gdalproxypool.cpp                            |   12 +-
 gcore/gdalrasterband.cpp                           |   58 +-
 gcore/gdalvirtualmem.cpp                           |   18 +-
 gcore/overview.cpp                                 |  134 +-
 man/man1/gdal-config.1                             |    4 +-
 man/man1/gdal2tiles.1                              |    4 +-
 man/man1/gdal_calc.1                               |    4 +-
 man/man1/gdal_contour.1                            |    4 +-
 man/man1/gdal_edit.1                               |    4 +-
 man/man1/gdal_fillnodata.1                         |    4 +-
 man/man1/gdal_grid.1                               |    4 +-
 man/man1/gdal_merge.1                              |    4 +-
 man/man1/gdal_polygonize.1                         |    4 +-
 man/man1/gdal_proximity.1                          |    4 +-
 man/man1/gdal_rasterize.1                          |    4 +-
 man/man1/gdal_retile.1                             |    4 +-
 man/man1/gdal_sieve.1                              |    4 +-
 man/man1/gdal_translate.1                          |    4 +-
 man/man1/gdal_utilities.1                          |    4 +-
 man/man1/gdaladdo.1                                |    4 +-
 man/man1/gdalbuildvrt.1                            |    4 +-
 man/man1/gdalcompare.1                             |    4 +-
 man/man1/gdaldem.1                                 |    4 +-
 man/man1/gdalinfo.1                                |    4 +-
 man/man1/gdallocationinfo.1                        |    4 +-
 man/man1/gdalmanage.1                              |    4 +-
 man/man1/gdalmove.1                                |    4 +-
 man/man1/gdalsrsinfo.1                             |    4 +-
 man/man1/gdaltindex.1                              |    4 +-
 man/man1/gdaltransform.1                           |    4 +-
 man/man1/gdalwarp.1                                |    4 +-
 man/man1/nearblack.1                               |    4 +-
 man/man1/ogr2ogr.1                                 |    4 +-
 man/man1/ogr_utilities.1                           |    4 +-
 man/man1/ogrinfo.1                                 |    4 +-
 man/man1/ogrlineref.1                              |    4 +-
 man/man1/ogrtindex.1                               |    4 +-
 man/man1/pct2rgb.1                                 |    4 +-
 man/man1/rgb2pct.1                                 |    4 +-
 ogr/ogr_expat.cpp                                  |    6 +-
 ogr/ogr_fromepsg.cpp                               |    6 +-
 ogr/ogr_geocoding.cpp                              |   10 +-
 ogr/ogr_srs_proj4.cpp                              |   32 +-
 ogr/ogr_srs_xml.cpp                                |    5 +-
 ogr/ogrfeature.cpp                                 |   26 +-
 ogr/ogrgeometry.cpp                                |    6 +-
 ogr/ogrgeometrycollection.cpp                      |    6 +-
 .../aeronavfaa/ograeronavfaadatasource.cpp         |    7 +-
 ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadriver.cpp |    7 +-
 ogr/ogrsf_frmts/aeronavfaa/ograeronavfaalayer.cpp  |    7 +-
 ogr/ogrsf_frmts/arcgen/ograrcgendatasource.cpp     |    7 +-
 ogr/ogrsf_frmts/arcgen/ograrcgendriver.cpp         |    7 +-
 ogr/ogrsf_frmts/arcgen/ograrcgenlayer.cpp          |    7 +-
 ogr/ogrsf_frmts/avc/avc_bin.c                      |    2 +-
 ogr/ogrsf_frmts/avc/avc_binwr.c                    |    6 +-
 ogr/ogrsf_frmts/avc/avc_misc.c                     |    2 +-
 ogr/ogrsf_frmts/avc/ogravcbindatasource.cpp        |    7 +-
 ogr/ogrsf_frmts/avc/ogravcbindriver.cpp            |    7 +-
 ogr/ogrsf_frmts/avc/ogravce00datasource.cpp        |    7 +-
 ogr/ogrsf_frmts/avc/ogravce00driver.cpp            |    3 +-
 ogr/ogrsf_frmts/avc/ogravclayer.cpp                |    7 +-
 ogr/ogrsf_frmts/bna/ogrbnadatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/bna/ogrbnalayer.cpp                |    5 +-
 ogr/ogrsf_frmts/bna/ogrbnaparser.cpp               |    6 +-
 ogr/ogrsf_frmts/bna/ogrbnaparser.h                 |    3 +-
 ogr/ogrsf_frmts/cartodb/ogrcartodbdatasource.cpp   |    6 +-
 ogr/ogrsf_frmts/cartodb/ogrcartodbtablelayer.cpp   |    7 +-
 ogr/ogrsf_frmts/couchdb/ogrcouchdbdatasource.cpp   |    6 +-
 ogr/ogrsf_frmts/couchdb/ogrcouchdbdriver.cpp       |    7 +-
 ogr/ogrsf_frmts/couchdb/ogrcouchdbtablelayer.cpp   |    6 +-
 ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp           |    6 +-
 ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp                |   32 +-
 ogr/ogrsf_frmts/dgn/dgnhelp.cpp                    |   12 +-
 ogr/ogrsf_frmts/dgn/dgnread.cpp                    |    7 +-
 ogr/ogrsf_frmts/dgn/dgnstroke.cpp                  |    8 +-
 ogr/ogrsf_frmts/dgn/dgnwrite.cpp                   |   13 +-
 ogr/ogrsf_frmts/dgn/ogrdgnlayer.cpp                |    9 +-
 ogr/ogrsf_frmts/dxf/ogrdxfdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp               |    7 +-
 ogr/ogrsf_frmts/dxf/ogrdxfwriterlayer.cpp          |    7 +-
 ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp     |    7 +-
 ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp         |    7 +-
 ogr/ogrsf_frmts/elastic/ogrelasticdatasource.cpp   |   19 +-
 ogr/ogrsf_frmts/elastic/ogrelasticdriver.cpp       |    7 +-
 ogr/ogrsf_frmts/elastic/ogrelasticlayer.cpp        |   19 +-
 ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp              |   51 +-
 ogr/ogrsf_frmts/filegdb/ogr_fgdb.h                 |    5 +-
 ogr/ogrsf_frmts/generic/ogrlayer.cpp               |    8 +-
 ogr/ogrsf_frmts/generic/ogrlayerdecorator.cpp      |    8 +-
 ogr/ogrsf_frmts/geoconcept/geoconcept.c            |    6 +-
 ogr/ogrsf_frmts/geoconcept/geoconcept.h            |   15 -
 ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.c   |    2 +-
 ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.h   |   11 -
 ogr/ogrsf_frmts/geoconcept/ogrgeoconceptlayer.cpp  |    6 +-
 ogr/ogrsf_frmts/geojson/libjson/json_object.c      |   16 +-
 .../geojson/libjson/json_object_iterator.c         |    4 +-
 ogr/ogrsf_frmts/geojson/ogr_geojson.h              |    7 +-
 ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp      |    4 +-
 ogr/ogrsf_frmts/geojson/ogrgeojsonlayer.cpp        |    8 +-
 ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp       |   14 +-
 ogr/ogrsf_frmts/geojson/ogrgeojsonutils.cpp        |    7 +-
 ogr/ogrsf_frmts/geojson/ogrgeojsonwriter.cpp       |    6 +-
 ogr/ogrsf_frmts/geojson/ogrtopojsonreader.cpp      |    4 +-
 ogr/ogrsf_frmts/georss/ogrgeorssdatasource.cpp     |   12 +-
 ogr/ogrsf_frmts/georss/ogrgeorsslayer.cpp          |    7 +-
 ogr/ogrsf_frmts/gft/ogrgftdatasource.cpp           |    6 +-
 ogr/ogrsf_frmts/gft/ogrgftdriver.cpp               |    7 +-
 ogr/ogrsf_frmts/gft/ogrgfttablelayer.cpp           |    8 +-
 ogr/ogrsf_frmts/gme/ogr_gme.h                      |    6 +-
 ogr/ogrsf_frmts/gme/ogrgmedatasource.cpp           |    2 +-
 ogr/ogrsf_frmts/gme/ogrgmedriver.cpp               |    3 +-
 ogr/ogrsf_frmts/gme/ogrgmejson.cpp                 |   11 +-
 ogr/ogrsf_frmts/gme/ogrgmelayer.cpp                |   98 +-
 ogr/ogrsf_frmts/gml/gmlfeature.cpp                 |    5 +-
 ogr/ogrsf_frmts/gml/gmlhandler.cpp                 |   17 +-
 ogr/ogrsf_frmts/gml/gmlreader.cpp                  |   26 +-
 ogr/ogrsf_frmts/gml/gmlreader.h                    |    6 +-
 ogr/ogrsf_frmts/gml/gmlreaderp.h                   |   11 +-
 ogr/ogrsf_frmts/gml/hugefileresolver.cpp           |    8 +-
 ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp           |    2 +-
 ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp   |    5 +-
 ogr/ogrsf_frmts/gpkg/ogrgeopackagelayer.cpp        |   16 +-
 ogr/ogrsf_frmts/gpkg/ogrgeopackageutility.cpp      |    4 +-
 ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp |    7 +-
 ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp           |    8 +-
 ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp                |   10 +-
 ogr/ogrsf_frmts/gtm/gtmtracklayer.cpp              |    4 +-
 ogr/ogrsf_frmts/gtm/gtmwaypointlayer.cpp           |    4 +-
 ogr/ogrsf_frmts/gtm/ogrgtmdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/gtm/ogrgtmlayer.cpp                |    4 +-
 ogr/ogrsf_frmts/htf/ogrhtfdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/htf/ogrhtfdriver.cpp               |    7 +-
 ogr/ogrsf_frmts/idrisi/generate_test_files.c       |   51 +-
 ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp     |    7 +-
 ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp         |    5 +-
 ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp          |   54 +-
 ogr/ogrsf_frmts/kml/kml.cpp                        |   18 +-
 ogr/ogrsf_frmts/kml/ogrkmldatasource.cpp           |    4 +-
 ogr/ogrsf_frmts/kml/ogrkmllayer.cpp                |    4 +-
 ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp           |   14 +-
 ogr/ogrsf_frmts/mem/ogrmemdriver.cpp               |    7 +-
 ogr/ogrsf_frmts/mem/ogrmemlayer.cpp                |   10 +-
 ogr/ogrsf_frmts/mitab/mitab.h                      |   33 +-
 ogr/ogrsf_frmts/mitab/mitab_bounds.cpp             |    2 +
 ogr/ogrsf_frmts/mitab/mitab_feature_mif.cpp        |    4 +-
 ogr/ogrsf_frmts/mitab/mitab_mapindexblock.cpp      |    2 +-
 ogr/ogrsf_frmts/mitab/mitab_miffile.cpp            |   17 +-
 ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp            |    5 +-
 ogr/ogrsf_frmts/mitab/mitab_tabseamless.cpp        |    6 +-
 ogr/ogrsf_frmts/mitab/mitab_tabview.cpp            |    4 +-
 ogr/ogrsf_frmts/mssqlspatial/ogr_mssqlspatial.h    |    3 +-
 .../mssqlspatial/ogrmssqlspatialdatasource.cpp     | 2429 +++---
 .../mssqlspatial/ogrmssqlspatialselectlayer.cpp    |    7 +-
 .../mssqlspatial/ogrmssqlspatialtablelayer.cpp     | 2486 +++---
 ogr/ogrsf_frmts/mysql/GNUmakefile                  |    5 -
 ogr/ogrsf_frmts/mysql/ogrmysqldatasource.cpp       |   36 +-
 ogr/ogrsf_frmts/mysql/ogrmysqldriver.cpp           |   33 +-
 ogr/ogrsf_frmts/nas/drv_nas.html                   |    4 +-
 ogr/ogrsf_frmts/nas/nashandler.cpp                 |  151 +-
 ogr/ogrsf_frmts/nas/nasreader.cpp                  |   42 +-
 ogr/ogrsf_frmts/nas/nasreaderp.h                   |   31 +-
 ogr/ogrsf_frmts/nas/ogr_nas.h                      |   22 +-
 ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp           |    6 +-
 ogr/ogrsf_frmts/nas/ogrnaslayer.cpp                |   16 +-
 ogr/ogrsf_frmts/nas/ogrnasrelationlayer.cpp        |    8 +-
 ogr/ogrsf_frmts/ntf/ntf_estlayers.cpp              |    8 +-
 ogr/ogrsf_frmts/ntf/ntf_raster.cpp                 |    7 +-
 ogr/ogrsf_frmts/ntf/ogrntffeatureclasslayer.cpp    |    7 +-
 ogr/ogrsf_frmts/oci/ogrocisession.cpp              |    7 +-
 ogr/ogrsf_frmts/oci/ogrocistroke.cpp               |  542 +-
 ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp        |   22 +-
 ogr/ogrsf_frmts/ods/ods_formula_parser.cpp         |    4 +-
 ogr/ogrsf_frmts/ods/ods_formula_parser.y           |    4 +-
 ogr/ogrsf_frmts/ods/ogrodsdatasource.cpp           |   22 +-
 ogr/ogrsf_frmts/openair/ogropenairdatasource.cpp   |    7 +-
 ogr/ogrsf_frmts/openair/ogropenairdriver.cpp       |    7 +-
 ogr/ogrsf_frmts/openair/ogropenairlabellayer.cpp   |    7 +-
 ogr/ogrsf_frmts/openair/ogropenairlayer.cpp        |    7 +-
 ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp       |   65 +-
 ogr/ogrsf_frmts/openfilegdb/filegdbtable.h         |   11 +-
 .../openfilegdb/ogropenfilegdblayer.cpp            |   35 +-
 ogr/ogrsf_frmts/osm/gpb.h                          |    3 +-
 ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp           |   18 +-
 ogr/ogrsf_frmts/osm/ogrosmdriver.cpp               |   12 +-
 ogr/ogrsf_frmts/osm/ogrosmlayer.cpp                |    6 +-
 ogr/ogrsf_frmts/osm/osm_parser.cpp                 |   26 +-
 ogr/ogrsf_frmts/pcidsk/ogrpcidskdatasource.cpp     |    3 +-
 ogr/ogrsf_frmts/pcidsk/ogrpcidskdriver.cpp         |    3 +-
 ogr/ogrsf_frmts/pdf/ogrpdfdatasource.cpp           |   10 +-
 ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/pds/ogrpdsdriver.cpp               |    7 +-
 ogr/ogrsf_frmts/pg/ogrpgtablelayer.cpp             |   10 +-
 ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp         |    8 +-
 ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp          |   12 +-
 ogr/ogrsf_frmts/rec/ogrreclayer.cpp                |    7 +-
 ogr/ogrsf_frmts/s57/ogrs57datasource.cpp           |    7 +-
 ogr/ogrsf_frmts/s57/s57featuredefns.cpp            |    7 +-
 ogr/ogrsf_frmts/sdts/ogrsdtslayer.cpp              |    7 +-
 ogr/ogrsf_frmts/segukooa/ogrsegukooadatasource.cpp |    7 +-
 ogr/ogrsf_frmts/segukooa/ogrsegukooadriver.cpp     |    7 +-
 ogr/ogrsf_frmts/segy/ogrsegydatasource.cpp         |    7 +-
 ogr/ogrsf_frmts/segy/ogrsegydriver.cpp             |    7 +-
 ogr/ogrsf_frmts/shape/dbfopen.c                    |   51 +-
 ogr/ogrsf_frmts/shape/ogrshapedriver.cpp           |    7 +-
 ogr/ogrsf_frmts/shape/shape2ogr.cpp                |   36 +-
 ogr/ogrsf_frmts/shape/shpopen.c                    |   31 +-
 ogr/ogrsf_frmts/shape/shptree.c                    |    4 +-
 ogr/ogrsf_frmts/sqlite/ogr_sqlite.h                |    6 +-
 ogr/ogrsf_frmts/sqlite/ogrsqliteexecutesql.cpp     |   16 +-
 ogr/ogrsf_frmts/sqlite/ogrsqlitelayer.cpp          |    6 +-
 ogr/ogrsf_frmts/sqlite/ogrsqliteregexp.cpp         |   14 +-
 ogr/ogrsf_frmts/sqlite/ogrsqlitesqlfunctions.cpp   |    8 +-
 ogr/ogrsf_frmts/sqlite/ogrsqlitetablelayer.cpp     |    7 +-
 ogr/ogrsf_frmts/sqlite/ogrsqlitevfs.cpp            |   77 +-
 ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp     |    6 +-
 ogr/ogrsf_frmts/sua/ogrsuadatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/sua/ogrsuadriver.cpp               |    7 +-
 ogr/ogrsf_frmts/sua/ogrsualayer.cpp                |    7 +-
 ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp           |    8 +-
 ogr/ogrsf_frmts/svg/ogrsvgdriver.cpp               |    6 +-
 ogr/ogrsf_frmts/svg/ogrsvglayer.cpp                |   10 +-
 ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp           |    9 +-
 ogr/ogrsf_frmts/sxf/ogrsxflayer.cpp                |   12 +-
 ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp       |   13 +-
 ogr/ogrsf_frmts/tiger/ogrtigerlayer.cpp            |    8 +-
 ogr/ogrsf_frmts/tiger/tigeraltname.cpp             |    7 +-
 ogr/ogrsf_frmts/tiger/tigerarealandmarks.cpp       |    7 +-
 ogr/ogrsf_frmts/tiger/tigercompletechain.cpp       |   10 +-
 ogr/ogrsf_frmts/tiger/tigerentitynames.cpp         |    7 +-
 ogr/ogrsf_frmts/tiger/tigerfeatureids.cpp          |    7 +-
 ogr/ogrsf_frmts/tiger/tigerfilebase.cpp            |    7 +-
 ogr/ogrsf_frmts/tiger/tigeridhistory.cpp           |    7 +-
 ogr/ogrsf_frmts/tiger/tigerkeyfeatures.cpp         |    8 +-
 ogr/ogrsf_frmts/tiger/tigerlandmarks.cpp           |    6 +-
 ogr/ogrsf_frmts/tiger/tigeroverunder.cpp           |    7 +-
 ogr/ogrsf_frmts/tiger/tigerpip.cpp                 |    6 +-
 ogr/ogrsf_frmts/tiger/tigerpolychainlink.cpp       |    8 +-
 ogr/ogrsf_frmts/tiger/tigerpolygon.cpp             |    7 +-
 ogr/ogrsf_frmts/tiger/tigerpolygoncorrections.cpp  |    7 +-
 ogr/ogrsf_frmts/tiger/tigerpolygoneconomic.cpp     |    7 +-
 ogr/ogrsf_frmts/tiger/tigerspatialmetadata.cpp     |    8 +-
 ogr/ogrsf_frmts/tiger/tigertlidrange.cpp           |    8 +-
 ogr/ogrsf_frmts/tiger/tigerzerocellid.cpp          |    8 +-
 ogr/ogrsf_frmts/tiger/tigerzipcodes.cpp            |    7 +-
 ogr/ogrsf_frmts/tiger/tigerzipplus4.cpp            |    8 +-
 ogr/ogrsf_frmts/vfk/ogrvfkdriver.cpp               |    6 +-
 ogr/ogrsf_frmts/vfk/vfkreader.cpp                  |   79 +-
 ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp            |    4 +-
 ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp               |   17 +-
 ogr/ogrsf_frmts/wasp/ogrwasplayer.cpp              |    5 +-
 ogr/ogrsf_frmts/wfs/ogrwfsdatasource.cpp           |    7 +-
 ogr/ogrsf_frmts/wfs/ogrwfsdriver.cpp               |    5 +-
 ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp                |    6 +-
 ogr/ogrsf_frmts/xlsx/ogrxlsxdatasource.cpp         |   28 +-
 ogr/ogrsf_frmts/xplane/ogrxplanedatasource.cpp     |    5 +-
 ogr/ogrsf_frmts/xplane/ogrxplanedriver.cpp         |    2 +-
 ogr/ogrutils.cpp                                   |    7 +-
 ogr/osr_cs_wkt.c                                   |    6 +-
 ogr/swq_select.cpp                                 |    3 +-
 port/cpl_conv.cpp                                  |   17 +-
 port/cpl_getexecpath.cpp                           |    7 +-
 port/cpl_google_oauth2.cpp                         |    2 +-
 port/cpl_http.cpp                                  |    8 +-
 port/cpl_minizip_ioapi.cpp                         |   14 +-
 port/cpl_minizip_unzip.cpp                         |   22 +-
 port/cpl_minizip_zip.cpp                           |   12 +-
 port/cpl_multiproc.cpp                             |    7 +-
 port/cpl_port.h                                    |    9 +-
 port/cpl_progress.cpp                              |   10 +-
 port/cpl_spawn.cpp                                 |   19 +-
 port/cpl_virtualmem.cpp                            |   64 +-
 port/cpl_vsi_virtual.h                             |    4 +-
 port/cpl_vsil_abstract_archive.cpp                 |   14 +-
 port/cpl_vsil_buffered_reader.cpp                  |    6 +-
 port/cpl_vsil_cache.cpp                            |    3 +-
 port/cpl_vsil_curl.cpp                             |   14 +-
 port/cpl_vsil_curl_streaming.cpp                   |    6 +-
 port/cpl_vsil_gzip.cpp                             |   61 +-
 port/cpl_vsil_sparsefile.cpp                       |   21 +-
 port/cpl_vsil_stdin.cpp                            |    9 +-
 port/cpl_vsil_stdout.cpp                           |   26 +-
 port/cpl_vsil_subfile.cpp                          |   18 +-
 port/cpl_vsil_unix_stdio_64.cpp                    |   12 +-
 port/cpl_xml_validate.cpp                          |    6 +-
 port/cplgetsymbol.cpp                              |    8 +-
 swig/include/java/gdal_java.i                      |    4 +-
 swig/include/perl/gdal_perl.i                      |    4 +-
 swig/include/perl/ogr_perl.i                       |    2 +-
 swig/include/perl/typemaps_perl.i                  |    2 +-
 swig/perl/gdal_wrap.cpp                            |   32 +-
 swig/perl/lib/Geo/GDAL.pm                          |    4 +-
 swig/perl/lib/Geo/OGR.pm                           |    2 +-
 swig/perl/ogr_wrap.cpp                             |   16 +-
 swig/python/README.txt                             |    4 +-
 swig/python/scripts/gdal2tiles.py                  |    8 +-
 swig/python/scripts/pct2rgb.py                     |    4 +-
 swig/python/setup.py                               |    2 +-
 487 files changed, 13655 insertions(+), 11650 deletions(-)

diff --git a/GDALmake.opt.in b/GDALmake.opt.in
index 7140214..82525d9 100644
--- a/GDALmake.opt.in
+++ b/GDALmake.opt.in
@@ -87,7 +87,7 @@ GDAL_INCLUDE	=	-I$(GDAL_ROOT)/port -I$(GDAL_ROOT)/gcore \
 # libtool targets and help variables
 LIBGDAL	:=		libgdal.la
 LIBGDAL_CURRENT	:=	19
-LIBGDAL_REVISION	:=	0
+LIBGDAL_REVISION	:=	1
 LIBGDAL_AGE	:=	18
 
 # native build targets and variables
@@ -126,7 +126,6 @@ INGRES_INC = @INGRES_INC@
 HAVE_MYSQL =	@HAVE_MYSQL@
 MYSQL_LIB  =	@MYSQL_LIB@
 MYSQL_INC  =	@MYSQL_INC@
-MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION  =    @MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION@
 LIBS	   +=	$(MYSQL_LIB)
 
 #
diff --git a/NEWS b/NEWS
index 6541e33..9648cfa 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,213 @@
+= GDAL/OGR 1.11.1 Release Notes = 
+
+The 1.11.1 release is a bug fix release.
+
+== Build ==
+
+ * Fix compilation errors with json-c 0.12 (#5449)
+ * configure: fix for cpl_recode_iconv.cpp compilation error on freebsd 10 (#5452)
+ * Fix compilation error in alg/gdalgrid.cpp when AVX is available, but not SSE (#5566)
+ * Fix wrong include order in ingr and nitf subdirs w.r.t internal libtiff (#5644)
+ * Add CPL_UNUSED for gcc >= 4 (#5414)
+
+== Port ==
+
+ * CPLSpawn() on Windows: quote arguments with spaces in them (#5469)
+ * /vsigzip/: avoid infinite loop when reading broken .gml.gz file (#5486)
+ * /vsizip/: fix bug that caused premature end of file condition with some read patterns (#5530)
+ * /vsizip/: on >4GB zips: accept .zip declare 0 disks (#5615)
+ * Fix stack corruption upon thread termination with CPLSetThreadLocalConfigOption on Windows 32 bit (#5590, reported by cleo)
+ * cpl_http.cpp: truly set CURLOPT_NOSIGNAL if available (#5568)
+
+== GDAL Core ==
+
+ * EXIF reader: add missing validation for some data types (#3078)
+ * Fix segfault in GDALPamRasterBand::SerializeToXML() when saving an empty RAT (#5451)
+ * Windows plugin: complementary fix to #5211 to avoid error dialog box when there are dependency problems (#5525)
+ * RPC transformer with DEM: fix near interpolation (patch by liminlu0314, #5553)
+ * OpenCL warper: remove unused variable in bilinear resampling that can cause compilation error (#5518)
+ * GDALCreateTPSTransformer(): fix crash if the forward or backward transform cannot be computed (#5588)
+ * Overview: ignore alpha=0 values when compute an average overview of an alpha band; and also avoid memory errors when calling GetMaskBand()/GetMaskFlags() after overview computation if GetMaskXXX() has been called before (#5640)
+
+== Utilities ==
+
+ * gdal2tiles.py: fix inverted long/lat in BoundingBox and Origin elements of tilemapresource.xml (#5336)
+ * pct2rgb.py: make it work (again) with color tables with less than 256 entries (#5555)
+
+== GDAL drivers ==
+
+BAG driver:
+ * change nodata value for uncertainty band to 1e6; and do not expose wrong values of minimum and maximum of uncertainty band (#5482)
+
+DIMAP driver:
+ * DIMAP 2: handle the case where the Raster_Data element is in main file; fix to extract geodetic SRS; fix to extract geotransform from JPEG2000 file if not available in XML (#5018, #4826)
+
+ENVI driver:
+ * avoid generating potentially corrupted .hdr files when opening in update mode; Write 'Arbitrary' instead of 'Unknown' as the projection name for an undefined SRS; when writing, consider that LOCAL_CS SRS is like ungeoreferenced (#5467)
+
+ERS driver:
+ * reset RasterInfo.RegistrationCellX/Y if setting a new geotransform on an updated .ers file (#5493)
+
+MBTILES driver:
+ * better detection of 4 bands dataset (if sample tile is a paletted PNG with transparency) (#5439)
+ * take into account alpha component of color table in RasterIO() (#5439)
+ * avoid wrong detection of 3 bands when finding paletted PNG in /vsicurl mode (#5439)
+
+GIF driver:
+ * add compatibility with giflib 5.1 (#5519)
+
+GeoRaster driver:
+ * fix Oracle SRID authority (#5607)
+
+GRIB driver:
+ * avoid divide by zero while setting geotransform on 1xn or nx1 grib file (#5532)
+
+GTiff driver:
+ * Internal libtiff: fix segfault on invalid JPEG-in-TIFF (http://bugzilla.maptools.org/show_bug.cgi?id=2471)
+ * allow unsetting TIFFTAG_SOFTWARE, TIFFTAG_DOCUMENTNAME, etc... by removing them from metadata list or passing None as a value of SetMetadataItem() (#5619)
+ * fix to make band.SetMetadata({}) clear band metadata (#5628)
+
+HFA driver:
+ * fix recognition of Hotine Mercator Azimuth Center in Imagine format (and Swisstopo GeoTIFF) (#5551)
+
+JP2KAK driver:
+ * fix bug in vsil_target::end_rewrite() that prevented TLM index to be generated (#5585)
+
+JPIPKAK driver:
+ * avoid symbol collision with kdu_cpl_error_message from JP2KAK driver (#4865)
+
+MSG driver:
+ * fix compilation problem (#5479)
+
+NITF driver:
+ * HISTOA TRE: put definition of TRE in conformance with STDI-0002 (App L page 14) and STDI-0006 (Page 57) (#5572)
+
+OpenJPEG driver:
+ * fix warning when reading a single tile image whose dimensions are not a multiple of 1024 (#5480)
+
+OZI Map driver:
+ * retrieve the image filename in a case insensitive way (#5593)
+
+PDF driver:
+ * fix compilation problem with Podofo on Windows (#5469)
+
+PostGISRaster driver:
+ * Fix read of metadata for tables with multiple raster cols (#5529)
+
+VRT driver:
+ * make sure nodata value set on VRT raster band is taken into account in statistics computation (#5463)
+ * fix ComputeStatistics() on VRT that are a sub-window of source dataset (#5468)
+ * VRT raw: fix corrupted serialization on Windows (#5531)
+ * Implement heuristics to determine if GetMinimum()/GetMaximum() should use the implementation of their sources of not. Can be overriden by setting VRT_MIN_MAX_FROM_SOURCES = YES/NO (#5444)
+
+WMS driver:
+ * fix to make GDAL_DEFAULT_WMS_CACHE_PATH configuration option work as expected (#4540)
+
+XYZ driver:
+ * fix back line seeking with datasets that have not the same number of values per lines (#5488)
+ * report correct values of min/max for GDT_Float32 bands (#5492)
+
+== OGR core ==
+
+ * Fix OGRFeature::SetGeometryDirectly() and SetGeomFieldDirectly() to free the passed geometry even if the method fails (#5623)
+ * OGRLayerDecorator: remove return statements from void methods (#5618)
+ * OSR proj.4 import: for HOM, make sure +no_off/no_uoff is preserved, and change default value of gamma parameter to be the same as alpha (#5511)
+
+== OGR utilities ==
+
+ * ogr2ogr: fix problem with SRS when copying layers with multiple geometry columns with different SRS (#5546)
+ * ogr2ogr: turn string value to one element list if destination field is stringlist
+
+== OGR drivers ==
+
+CSV driver:
+ * fix to avoid truncation of WKT geometries to 8000 characters (#5508)
+
+FileGDB:
+ * use LatestWKID when available, and turn importFromEPSG() errors into warning (#5638)
+
+GeoJSON driver:
+ * accept and skip UTF-8 BOM (#5630)
+
+GME driver:
+ * Merged SetSpatialFilter fix
+
+GML driver:
+ * fix bug that prevented multiple instanciation of the reader with Xerces backend (#5571)
+ * update GFS files for RUIAN (#5610)
+
+GPKG driver:
+ * fix crash on ogr2ogr -f GPKG with non-spatial layer (#5445)
+ * fix GetExtent() crash on layers without extent set in gpkg_contents (#5471)
+ * put correct value (1) in gpkg_geometry_columns for 2.5D tables (#5481)
+ * fix component geometry type of GPKG 3D MultiGeometries (#5629)
+
+IDRISI driver:
+ * fix support for multi-ring polygons (#5544)
+
+VFK driver:
+ * change default DB filename
+
+MapInfo File driver:
+ * MIF: Remove duplicate OLCSequentialWrite test and report OLCCreateField (#5477)
+ * MIF: don't write field width for integer fields in .mif, which is incompatible with MapInfo (#3853)
+ * MIF: close polygon rings when reading Region from MIF file (#5614)
+
+MSSQL driver:
+ * Fix schema handling (#5401)
+ * Fix spatial geometry field handling (#5474)
+
+MySQL driver:
+ * thread-safe initialization of mysql client library (#5528)
+
+NAS driver:
+ * implement wfs:update (adds new context 'update' and fields "endet" and
+  "anlass" to "delete" layer).
+ * also assign xlink:href attributes as layer attribute, not only
+   in "alkis_beziehungen" layer; (#5372)
+
+OCI driver:
+ * fix memory leaks (#5599)
+ * fix creation of DATE fields (#5600)
+ * fix creation of columns whose name length is longer than 30 characters (#5466)
+
+OpenFileGDB driver:
+ * fix occasionnal write-after-end-of-buffer (#5464)
+ * fix spatial filter with GeneralPolygon shapes (#5591)
+ * add compatibility with .gdbtable files bigger than 4 GB (#5615)
+ * remove not really justified check in .gdbtablx that prevents legit GDB to be read (#5635)
+ * fix for reading GDB with string fields with a default value length > 127 (#5636)
+ * support opening files with ConfigurationKeyword=MAX_FILE_SIZE_4GB or MAX_FILE_SIZE_256TB (#5615)
+ * use LatestWKID when available, and turn importFromEPSG() errors into warning (#5638)
+ * increase accepted size for field description zone up to 10 MB (#5660)
+
+OSM driver:
+ * fix random crash, particularly on MacOSX (#5465)
+
+PG driver:
+ * fix crash when writing a StringList with 0 element (#5655, derived from patch by rtorre)
+
+PGDump driver:
+ * fix crash when writing a StringList with 0 element (#5655, derived from patch by rtorre)
+
+Shapefile driver:
+ * fix writing values up to 2^53 in OFTReal fields with 0 decimal places (#5625)
+
+TIGER driver:
+ * Fix potential buffer underflow when providing /vsistdin/ to Tiger driver (#5567)
+
+VFK driver:
+ * recode also header values (#5631)
+ * process DKATUZE from header properly (#5633)
+
+== SWIG Language Bindings ==
+
+Java bindings:
+ * Pass eRWFlag to allow both reading or writing (#5506).  Write was broken in DatasetRasterIO().
+
+Perl bindings:
+ * Fix schema corruption when 'Index' is a field (#5662)
+
 = GDAL/OGR 1.11.0 Release Notes (r25919 to r27200) =
 
 == In a nutshell... ==
diff --git a/VERSION b/VERSION
index 1cac385..720c738 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.11.0
+1.11.1
diff --git a/alg/gdal_crs.c b/alg/gdal_crs.c
index 58e5d0e..f75a55c 100644
--- a/alg/gdal_crs.c
+++ b/alg/gdal_crs.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_crs.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdal_crs.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Mapinfo Image Warper
  * Purpose:  Implemention of the GDALTransformer wrapper around CRS.C functions
@@ -58,7 +58,7 @@
 #include "cpl_minixml.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: gdal_crs.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdal_crs.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 /* Hum, we cannot include gdal_priv.h from a .c file... */
 CPL_C_START
@@ -326,7 +326,7 @@ void GDALDestroyGCPTransformer( void *pTransformArg )
 
 int GDALGCPTransform( void *pTransformArg, int bDstToSrc, 
                       int nPointCount, 
-                      double *x, double *y, double *z, 
+                      double *x, double *y, CPL_UNUSED double *z, 
                       int *panSuccess )
 
 {
diff --git a/alg/gdal_rpc.cpp b/alg/gdal_rpc.cpp
index 81e159b..79f386e 100644
--- a/alg/gdal_rpc.cpp
+++ b/alg/gdal_rpc.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_rpc.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdal_rpc.cpp 27486 2014-07-01 17:30:04Z rouault $
  *
  * Project:  Image Warper
  * Purpose:  Implements a rational polynomail (RPC) based transformer. 
@@ -33,7 +33,7 @@
 #include "ogr_spatialref.h"
 #include "cpl_minixml.h"
 
-CPL_CVSID("$Id: gdal_rpc.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdal_rpc.cpp 27486 2014-07-01 17:30:04Z rouault $");
 
 CPL_C_START
 CPLXMLNode *GDALSerializeRPCTransformer( void *pTransformArg );
@@ -768,14 +768,14 @@ int GDALRPCTransform( void *pTransformArg, int bDstToSrc,
                 }
                 else
                 {
-                    if (!(dX >= 0 && dY >= 0 && dX <= nRasterXSize && dY <= nRasterYSize))
+                    if (!(dX >= 0 && dY >= 0 && dX < nRasterXSize && dY < nRasterYSize))
                     {
                         panSuccess[i] = FALSE;
                         continue;
                     }
                     CPLErr eErr = psTransform->poDS->RasterIO(GF_Read, dX, dY, 1, 1,
                                                               &dfDEMH, 1, 1,
-                                                              GDT_Int32, 1, bands, 0, 0, 0);
+                                                              GDT_Float64, 1, bands, 0, 0, 0);
                     if(eErr != CE_None)
                     {
                         panSuccess[i] = FALSE;
@@ -903,14 +903,14 @@ int GDALRPCTransform( void *pTransformArg, int bDstToSrc,
             }
             else
             {
-                if (!(dX >= 0 && dY >= 0 && dX <= nRasterXSize && dY <= nRasterYSize))
+                if (!(dX >= 0 && dY >= 0 && dX < nRasterXSize && dY < nRasterYSize))
                 {
                     panSuccess[i] = FALSE;
                     continue;
                 }
                 CPLErr eErr = psTransform->poDS->RasterIO(GF_Read, dX, dY, 1, 1,
                                                           &dfDEMH, 1, 1,
-                                                          GDT_Int32, 1, bands, 0, 0, 0);
+                                                          GDT_Float64, 1, bands, 0, 0, 0);
                 if(eErr != CE_None)
                 {
                     panSuccess[i] = FALSE;
diff --git a/alg/gdal_tps.cpp b/alg/gdal_tps.cpp
index 536d67a..c225852 100644
--- a/alg/gdal_tps.cpp
+++ b/alg/gdal_tps.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_tps.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdal_tps.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  High Performance Image Reprojector
  * Purpose:  Thin Plate Spline transformer (GDAL wrapper portion)
@@ -37,7 +37,7 @@
 #include "cpl_atomic_ops.h"
 #include "cpl_multiproc.h"
 
-CPL_CVSID("$Id: gdal_tps.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdal_tps.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 CPLXMLNode *GDALSerializeTPSTransformer( void *pTransformArg );
@@ -206,7 +206,7 @@ void *GDALCreateTPSTransformerInt( int nGCPCount, const GDAL_GCP *pasGCPList,
 
     if( !psInfo->bForwardSolved || !psInfo->bReverseSolved )
     {
-        delete psInfo;
+        GDALDestroyTPSTransformer(psInfo);
         return NULL;
     }
 
@@ -273,7 +273,7 @@ void GDALDestroyTPSTransformer( void *pTransformArg )
 
 int GDALTPSTransform( void *pTransformArg, int bDstToSrc, 
                       int nPointCount, 
-                      double *x, double *y, double *z, 
+                      double *x, double *y, CPL_UNUSED double *z,
                       int *panSuccess )
 
 {
diff --git a/alg/gdalcutline.cpp b/alg/gdalcutline.cpp
index 0545f7b..7984aab 100644
--- a/alg/gdalcutline.cpp
+++ b/alg/gdalcutline.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalcutline.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalcutline.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  High Performance Image Reprojector
  * Purpose:  Implement cutline/blend mask generator.
@@ -35,7 +35,7 @@
 #include "ogr_geometry.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: gdalcutline.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalcutline.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         BlendMaskGenerator()                         */
@@ -229,13 +229,12 @@ BlendMaskGenerator( int nXOff, int nYOff, int nXSize, int nYSize,
 
 static int CutlineTransformer( void *pTransformArg, int bDstToSrc, 
                                int nPointCount, 
-                               double *x, double *y, double *z, 
-                               int *panSuccess )
+                               double *x, double *y, CPL_UNUSED double *z, 
+                               CPL_UNUSED int *panSuccess )
 
 {
     int nXOff = ((int *) pTransformArg)[0];
     int nYOff = ((int *) pTransformArg)[1];				
-    int i;
 
     if( bDstToSrc )
     {
@@ -243,7 +242,7 @@ static int CutlineTransformer( void *pTransformArg, int bDstToSrc,
         nYOff *= -1;
     }
 
-    for( i = 0; i < nPointCount; i++ )
+    for( int i = 0; i < nPointCount; i++ )
     {
         x[i] -= nXOff;
         y[i] -= nYOff;
@@ -261,7 +260,7 @@ static int CutlineTransformer( void *pTransformArg, int bDstToSrc,
 /************************************************************************/
 
 CPLErr 
-GDALWarpCutlineMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType,
+GDALWarpCutlineMasker( void *pMaskFuncArg, CPL_UNUSED int nBandCount, CPL_UNUSED GDALDataType eType,
                        int nXOff, int nYOff, int nXSize, int nYSize,
                        GByte ** /*ppImageData */,
                        int bMaskIsFloat, void *pValidityMask )
diff --git a/alg/gdalgeoloc.cpp b/alg/gdalgeoloc.cpp
index 7f88e05..e5e0c9d 100644
--- a/alg/gdalgeoloc.cpp
+++ b/alg/gdalgeoloc.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalgeoloc.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalgeoloc.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Implements Geolocation array based transformer.
@@ -38,7 +38,7 @@ SHPHandle hSHP = NULL;
 DBFHandle hDBF = NULL;
 #endif
 
-CPL_CVSID("$Id: gdalgeoloc.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalgeoloc.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 CPLXMLNode *GDALSerializeGeoLocTransformer( void *pTransformArg );
@@ -896,7 +896,7 @@ void GDALDestroyGeoLocTransformer( void *pTransformAlg )
 
 int GDALGeoLocTransform( void *pTransformArg, int bDstToSrc, 
                          int nPointCount, 
-                         double *padfX, double *padfY, double *padfZ,
+                         double *padfX, double *padfY, CPL_UNUSED double *padfZ,
                          int *panSuccess )
 
 {
diff --git a/alg/gdalgrid.cpp b/alg/gdalgrid.cpp
index af4e976..0e2642d 100644
--- a/alg/gdalgrid.cpp
+++ b/alg/gdalgrid.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalgrid.cpp 27110 2014-03-28 21:29:20Z rouault $
+ * $Id: gdalgrid.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL Gridding API.
  * Purpose:  Implementation of GDAL scattered data gridder.
@@ -40,7 +40,7 @@
 #include <xmmintrin.h>
 #endif
 
-CPL_CVSID("$Id: gdalgrid.cpp 27110 2014-03-28 21:29:20Z rouault $");
+CPL_CVSID("$Id: gdalgrid.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define TO_RADIANS (3.14159265358979323846 / 180.0)
 
@@ -193,7 +193,7 @@ GDALGridInverseDistanceToAPower( const void *poOptions, GUInt32 nPoints,
                                  const double *padfZ,
                                  double dfXPoint, double dfYPoint,
                                  double *pdfValue,
-                                 void* hExtraParamsIn )
+                                 CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -301,7 +301,7 @@ GDALGridInverseDistanceToAPowerNoSearch( const void *poOptions, GUInt32 nPoints,
                                          const double *padfZ,
                                          double dfXPoint, double dfYPoint,
                                          double *pdfValue,
-                                         void* hExtraParamsIn )
+                                         CPL_UNUSED void* hExtraParamsIn )
 {
     const double    dfPowerDiv2 =
         ((GDALGridInverseDistanceToAPowerOptions *)poOptions)->dfPower / 2;
@@ -403,9 +403,9 @@ static CPLErr
 GDALGridInverseDistanceToAPower2NoSmoothingNoSearchSSE(
                                         const void *poOptions,
                                         GUInt32 nPoints,
-                                        const double *unused_padfX,
-                                        const double *unused_padfY,
-                                        const double *unused_padfZ,
+                                        CPL_UNUSED const double *unused_padfX,
+                                        CPL_UNUSED const double *unused_padfY,
+                                        CPL_UNUSED const double *unused_padfZ,
                                         double dfXPoint, double dfYPoint,
                                         double *pdfValue,
                                         void* hExtraParamsIn )
@@ -581,7 +581,7 @@ GDALGridMovingAverage( const void *poOptions, GUInt32 nPoints,
                        const double *padfX, const double *padfY,
                        const double *padfZ,
                        double dfXPoint, double dfYPoint, double *pdfValue,
-                       void* hExtraParamsIn )
+                       CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -835,7 +835,7 @@ GDALGridDataMetricMinimum( const void *poOptions, GUInt32 nPoints,
                            const double *padfX, const double *padfY,
                            const double *padfZ,
                            double dfXPoint, double dfYPoint, double *pdfValue,
-                           void* hExtraParamsIn )
+                           CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -947,7 +947,7 @@ GDALGridDataMetricMaximum( const void *poOptions, GUInt32 nPoints,
                            const double *padfX, const double *padfY,
                            const double *padfZ,
                            double dfXPoint, double dfYPoint, double *pdfValue,
-                           void* hExtraParamsIn )
+                           CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -1060,7 +1060,7 @@ GDALGridDataMetricRange( const void *poOptions, GUInt32 nPoints,
                          const double *padfX, const double *padfY,
                          const double *padfZ,
                          double dfXPoint, double dfYPoint, double *pdfValue,
-                         void* hExtraParamsIn )
+                         CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -1170,9 +1170,9 @@ GDALGridDataMetricRange( const void *poOptions, GUInt32 nPoints,
 CPLErr
 GDALGridDataMetricCount( const void *poOptions, GUInt32 nPoints,
                          const double *padfX, const double *padfY,
-                         const double *padfZ,
+                         CPL_UNUSED const double *padfZ,
                          double dfXPoint, double dfYPoint, double *pdfValue,
-                         void* hExtraParamsIn )
+                         CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -1273,10 +1273,10 @@ GDALGridDataMetricCount( const void *poOptions, GUInt32 nPoints,
 CPLErr
 GDALGridDataMetricAverageDistance( const void *poOptions, GUInt32 nPoints,
                                    const double *padfX, const double *padfY,
-                                   const double *padfZ,
+                                   CPL_UNUSED const double *padfZ,
                                    double dfXPoint, double dfYPoint,
                                    double *pdfValue,
-                                   void* hExtraParamsIn )
+                                   CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -1384,10 +1384,10 @@ GDALGridDataMetricAverageDistance( const void *poOptions, GUInt32 nPoints,
 CPLErr
 GDALGridDataMetricAverageDistancePts( const void *poOptions, GUInt32 nPoints,
                                       const double *padfX, const double *padfY,
-                                      const double *padfZ,
+                                      CPL_UNUSED const double *padfZ,
                                       double dfXPoint, double dfYPoint,
                                       double *pdfValue,
-                                      void* hExtraParamsIn )
+                                      CPL_UNUSED void* hExtraParamsIn )
 {
     // TODO: For optimization purposes pre-computed parameters should be moved
     // out of this routine to the calling function.
@@ -1766,14 +1766,14 @@ GDALGridCreate( GDALGridAlgorithm eAlgorithm, const void *poOptions,
                             pabyX = pabyY = pabyZ = NULL;
                         }
                     }
-                    else
 #endif
 
 #ifdef HAVE_SSE_AT_COMPILE_TIME
 
 #define ALIGN16(x)  (((char*)(x)) + ((16 - (((size_t)(x)) % 16)) % 16))
 
-                    if( CSLTestBoolean(CPLGetConfigOption("GDAL_USE_SSE", "YES")) &&
+                    if( pafXAligned == NULL &&
+                        CSLTestBoolean(CPLGetConfigOption("GDAL_USE_SSE", "YES")) &&
                         CPLHaveRuntimeSSE() )
                     {
                         pabyX = (float*)VSIMalloc(sizeof(float) * nPoints + 15);
diff --git a/alg/gdalgridavx.cpp b/alg/gdalgridavx.cpp
index c7a3b08..d67c685 100644
--- a/alg/gdalgridavx.cpp
+++ b/alg/gdalgridavx.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalgridavx.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalgridavx.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL Gridding API.
  * Purpose:  Implementation of GDAL scattered data gridder.
@@ -33,7 +33,7 @@
 #ifdef HAVE_AVX_AT_COMPILE_TIME
 #include <immintrin.h>
 
-CPL_CVSID("$Id: gdalgridavx.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalgridavx.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          CPLHaveRuntimeAVX()                         */
@@ -85,9 +85,9 @@ CPLErr
 GDALGridInverseDistanceToAPower2NoSmoothingNoSearchAVX(
                                         const void *poOptions,
                                         GUInt32 nPoints,
-                                        const double *unused_padfX,
-                                        const double *unused_padfY,
-                                        const double *unused_padfZ,
+                                        CPL_UNUSED const double *unused_padfX,
+                                        CPL_UNUSED const double *unused_padfY,
+                                        CPL_UNUSED const double *unused_padfZ,
                                         double dfXPoint, double dfYPoint,
                                         double *pdfValue,
                                         void* hExtraParamsIn )
diff --git a/alg/gdalsievefilter.cpp b/alg/gdalsievefilter.cpp
index 7abefe6..97d6a08 100644
--- a/alg/gdalsievefilter.cpp
+++ b/alg/gdalsievefilter.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalsievefilter.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalsievefilter.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Raster to Polygon Converter
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include <vector>
 
-CPL_CVSID("$Id: gdalsievefilter.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalsievefilter.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define GP_NODATA_MARKER -51502112
 #define MY_MAX_INT 2147483647
@@ -183,7 +183,7 @@ CPLErr CPL_STDCALL
 GDALSieveFilter( GDALRasterBandH hSrcBand, GDALRasterBandH hMaskBand,
                  GDALRasterBandH hDstBand,
                  int nSizeThreshold, int nConnectedness,
-                 char **papszOptions,
+                 CPL_UNUSED char **papszOptions,
                  GDALProgressFunc pfnProgress, 
                  void * pProgressArg )
 
diff --git a/alg/gdaltransformer.cpp b/alg/gdaltransformer.cpp
index 78d0c71..5c39ea5 100644
--- a/alg/gdaltransformer.cpp
+++ b/alg/gdaltransformer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdaltransformer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdaltransformer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Mapinfo Image Warper
  * Purpose:  Implementation of one or more GDALTrasformerFunc types, including
@@ -38,7 +38,7 @@
 #include "cpl_list.h"
 #include "cpl_multiproc.h"
 
-CPL_CVSID("$Id: gdaltransformer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdaltransformer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 CPL_C_START
 void *GDALDeserializeGCPTransformer( CPLXMLNode *psTree );
 void *GDALDeserializeTPSTransformer( CPLXMLNode *psTree );
@@ -168,7 +168,7 @@ GDALSuggestedWarpOutput( GDALDatasetH hSrcDS,
 
  static int GDALSuggestedWarpOutput2_MustAdjustForRightBorder(
                      GDALTransformerFunc pfnTransformer, void *pTransformArg,
-                     double* padfExtent, int nPixels, int nLines,
+                     double* padfExtent, CPL_UNUSED int nPixels, int nLines,
                      double dfPixelSizeX, double dfPixelSizeY)
  {
     int nSamplePoints;
@@ -230,7 +230,7 @@ GDALSuggestedWarpOutput( GDALDatasetH hSrcDS,
 
  static int GDALSuggestedWarpOutput2_MustAdjustForBottomBorder(
                      GDALTransformerFunc pfnTransformer, void *pTransformArg,
-                     double* padfExtent, int nPixels, int nLines,
+                     double* padfExtent, int nPixels, CPL_UNUSED int nLines,
                      double dfPixelSizeX, double dfPixelSizeY)
  {
     int nSamplePoints;
@@ -339,7 +339,7 @@ GDALSuggestedWarpOutput2( GDALDatasetH hSrcDS,
                           void *pTransformArg, 
                           double *padfGeoTransformOut, 
                           int *pnPixels, int *pnLines,
-                          double *padfExtent, int nOptions )
+                          double *padfExtent, CPL_UNUSED int nOptions )
 
 {
     VALIDATE_POINTER1( hSrcDS, "GDALSuggestedWarpOutput2", CE_Failure );
@@ -348,8 +348,8 @@ GDALSuggestedWarpOutput2( GDALDatasetH hSrcDS,
 /*      Setup sample points all around the edge of the input raster.    */
 /* -------------------------------------------------------------------- */
     int    nSamplePoints = 0;
-    int    nInXSize = GDALGetRasterXSize( hSrcDS );
-    int    nInYSize = GDALGetRasterYSize( hSrcDS );
+    const int    nInXSize = GDALGetRasterXSize( hSrcDS );
+    const int    nInYSize = GDALGetRasterYSize( hSrcDS );
 
     if (pfnTransformer == GDALGenImgProjTransform)
     {
@@ -921,7 +921,7 @@ void* GDALCloneGenImgProjTransformer( void *hTransformArg )
 void *
 GDALCreateGenImgProjTransformer( GDALDatasetH hSrcDS, const char *pszSrcWKT,
                                  GDALDatasetH hDstDS, const char *pszDstWKT,
-                                 int bGCPUseOK, double dfGCPErrorThreshold,
+                                 int bGCPUseOK, CPL_UNUSED double dfGCPErrorThreshold,
                                  int nOrder )
 
 {
@@ -2877,7 +2877,7 @@ int CPL_STDCALL GDALInvGeoTransform( double *gt_in, double *gt_out )
 /*                      GDALSerializeTransformer()                      */
 /************************************************************************/
 
-CPLXMLNode *GDALSerializeTransformer( GDALTransformerFunc pfnFunc,
+CPLXMLNode *GDALSerializeTransformer( CPL_UNUSED GDALTransformerFunc pfnFunc,
                                       void *pTransformArg )
 
 {
diff --git a/alg/gdaltransformgeolocs.cpp b/alg/gdaltransformgeolocs.cpp
index f0fee41..48179b0 100644
--- a/alg/gdaltransformgeolocs.cpp
+++ b/alg/gdaltransformgeolocs.cpp
@@ -67,7 +67,7 @@ GDALTransformGeolocations( GDALRasterBandH hXBand,
                            void *pTransformArg, 
                            GDALProgressFunc pfnProgress, 
                            void *pProgressArg,
-                           char **papszOptions )
+                           CPL_UNUSED char **papszOptions )
 
 {
     VALIDATE_POINTER1( hXBand, "GDALTransformGeolocations", CE_Failure );
diff --git a/alg/gdalwarper.cpp b/alg/gdalwarper.cpp
index c789da5..f13f6b2 100644
--- a/alg/gdalwarper.cpp
+++ b/alg/gdalwarper.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwarper.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalwarper.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  High Performance Image Reprojector
  * Purpose:  Implementation of high level convenience APIs for warper.
@@ -34,7 +34,7 @@
 #include "ogr_api.h"
 #include "gdal_priv.h"
 
-CPL_CVSID("$Id: gdalwarper.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalwarper.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         GDALReprojectImage()                         */
@@ -77,7 +77,7 @@ CPLErr CPL_STDCALL
 GDALReprojectImage( GDALDatasetH hSrcDS, const char *pszSrcWKT, 
                     GDALDatasetH hDstDS, const char *pszDstWKT,
                     GDALResampleAlg eResampleAlg, 
-                    double dfWarpMemoryLimit, 
+                    CPL_UNUSED double dfWarpMemoryLimit, 
                     double dfMaxError,
                     GDALProgressFunc pfnProgress, void *pProgressArg, 
                     GDALWarpOptions *psOptions )
@@ -509,7 +509,7 @@ GDALWarpNoDataMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType,
 /************************************************************************/
 
 CPLErr 
-GDALWarpSrcAlphaMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType, 
+GDALWarpSrcAlphaMasker( void *pMaskFuncArg, CPL_UNUSED int nBandCount, CPL_UNUSED GDALDataType eType, 
                         int nXOff, int nYOff, int nXSize, int nYSize,
                         GByte ** /*ppImageData */,
                         int bMaskIsFloat, void *pValidityMask )
@@ -568,7 +568,7 @@ GDALWarpSrcAlphaMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType,
 /************************************************************************/
 
 CPLErr 
-GDALWarpSrcMaskMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType, 
+GDALWarpSrcMaskMasker( void *pMaskFuncArg, CPL_UNUSED int nBandCount, CPL_UNUSED GDALDataType eType, 
                        int nXOff, int nYOff, int nXSize, int nYSize,
                        GByte ** /*ppImageData */,
                        int bMaskIsFloat, void *pValidityMask )
@@ -659,7 +659,7 @@ GDALWarpSrcMaskMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType,
 /************************************************************************/
 
 CPLErr 
-GDALWarpDstAlphaMasker( void *pMaskFuncArg, int nBandCount, GDALDataType eType,
+GDALWarpDstAlphaMasker( void *pMaskFuncArg, int nBandCount, CPL_UNUSED GDALDataType eType,
                         int nXOff, int nYOff, int nXSize, int nYSize,
                         GByte ** /*ppImageData */,
                         int bMaskIsFloat, void *pValidityMask )
diff --git a/alg/gdalwarper.h b/alg/gdalwarper.h
index 1fb5f3e..9531fc3 100644
--- a/alg/gdalwarper.h
+++ b/alg/gdalwarper.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwarper.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalwarper.h 27701 2014-09-20 15:07:02Z goatbar $
  *
  * Project:  GDAL High Performance Warper
  * Purpose:  Prototypes, and definitions for warping related work.
@@ -338,8 +338,9 @@ private:
     CPLErr          CreateKernelMask( GDALWarpKernel *, int iBand, 
                                       const char *pszType );
 
-    void            *unused1;
-    void            *unused2;
+    /* Unused kept to preserve binary ABI */
+    CPL_UNUSED void            *unused1;
+    CPL_UNUSED void            *unused2;
     void            *hIOMutex;
     void            *hWarpMutex;
 
diff --git a/alg/gdalwarpkernel_opencl.c b/alg/gdalwarpkernel_opencl.c
index ad5dc1a..3bb4204 100644
--- a/alg/gdalwarpkernel_opencl.c
+++ b/alg/gdalwarpkernel_opencl.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwarpkernel_opencl.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalwarpkernel_opencl.c 27455 2014-06-15 10:54:41Z rouault $
  *
  * Project:  OpenCL Image Reprojector
  * Purpose:  Implementation of the GDALWarpKernel reprojector in OpenCL.
@@ -41,7 +41,7 @@
 #include "cpl_string.h"
 #include "gdalwarpkernel_opencl.h"
 
-CPL_CVSID("$Id: gdalwarpkernel_opencl.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalwarpkernel_opencl.c 27455 2014-06-15 10:54:41Z rouault $");
 
 #define handleErr(err) if((err) != CL_SUCCESS) { \
     CPLError(CE_Failure, CPLE_AppDefined, "Error at file %s line %d: %s", __FILE__, __LINE__, getCLErrorString(err)); \
@@ -836,7 +836,6 @@ cl_kernel get_kernel(struct oclWarper *warper, char useVec,
                     "__global int *nDstValid,\n"
                     "const int bandNum)\n"
 "{\n"
-    "int i;\n"
     "float2  fSrc = getSrcCoords(srcCoords);\n"
     "if (!isValid(fUnifiedSrcDensity, nUnifiedSrcValid, fSrc))\n"
         "return;\n"
diff --git a/alg/llrasterize.cpp b/alg/llrasterize.cpp
index 258fc40..1ac1352 100644
--- a/alg/llrasterize.cpp
+++ b/alg/llrasterize.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: llrasterize.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: llrasterize.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Vector polygon rasterization code.
@@ -254,13 +254,11 @@ No known bug
 /************************************************************************/
 
 void GDALdllImagePoint( int nRasterXSize, int nRasterYSize, 
-                        int nPartCount, int *panPartSize,
+                        int nPartCount, CPL_UNUSED int *panPartSize,
                         double *padfX, double *padfY, double *padfVariant,
                         llPointFunc pfnPointFunc, void *pCBData )
 {
-    int     i;
- 
-    for ( i = 0; i < nPartCount; i++ )
+    for ( int i = 0; i < nPartCount; i++ )
     {
         int nX = (int)floor( padfX[i] );
         int nY = (int)floor( padfY[i] );
diff --git a/alg/rasterfill.cpp b/alg/rasterfill.cpp
index 609b9fd..951d7ab 100644
--- a/alg/rasterfill.cpp
+++ b/alg/rasterfill.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: rasterfill.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: rasterfill.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Interpolate in nodata areas.
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: rasterfill.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: rasterfill.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           GDALFilterLine()                           */
@@ -389,9 +389,9 @@ CPLErr CPL_STDCALL
 GDALFillNodata( GDALRasterBandH hTargetBand, 
                 GDALRasterBandH hMaskBand,
                 double dfMaxSearchDist, 
-                int bDeprecatedOption,
+                CPL_UNUSED int bDeprecatedOption,
                 int nSmoothingIterations,
-                char **papszOptions,
+                CPL_UNUSED char **papszOptions,
                 GDALProgressFunc pfnProgress, 
                 void * pProgressArg )
 
diff --git a/apps/gdaldem.cpp b/apps/gdaldem.cpp
index 4d70825..86c0dd3 100644
--- a/apps/gdaldem.cpp
+++ b/apps/gdaldem.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdaldem.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdaldem.cpp 27613 2014-08-30 15:55:30Z rouault $
  *
  * Project:  GDAL DEM Utilities
  * Purpose:  
@@ -91,7 +91,7 @@
 #include "gdal_priv.h"
 #include "commonutils.h"
 
-CPL_CVSID("$Id: gdaldem.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdaldem.cpp 27613 2014-08-30 15:55:30Z rouault $");
 
 #ifndef M_PI
 # define M_PI  3.1415926535897932384626433832795
diff --git a/apps/ogr2ogr.cpp b/apps/ogr2ogr.cpp
index 9271fae..2973435 100644
--- a/apps/ogr2ogr.cpp
+++ b/apps/ogr2ogr.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr2ogr.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr2ogr.cpp 27475 2014-06-28 13:16:46Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Simple client for translating between formats.
@@ -39,7 +39,7 @@
 #include <map>
 #include <vector>
 
-CPL_CVSID("$Id: ogr2ogr.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogr2ogr.cpp 27475 2014-06-28 13:16:46Z rouault $");
 
 static int bSkipFailures = FALSE;
 static int nGroupTransactions = 20000;
@@ -2484,7 +2484,7 @@ static TargetLayerInfo* SetupTargetLayer( OGRDataSource *poSrcDS,
                                                 OGRDataSource *poDstDS,
                                                 char **papszLCO,
                                                 const char *pszNewLayerName,
-                                                OGRSpatialReference *poOutputSRS,
+                                                OGRSpatialReference *poOutputSRSIn,
                                                 int bNullifyOutputSRS,
                                                 char **papszSelFields,
                                                 int bAppend, int bAddMissingFields, int eGType,
@@ -2554,6 +2554,7 @@ static TargetLayerInfo* SetupTargetLayer( OGRDataSource *poSrcDS,
         }
     }
 
+    OGRSpatialReference* poOutputSRS = poOutputSRSIn;
     if( poOutputSRS == NULL && !bNullifyOutputSRS )
     {
         if( nSrcGeomFieldCount == 1 || anRequestedGeomFields.size() == 0 )
@@ -2715,8 +2716,8 @@ static TargetLayerInfo* SetupTargetLayer( OGRDataSource *poSrcDS,
                 int iSrcGeomField = anRequestedGeomFields[i];
                 OGRGeomFieldDefn oGFldDefn
                     (poSrcFDefn->GetGeomFieldDefn(iSrcGeomField));
-                if( poOutputSRS != NULL )
-                    oGFldDefn.SetSpatialRef(poOutputSRS);
+                if( poOutputSRSIn != NULL )
+                    oGFldDefn.SetSpatialRef(poOutputSRSIn);
                 if( bForceGType )
                     oGFldDefn.SetType((OGRwkbGeometryType) eGType);
                 else
diff --git a/configure b/configure
index 1bcff74..ec031b0 100755
--- a/configure
+++ b/configure
@@ -723,7 +723,6 @@ INGRES_INC
 INGRES_LIB
 II_SYSTEM
 HAVE_INGRES
-MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION
 MYSQL_LIB
 MYSQL_INC
 HAVE_MYSQL
@@ -18960,7 +18959,7 @@ _ACEOF
 if test "$am_func_iconv" = "yes"; then
     rm -f testiconv.*
     echo '#include <iconv.h>' > testiconv.cpp
-    echo 'int main(int argc, char** argv) { iconv_t cd; return iconv (cd, (const char **) 0, 0, 0, 0); } ' >> testiconv.cpp
+    echo 'int main(int argc, char** argv) { iconv_t cd = 0; return iconv (cd, (const char **) 0, 0, 0, 0); } ' >> testiconv.cpp
     if test -z "`${CXX} ${CPPFLAGS} testiconv.cpp -c 2>&1`" ; then
         { $as_echo "$as_me:${as_lineno-$LINENO}: result: using ICONV_CPP_CONST=\"const\"" >&5
 $as_echo "using ICONV_CPP_CONST=\"const\"" >&6; }
@@ -23338,33 +23337,6 @@ $as_echo "no, mysql is pre-4.x" >&6; }
       { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
 
-      # Check if mysql headers declare load_defaults
-      { $as_echo "$as_me:${as_lineno-$LINENO}: checking load_defaults() in MySQL" >&5
-$as_echo_n "checking load_defaults() in MySQL... " >&6; }
-      rm -f testmysql.*
-      echo '#include "my_global.h"' > testmysql.cpp
-      echo '#include "my_sys.h"' >> testmysql.cpp
-      echo 'int main(int argc, char** argv) { load_defaults(0, 0, 0, 0); return 0; } ' >> testmysql.cpp
-      if test -z "`${CXX} ${CXXFLAGS} ${MYSQL_INC} -o testmysql testmysql.cpp ${MYSQL_LIB} 2>&1`" ; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, found in my_sys.h" >&5
-$as_echo "yes, found in my_sys.h" >&6; }
-      else
-        echo 'extern "C" void load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv);' > testmysql.cpp
-        echo 'int main(int argc, char** argv) { load_defaults(0, 0, 0, 0); return 0; } ' >> testmysql.cpp
-        if test -z "`${CXX} ${CXXFLAGS} ${MYSQL_INC} -o testmysql testmysql.cpp ${MYSQL_LIB} 2>&1`" ; then
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, found in library but not in header" >&5
-$as_echo "yes, found in library but not in header" >&6; }
-            MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION=yes
-        else
-            HAVE_MYSQL=no
-            MYSQL_LIB=
-            MYSQL_INC=
-            as_fn_error $? "Cannot find load_defaults()" "$LINENO" 5
-        fi
-      fi
-      rm -f testmysql.*
-      rm -f testmysql
-
 	;;
   esac
 fi
@@ -23375,8 +23347,6 @@ MYSQL_INC=$MYSQL_INC
 
 MYSQL_LIB=$MYSQL_LIB
 
-MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION=$MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION
-
 
 
 
diff --git a/configure.in b/configure.in
index dfd94c4..a0cf595 100644
--- a/configure.in
+++ b/configure.in
@@ -1,5 +1,5 @@
 dnl ***************************************************************************
-dnl $Id: configure.in 26958 2014-02-17 18:24:07Z rouault $
+dnl $Id: configure.in 27506 2014-07-07 19:49:05Z rouault $
 dnl
 dnl Project:  GDAL
 dnl Purpose:  Configure source file.
@@ -597,7 +597,7 @@ dnl ICONV_CONST when used from .cpp files.
 if test "$am_func_iconv" = "yes"; then
     rm -f testiconv.*
     echo '#include <iconv.h>' > testiconv.cpp
-    echo 'int main(int argc, char** argv) { iconv_t cd; return iconv (cd, (const char **) 0, 0, 0, 0); } ' >> testiconv.cpp
+    echo 'int main(int argc, char** argv) { iconv_t cd = 0; return iconv (cd, (const char **) 0, 0, 0, 0); } ' >> testiconv.cpp
     if test -z "`${CXX} ${CPPFLAGS} testiconv.cpp -c 2>&1`" ; then
         AC_MSG_RESULT([using ICONV_CPP_CONST="const"])
         ICONV_CPP_CONST="const"
@@ -2488,30 +2488,6 @@ else
       MYSQL_INC="`$MYSQL_CONFIG --include`"
       AC_MSG_RESULT([yes])
 
-      # Check if mysql headers declare load_defaults
-      AC_MSG_CHECKING([load_defaults() in MySQL])
-      rm -f testmysql.*
-      echo '#include "my_global.h"' > testmysql.cpp
-      echo '#include "my_sys.h"' >> testmysql.cpp
-      echo 'int main(int argc, char** argv) { load_defaults(0, 0, 0, 0); return 0; } ' >> testmysql.cpp
-      if test -z "`${CXX} ${CXXFLAGS} ${MYSQL_INC} -o testmysql testmysql.cpp ${MYSQL_LIB} 2>&1`" ; then
-        AC_MSG_RESULT([yes, found in my_sys.h])
-      else
-        echo 'extern "C" void load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv);' > testmysql.cpp
-        echo 'int main(int argc, char** argv) { load_defaults(0, 0, 0, 0); return 0; } ' >> testmysql.cpp
-        if test -z "`${CXX} ${CXXFLAGS} ${MYSQL_INC} -o testmysql testmysql.cpp ${MYSQL_LIB} 2>&1`" ; then
-            AC_MSG_RESULT([yes, found in library but not in header])
-            MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION=yes
-        else
-            HAVE_MYSQL=no
-            MYSQL_LIB=
-            MYSQL_INC=
-            AC_MSG_ERROR([Cannot find load_defaults()])
-        fi
-      fi
-      rm -f testmysql.*
-      rm -f testmysql
-
 	;;
   esac
 fi
@@ -2519,7 +2495,6 @@ fi
 AC_SUBST(HAVE_MYSQL,$HAVE_MYSQL)
 AC_SUBST(MYSQL_INC,$MYSQL_INC)
 AC_SUBST(MYSQL_LIB,$MYSQL_LIB)
-AC_SUBST(MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION,$MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION)
 
 dnl ---------------------------------------------------------------------------
 dnl INGRES support.
diff --git a/data/nitf_spec.xml b/data/nitf_spec.xml
index 20113fe..5f7d129 100644
--- a/data/nitf_spec.xml
+++ b/data/nitf_spec.xml
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!--
 /******************************************************************************
- * $Id: nitf_spec.xml 24212 2012-04-08 18:41:59Z rouault $
+ * $Id: nitf_spec.xml 27536 2014-07-16 08:01:29Z rouault $
  *
  * Project:  NITF Library
  * Purpose:  Description of NITF TREs
@@ -290,12 +290,12 @@
             <if cond="ROT_FLAG=1">
                 <field name="ROT_ANGLE" length="8"/>
             </if>
-            <field name="PROJ_FLAG" length="1"/>
             <field name="ASYM_FLAG" length="1"/>
             <if cond="ASYM_FLAG=1">
                 <field name="ZOOMROW" length="7"/>
                 <field name="ZOOMCOL" length="7"/>
             </if>
+            <field name="PROJ_FLAG" length="1"/>
             <field name="SHARP_FLAG" length="1"/>
             <if cond="SHARP_FLAG=1">
                 <field name="SHARPFAM" length="2"/>
diff --git a/data/ruian_vf_ob_v1.gfs b/data/ruian_vf_ob_v1.gfs
index 6747123..bebc746 100644
--- a/data/ruian_vf_ob_v1.gfs
+++ b/data/ruian_vf_ob_v1.gfs
@@ -78,14 +78,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -220,14 +226,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -336,21 +348,30 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID řízení v ISKN -->
     <PropertyDefn>
       <Name>RizeniId</Name>
       <ElementPath>RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -446,14 +467,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -491,7 +518,10 @@
     <PropertyDefn>
       <Name>Vymera</Name>
       <ElementPath>Vymera</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Převažující charakter využití ZSJ -->
@@ -556,14 +586,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -588,7 +624,10 @@
     <PropertyDefn>
       <Name>Id</Name>
       <ElementPath>Id</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Identifikátor nesprávnosti na prvku (?) -->
@@ -614,7 +653,10 @@
     <PropertyDefn>
       <Name>VymeraParcely</Name>
       <ElementPath>VymeraParcely</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Způsob využití pozemku -->
@@ -659,14 +701,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID řízení v ISKN -->
     <PropertyDefn>
       <Name>RizeniId</Name>
       <ElementPath>RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Bonitované díly parcely - výměra v metrech čtverečných -->
@@ -685,14 +733,20 @@
     <PropertyDefn>
       <Name>BonitovanyDilIdTranskace</Name>
       <ElementPath>BonitovaneDily|BonitovanyDil|IdTranskace</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>IntegerList</Type>
+      -->
+      <Type>StringList</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Bonitované díly parcely - ID řízení v ISKN -->
     <PropertyDefn>
       <Name>BonitovaneDilRizeniId</Name>
       <ElementPath>BonitovaneDily|BonitovanyDil|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>IntegerList</Type>
+      -->
+      <Type>StringList</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Způsob ochrany pozemku - kód ochrany -->
@@ -717,7 +771,10 @@
     <PropertyDefn>
       <Name>ZpusobOchranyRizeniId</Name>
       <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -762,7 +819,10 @@
     <PropertyDefn>
       <Name>IdentifikacniParcelaId</Name>
       <ElementPath>IdentifikacniParcela|Id</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Typ stavebního objektu -->
@@ -807,21 +867,30 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID budovy v ISKN -->
     <PropertyDefn>
       <Name>IsknBudovaId</Name>
       <ElementPath>IsknBudovaId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Datum dokončení stavebního objektu -->
@@ -919,7 +988,10 @@
     <PropertyDefn>
       <Name>ZpusobOchranyRizeniId</Name>
       <ElementPath>ZpusobyOchrany|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Detailní tecnicko-ekonomické atributy (TEA) (?) -->
@@ -1020,21 +1092,30 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID budovy v ISKN -->
     <PropertyDefn>
       <Name>IsknBudovaId</Name>
       <ElementPath>IsknBudovaId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
diff --git a/data/ruian_vf_st_v1.gfs b/data/ruian_vf_st_v1.gfs
index 648ccb2..368da78 100644
--- a/data/ruian_vf_st_v1.gfs
+++ b/data/ruian_vf_st_v1.gfs
@@ -1,6 +1,6 @@
 <GMLFeatureClassList>
+  <!-- Seznam států -->
   <GMLFeatureClass>
-    <!-- Seznam států -->
     <Name>Staty</Name>
     <ElementPath>Data|Staty|Stat</ElementPath>
     <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
@@ -60,14 +60,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změny v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -145,14 +151,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -230,14 +242,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -316,14 +334,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!--  ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -407,14 +431,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -498,14 +528,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -584,14 +620,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -674,14 +716,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -828,14 +876,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -900,14 +954,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -984,14 +1044,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Text popisující vlajku MOMC -->
@@ -1107,14 +1173,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1223,21 +1295,30 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID řízení v ISKN -->
     <PropertyDefn>
       <Name>RizeniId</Name>
       <ElementPath>RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1333,14 +1414,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1378,7 +1465,10 @@
     <PropertyDefn>
       <Name>Vymera</Name>
       <ElementPath>Vymera</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Převažující charakter využití ZSJ -->
diff --git a/data/ruian_vf_st_v1.gfs b/data/ruian_vf_v1.gfs
similarity index 63%
copy from data/ruian_vf_st_v1.gfs
copy to data/ruian_vf_v1.gfs
index 648ccb2..30655ed 100644
--- a/data/ruian_vf_st_v1.gfs
+++ b/data/ruian_vf_v1.gfs
@@ -1,6 +1,6 @@
 <GMLFeatureClassList>
+  <!-- Seznam států -->
   <GMLFeatureClass>
-    <!-- Seznam států -->
     <Name>Staty</Name>
     <ElementPath>Data|Staty|Stat</ElementPath>
     <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
@@ -60,14 +60,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změny v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -145,14 +151,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -230,14 +242,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -316,14 +334,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!--  ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -407,14 +431,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Kód územního celku v NUTS / LAU -->
@@ -498,14 +528,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -584,14 +620,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -674,14 +716,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -828,14 +876,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -900,14 +954,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
   </GMLFeatureClass>
@@ -984,14 +1044,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Text popisující vlajku MOMC -->
@@ -1107,14 +1173,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1223,21 +1295,30 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID řízení v ISKN -->
     <PropertyDefn>
       <Name>RizeniId</Name>
       <ElementPath>RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1333,14 +1414,20 @@
     <PropertyDefn>
       <Name>IdTransakce</Name>
       <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- ID návrhu změn v ISUI -->
     <PropertyDefn>
       <Name>GlobalniIdNavrhuZmeny</Name>
       <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Mluvnické charakteristiky 2 až 7 pád -->
@@ -1378,7 +1465,10 @@
     <PropertyDefn>
       <Name>Vymera</Name>
       <ElementPath>Vymera</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
       <Type>Integer</Type>
+      -->
+      <Type>String</Type>
       <Width>18</Width>
     </PropertyDefn>
     <!-- Převažující charakter využití ZSJ -->
@@ -1388,4 +1478,624 @@
       <Type>Integer</Type>
     </PropertyDefn>
   </GMLFeatureClass>
+  <!-- Ulice -->
+  <GMLFeatureClass>
+    <Name>Ulice</Name>
+    <ElementPath>Data|Ulice|Ulice</ElementPath>
+    <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
+    <!-- Geometrie definiční čáry ulice -->
+    <GeomPropertyDefn>
+      <Name>DefinicniCara</Name> 
+      <ElementPath>Geometrie|DefinicniCara</ElementPath> 
+      <Type>MultiLineString</Type>
+    </GeomPropertyDefn>
+    <!-- Kód ulice -->
+    <PropertyDefn>
+      <Name>Kod</Name>
+      <ElementPath>Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Název ulice -->
+    <PropertyDefn>
+      <Name>Nazev</Name>
+      <ElementPath>Nazev</ElementPath>
+      <Type>String</Type>
+      <Width>48</Width>
+    </PropertyDefn>
+    <!-- Identifikátor nesprávnosti na prvku (?) -->
+    <PropertyDefn>
+      <Name>Nespravny</Name>
+      <ElementPath>Nespravny</ElementPath>
+      <Type>String</Type>
+      <Width>5</Width>
+    </PropertyDefn>
+    <!-- Nadřazená obec -->
+    <PropertyDefn>
+      <Name>ObecKod</Name>
+      <ElementPath>Obec|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Začátek platnosti -->
+    <PropertyDefn>
+      <Name>PlatiOd</Name>
+      <ElementPath>PlatiOd</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- Konec platnosti -->
+    <PropertyDefn>
+      <Name>PlatiDo</Name>
+      <ElementPath>PlatiDo</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>IdTransakce</Name>
+      <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID návrhu změn v ISUI -->
+    <PropertyDefn>
+      <Name>GlobalniIdNavrhuZmeny</Name>
+      <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+  </GMLFeatureClass>
+  <!-- Parcely -->
+  <GMLFeatureClass>
+    <Name>Parcely</Name>
+    <ElementPath>Data|Parcely|Parcela</ElementPath>
+    <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
+    <!-- Geometrie definičního bodu parcely -->
+    <GeomPropertyDefn>
+      <Name>DefinicniBod</Name> 
+      <ElementPath>Geometrie|DefinicniBod</ElementPath> 
+      <Type>Point</Type>
+    </GeomPropertyDefn>
+    <!-- Originální geometrie hranice parcely ? -->
+    <GeomPropertyDefn>
+      <Name>OriginalniHranice</Name> 
+      <ElementPath>Geometrie|OriginalniHranice</ElementPath> 
+      <Type>Polygon</Type>
+    </GeomPropertyDefn>
+    <!-- Jednoznační identifikátor parcely -->
+    <PropertyDefn>
+      <Name>Id</Name>
+      <ElementPath>Id</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Identifikátor nesprávnosti na prvku (?) -->
+    <PropertyDefn>
+      <Name>Nespravny</Name>
+      <ElementPath>Nespravny</ElementPath>
+      <Type>String</Type>
+      <Width>5</Width>
+    </PropertyDefn>
+    <!-- Kmenové parcelní číslo -->
+    <PropertyDefn>
+      <Name>KmenoveCislo</Name>
+      <ElementPath>KmenoveCislo</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Poddělení čísla parcely -->
+    <PropertyDefn>
+      <Name>PododdeleniCisla</Name>
+      <ElementPath>PododdeleniCisla</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Výměra parcely -->
+    <PropertyDefn>
+      <Name>VymeraParcely</Name>
+      <ElementPath>VymeraParcely</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Způsob využití pozemku -->
+    <PropertyDefn>
+      <Name>ZpusobyVyuzitiPozemku</Name>
+      <ElementPath>ZpusobyVyuzitiPozemku</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Rozlišení druhu číslování parcely -->
+    <PropertyDefn>
+      <Name>DruhCislovaniKod</Name>
+      <ElementPath>DruhCislovaniKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Kód druhu pozemku -->
+    <PropertyDefn>
+      <Name>DruhPozemkuKod</Name>
+      <ElementPath>DruhPozemkuKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Nadřazené katastrální území -->
+    <PropertyDefn>
+      <Name>KatastralniUzemiKod</Name>
+      <ElementPath>KatastralniUzemi|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Začátek platnosti -->
+    <PropertyDefn>
+      <Name>PlatiOd</Name>
+      <ElementPath>PlatiOd</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- Konec platnosti -->
+    <PropertyDefn>
+      <Name>PlatiDo</Name>
+      <ElementPath>PlatiDo</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>IdTransakce</Name>
+      <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID řízení v ISKN -->
+    <PropertyDefn>
+      <Name>RizeniId</Name>
+      <ElementPath>RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Bonitované díly parcely - výměra v metrech čtverečných -->
+    <PropertyDefn>
+      <Name>BonitovanyDilVymera</Name>
+      <ElementPath>BonitovaneDily|BonitovanyDil|Vymera</ElementPath>
+      <Type>IntegerList</Type>
+    </PropertyDefn>
+    <!-- Kód bonitovaných půdně ekologických jednotek -->
+    <PropertyDefn>
+      <Name>BonitovanyDilBonitovanaJednotkaKod</Name>
+      <ElementPath>BonitovaneDily|BonitovanyDil|BonitovanaJednotkaKod</ElementPath>
+      <Type>IntegerList</Type>
+    </PropertyDefn>
+    <!-- Bonitované díly parcely - ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>BonitovanyDilIdTranskace</Name>
+      <ElementPath>BonitovaneDily|BonitovanyDil|IdTranskace</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>IntegerList</Type>
+      -->
+      <Type>StringList</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Bonitované díly parcely - ID řízení v ISKN -->
+    <PropertyDefn>
+      <Name>BonitovaneDilRizeniId</Name>
+      <ElementPath>BonitovaneDily|BonitovanyDil|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>IntegerList</Type>
+      -->
+      <Type>StringList</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Způsob ochrany pozemku - kód ochrany -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyKod</Name>
+      <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany pozemku - typ ochrany -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyTypOchranyKod</Name>
+      <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|TypOchranyKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+        <!-- Způsob ochrany pozemku - ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyIdTransakce</Name>
+      <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|IdTransakce</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany pozemku - ID řízení v ISKN -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyRizeniId</Name>
+      <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+  </GMLFeatureClass>
+  <!-- Stavební objekty -->
+  <GMLFeatureClass>
+    <Name>StavebniObjekty</Name>
+    <ElementPath>Data|StavebniObjekty|StavebniObjekt</ElementPath>
+    <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
+    <!-- Geometrie definičního bodu stavebního objektu -->
+    <GeomPropertyDefn>
+      <Name>DefinicniBod</Name> 
+      <ElementPath>Geometrie|DefinicniBod</ElementPath> 
+      <Type>Point</Type>
+    </GeomPropertyDefn>
+    <!-- Originální geometrie hranice stavebního objektu ? -->
+    <GeomPropertyDefn>
+      <Name>OriginalniHranice</Name> 
+      <ElementPath>Geometrie|OriginalniHranice</ElementPath> 
+      <Type>MultiPolygon</Type>
+    </GeomPropertyDefn>
+    <!-- Kód stavebního objektu -->
+    <PropertyDefn>
+      <Name>Kod</Name>
+      <ElementPath>Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Identifikátor nesprávnosti na prvku (?) -->
+    <PropertyDefn>
+      <Name>Nespravny</Name>
+      <ElementPath>Nespravny</ElementPath>
+      <Type>String</Type>
+      <Width>5</Width>
+    </PropertyDefn>
+    <!-- Seznam čísel domovních stavebního objektu -->
+    <PropertyDefn>
+      <Name>CisloDomovni</Name>
+      <ElementPath>CislaDomovni|CisloDomovni</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Jedna z parcel, na nichž je stavební objekt postaven, zvolená
+         pro identifikaci objektu (tzv. definiční parcela) -->
+    <PropertyDefn>
+      <Name>IdentifikacniParcelaId</Name>
+      <ElementPath>IdentifikacniParcela|Id</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Typ stavebního objektu -->
+    <PropertyDefn>
+      <Name>TypStavebnihoObjektuKod</Name>
+      <ElementPath>TypStavebnihoObjektuKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob využití -->
+    <PropertyDefn>
+      <Name>ZpusobVyuzitiKod</Name>
+      <ElementPath>ZpusobVyuzitiKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Nadřazená část obce -->
+    <PropertyDefn>
+      <Name>CastObceKod</Name>
+      <ElementPath>CastObce|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Nadřazený MOMC -->
+    <PropertyDefn>
+      <Name>MomcKod</Name>
+      <ElementPath>Momc|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Začátek platnosti -->
+    <PropertyDefn>
+      <Name>PlatiOd</Name>
+      <ElementPath>PlatiOd</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- Konec platnosti -->
+    <PropertyDefn>
+      <Name>PlatiDo</Name>
+      <ElementPath>PlatiDo</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>IdTransakce</Name>
+      <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID návrhu změn v ISUI -->
+    <PropertyDefn>
+      <Name>GlobalniIdNavrhuZmeny</Name>
+      <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID budovy v ISKN -->
+    <PropertyDefn>
+      <Name>IsknBudovaId</Name>
+      <ElementPath>IsknBudovaId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Datum dokončení stavebního objektu -->
+    <PropertyDefn>
+      <Name>Dokonceni</Name>
+      <ElementPath>Dokonceni</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- Druh svislé nosné konstrukce -->
+    <PropertyDefn>
+      <Name>DruhKonstrukceKod</Name>
+      <ElementPath>DruhKonstrukceKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Obestavěný prostor v m3 -->
+    <PropertyDefn>
+      <Name>ObestavenyProstor</Name>
+      <ElementPath>ObestavenyProstor</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Počet bytů u stavebního objektu s byty -->
+    <PropertyDefn>
+      <Name>PocetBytu</Name>
+      <ElementPath>PocetBytu</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Počet nadzemních a podzemních podlaží -->
+    <PropertyDefn>
+      <Name>PocetPodlazi</Name>
+      <ElementPath>PocetPodlazi</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Podlahová plocha v m2 -->
+    <PropertyDefn>
+      <Name>PodlahovaPlocha</Name>
+      <ElementPath>PodlahovaPlocha</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Připojení na kanalizační síť -->
+    <PropertyDefn>
+      <Name>PripojeniKanalizaceKod</Name>
+      <ElementPath>PripojeniKanalizaceKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Připojení na rozvod plynu -->
+    <PropertyDefn>
+      <Name>PripojeniPlynKod</Name>
+      <ElementPath>PripojeniPlynKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Připojení na vodovod -->
+    <PropertyDefn>
+      <Name>PripojeniVodovodKod</Name>
+      <ElementPath>PripojeniVodovodKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Vybavení výtahem -->
+    <PropertyDefn>
+      <Name>VybaveniVytahemKod</Name>
+      <ElementPath>VybaveniVytahemKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Zastavěná plocha v m2 -->
+    <PropertyDefn>
+      <Name>ZastavenaPlocha</Name>
+      <ElementPath>ZastavenaPlocha</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob vytápění -->
+    <PropertyDefn>
+      <Name>ZpusobVytapeniKod</Name>
+      <ElementPath>ZpusobVytapeniKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany stavebního objektu - kód ochrany -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyKod</Name>
+      <ElementPath>ZpusobyOchranyPozemku|ZpusobOchrany|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany stavebního objektu - typ ochrany -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyTypOchranyKod</Name>
+      <ElementPath>ZpusobyOchrany|TypOchranyKod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany stavebního objektu - ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyIdTransakce</Name>
+      <ElementPath>ZpusobyOchrany|IdTransakce</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Způsob ochrany stavebního objektu - ID řízení v ISKN -->
+    <PropertyDefn>
+      <Name>ZpusobOchranyRizeniId</Name>
+      <ElementPath>ZpusobyOchrany|RizeniId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- Detailní tecnicko-ekonomické atributy (TEA) (?) -->
+    <PropertyDefn>
+      <Name>DetailniTEAKod</Name>
+      <ElementPath>DetailniTEA|Kod</ElementPath>
+      <Type>IntegerList</Type>
+    </PropertyDefn>
+  </GMLFeatureClass>
+  <!-- Adresní místa -->
+  <GMLFeatureClass>
+    <Name>AdresniMista</Name>
+    <ElementPath>Data|AdresniMista|AdresniMisto</ElementPath>
+    <SRSName>urn:ogc:def:crs:EPSG::5514</SRSName>
+    <!-- Definiční bod typu Adresní bod -->
+    <GeomPropertyDefn>
+      <Name>AdresniBod</Name>
+      <ElementPath>Geometrie|DefinicniBod|AdresniBod</ElementPath>
+      <Type>Point</Type>
+    </GeomPropertyDefn>
+    <!-- Definiční bod typu Přístup pro záchrannou službu -->
+    <GeomPropertyDefn>
+      <Name>Zachranka</Name>
+      <ElementPath>Geometrie|DefinicniBod|Zachranka</ElementPath>
+      <Type>Point</Type>
+    </GeomPropertyDefn>
+    <!-- Definiční bod typu Přístup pro hasiče -->
+    <GeomPropertyDefn>
+      <Name>Hasici</Name>
+      <ElementPath>Geometrie|DefinicniBod|Hasici</ElementPath>
+      <Type>Point</Type>
+    </GeomPropertyDefn>
+    <!-- Kód adresního místa -->
+    <PropertyDefn>
+      <Name>Kod</Name>
+      <ElementPath>Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Identifikátor nesprávnosti na prvku (?) -->
+    <PropertyDefn>
+      <Name>Nespravny</Name>
+      <ElementPath>Nespravny</ElementPath>
+      <Type>String</Type>
+      <Width>5</Width>
+    </PropertyDefn>
+    <!-- Číslo domovní -->
+    <PropertyDefn>
+      <Name>CisloDomovni</Name>
+      <ElementPath>CisloDomovni</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Číselná část čísla orientačního -->
+    <PropertyDefn>
+      <Name>CisloOrientacni</Name>
+      <ElementPath>CisloOrientacni</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Koncové písmeno čísla orientačního -->
+    <PropertyDefn>
+      <Name>CisloOrientacniPismeno</Name>
+      <ElementPath>CisloOrientacniPismeno</ElementPath>
+      <Type>String</Type>
+      <Width>1</Width>
+    </PropertyDefn>
+    <!-- PSČ adresní pošty -->
+    <PropertyDefn>
+      <Name>Psc</Name>
+      <ElementPath>Psc</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Nadřazený stavební objekt -->
+    <PropertyDefn>
+      <Name>StavebniObjektKod</Name>
+      <ElementPath>StavebniObjekt|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Nadřazená ulice -->
+    <PropertyDefn>
+      <Name>UliceKod</Name>
+      <ElementPath>Ulice|Kod</ElementPath>
+      <Type>Integer</Type>
+    </PropertyDefn>
+    <!-- Začátek platnosti -->
+    <PropertyDefn>
+      <Name>PlatiOd</Name>
+      <ElementPath>PlatiOd</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- Konec platnosti -->
+    <PropertyDefn>
+      <Name>PlatiDo</Name>
+      <ElementPath>PlatiDo</ElementPath>
+      <Type>String</Type>
+      <Width>19</Width>
+    </PropertyDefn>
+    <!-- ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>IdTransakce</Name>
+      <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID návrhu změn v ISUI -->
+    <PropertyDefn>
+      <Name>GlobalniIdNavrhuZmeny</Name>
+      <ElementPath>GlobalniIdNavrhuZmeny</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID budovy v ISKN -->
+    <PropertyDefn>
+      <Name>IsknBudovaId</Name>
+      <ElementPath>IsknBudovaId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+  </GMLFeatureClass>
+  <!-- Zaniklé prvky -->
+  <GMLFeatureClass>
+    <Name>ZaniklePrvky</Name>
+    <ElementPath>Data|ZaniklePrvky|ZaniklyPrvek</ElementPath>
+    <!-- Typ prvku -->
+    <PropertyDefn>
+      <Name>TypPrvkuKod</Name>
+      <ElementPath>TypPrvkuKod</ElementPath>
+      <Type>String</Type>
+      <Width>2</Width>
+    </PropertyDefn>
+    <!-- ID (kód) prvku -->
+    <PropertyDefn>
+      <Name>PrvekId</Name>
+      <ElementPath>PrvekId</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+    <!-- ID transakce v RUIAN -->
+    <PropertyDefn>
+      <Name>IdTransakce</Name>
+      <ElementPath>IdTransakce</ElementPath>
+      <!-- OGR integers are only 32 bit wide for now, see http://trac.osgeo.org/gdal/wiki/rfc31_ogr_64
+      <Type>Integer</Type>
+      -->
+      <Type>String</Type>
+      <Width>18</Width>
+    </PropertyDefn>
+  </GMLFeatureClass>
 </GMLFeatureClassList>
diff --git a/frmts/aaigrid/aaigriddataset.cpp b/frmts/aaigrid/aaigriddataset.cpp
index faf5309..d44ebee 100644
--- a/frmts/aaigrid/aaigriddataset.cpp
+++ b/frmts/aaigrid/aaigriddataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: aaigriddataset.cpp 27050 2014-03-18 00:09:03Z kyle $
+ * $Id: aaigriddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Implements Arc/Info ASCII Grid Format.
@@ -35,7 +35,7 @@
 #include "cpl_string.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: aaigriddataset.cpp 27050 2014-03-18 00:09:03Z kyle $");
+CPL_CVSID("$Id: aaigriddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_AAIGrid(void);
@@ -952,7 +952,7 @@ const char *AAIGDataset::GetProjectionRef()
 
 GDALDataset * AAIGDataset::CreateCopy(
                 const char * pszFilename, GDALDataset *poSrcDS,
-                int bStrict, char ** papszOptions, 
+                CPL_UNUSED int bStrict, char ** papszOptions, 
                 GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/adrg/adrgdataset.cpp b/frmts/adrg/adrgdataset.cpp
index 8c6382c..39608bf 100644
--- a/frmts/adrg/adrgdataset.cpp
+++ b/frmts/adrg/adrgdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: adrgdataset.cpp 27095 2014-03-26 15:07:10Z rouault $
+ * $Id: adrgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Purpose:  ADRG reader
  * Author:   Even Rouault, even.rouault at mines-paris.org
@@ -31,7 +31,7 @@
 #include "cpl_string.h"
 #include "iso8211.h"
 
-CPL_CVSID("$Id: adrgdataset.cpp 27095 2014-03-26 15:07:10Z rouault $");
+CPL_CVSID("$Id: adrgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define N_ELEMENTS(x)  (sizeof(x)/sizeof(x[0]))
 
@@ -1569,7 +1569,7 @@ GDALDataset *ADRGDataset::Open( GDALOpenInfo * poOpenInfo )
 /************************************************************************/
 
 GDALDataset *ADRGDataset::Create(const char* pszFilename, int nXSize, int nYSize,
-                                 int nBands, GDALDataType eType, char **papszOptions)
+                                 int nBands, GDALDataType eType, CPL_UNUSED char **papszOptions)
 {
     int i;
 
diff --git a/frmts/aigrid/aigccitt.c b/frmts/aigrid/aigccitt.c
index 132da78..fc57659 100644
--- a/frmts/aigrid/aigccitt.c
+++ b/frmts/aigrid/aigccitt.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: aigccitt.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: aigccitt.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Arc/Info Binary Grid Translator
  * Purpose:  Code for decoding CCITT RLE (G1) compressed data.
@@ -88,6 +88,7 @@ typedef struct {		/* state table entry */
 	GUInt32	Param;		/* unsigned 32-bit run length in bits */
 } TIFFFaxTabEnt;
 
+#if 0  /* Unused */
 static const TIFFFaxTabEnt aig_TIFFFaxMainTable[128] = {
 {12,7,0},{3,1,0},{5,3,1},{3,1,0},{2,3,0},{3,1,0},{4,3,1},{3,1,0},{1,4,0},{3,1,0},{5,3,1},{3,1,0},
 {2,3,0},{3,1,0},{4,3,1},{3,1,0},{5,6,2},{3,1,0},{5,3,1},{3,1,0},{2,3,0},{3,1,0},{4,3,1},{3,1,0},
@@ -101,6 +102,8 @@ static const TIFFFaxTabEnt aig_TIFFFaxMainTable[128] = {
 {2,3,0},{3,1,0},{4,3,1},{3,1,0},{4,6,2},{3,1,0},{5,3,1},{3,1,0},{2,3,0},{3,1,0},{4,3,1},{3,1,0},
 {1,4,0},{3,1,0},{5,3,1},{3,1,0},{2,3,0},{3,1,0},{4,3,1},{3,1,0}
 };
+#endif  /* Unused */
+
 static const TIFFFaxTabEnt aig_TIFFFaxWhiteTable[4096] = {
 {12,11,0},{7,4,3},{7,5,11},{7,4,5},{7,6,12},{7,5,9},{9,6,1664},{7,4,6},{7,7,20},{9,5,128},{7,7,24},{7,6,14},
 {7,7,28},{7,4,4},{7,4,2},{7,4,7},{7,7,23},{7,4,3},{7,7,27},{7,4,5},{7,8,39},{7,6,16},{9,8,576},{7,4,6},
@@ -1165,6 +1168,8 @@ static const unsigned char aig_TIFFBitRevTable[256] = {
     0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
     0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
 };
+
+#if 0  /* Unused */
 static const unsigned char aig_TIFFNoBitRevTable[256] = {
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 
@@ -1199,6 +1204,7 @@ static const unsigned char aig_TIFFNoBitRevTable[256] = {
     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 
     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 
 };
+#endif  /* Unused */
 
 /*
  * The following macros define the majority of the G3/G4 decoder
@@ -1848,7 +1854,7 @@ Fax3DecodeRLE(Fax3BaseState* tif, unsigned char *buf, int occ,
 
 CPLErr DecompressCCITTRLETile( unsigned char *pabySrcData, int nSrcBytes, 
                                unsigned char *pabyDstData, int nDstBytes,
-                               int nBlockXSize, int nBlockYSize )
+                               int nBlockXSize, CPL_UNUSED int nBlockYSize )
 
 {
     Fax3DecodeState  sDecoderState;
@@ -1865,7 +1871,8 @@ CPLErr DecompressCCITTRLETile( unsigned char *pabySrcData, int nSrcBytes,
     DecoderState(sp)->runs = NULL;
     DecoderState(sp)->fill = aig_TIFFFax3fillruns;
 
-    if( sizeof(runs_buf) < (nBlockXSize * 2 + 3) )
+    /* TODO: Verify that the cast is safe. */
+    if( sizeof(runs_buf) < (size_t)(nBlockXSize * 2 + 3) )
     {
         CPLError(CE_Failure, CPLE_AppDefined, "Run buffer too small");
         return CE_Failure;
diff --git a/frmts/airsar/airsardataset.cpp b/frmts/airsar/airsardataset.cpp
index 818d2ec..fa2880d 100644
--- a/frmts/airsar/airsardataset.cpp
+++ b/frmts/airsar/airsardataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: airsardataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: airsardataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  AirSAR Reader
  * Purpose:  Implements read support for AirSAR Polarimetric data.
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_vsi.h"
 
-CPL_CVSID("$Id: airsardataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: airsardataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_AirSAR(void);
@@ -173,7 +173,7 @@ AirSARRasterBand::~AirSARRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr AirSARRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr AirSARRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                       void * pImage )
 
 {
diff --git a/frmts/arg/argdataset.cpp b/frmts/arg/argdataset.cpp
index f746a5d..7924434 100644
--- a/frmts/arg/argdataset.cpp
+++ b/frmts/arg/argdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: argdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: argdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Azavea Raster Grid format driver.
  * Purpose:  Implements support for reading and writing Azavea Raster Grid
@@ -34,7 +34,7 @@
 #include <json.h>
 #include <ogr_spatialref.h>
 
-CPL_CVSID("$Id: argdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: argdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define MAX_FILENAME_LEN 4096
 
@@ -577,8 +577,11 @@ GDALDataset *ARGDataset::Open( GDALOpenInfo * poOpenInfo )
 /*                          CreateCopy()                                */
 /************************************************************************/
 GDALDataset * ARGDataset::CreateCopy( const char * pszFilename, 
-    GDALDataset * poSrcDS, int bStrict, char ** papszOptions, 
-    GDALProgressFunc pfnProgress, void * pProgressData ) 
+                                      GDALDataset * poSrcDS,
+                                      CPL_UNUSED int bStrict,
+                                      CPL_UNUSED char ** papszOptions, 
+                                      CPL_UNUSED GDALProgressFunc pfnProgress,
+                                      CPL_UNUSED void * pProgressData ) 
 {
     int nBands = poSrcDS->GetRasterCount();
     int nXSize = poSrcDS->GetRasterXSize();
diff --git a/frmts/blx/blx.c b/frmts/blx/blx.c
index ffee433..a3a8f99 100644
--- a/frmts/blx/blx.c
+++ b/frmts/blx/blx.c
@@ -534,7 +534,7 @@ int lutcmp(const void *aa, const void *bb) {
 }
 
 
-int blx_encode_celldata(blxcontext_t *ctx, blxdata *indata, int side, unsigned char *outbuf, int outbufsize) {
+int blx_encode_celldata(blxcontext_t *ctx, blxdata *indata, int side, unsigned char *outbuf, CPL_UNUSED int outbufsize) {
     unsigned char *p=outbuf, *tmpdata, *coutstart, *cout=NULL;
     int level, cn, coutsize, zeros;
     blxdata *vdec=NULL, *vdiff=NULL, *c[4], *tc1, *clut, *indata_scaled;
diff --git a/frmts/bmp/bmpdataset.cpp b/frmts/bmp/bmpdataset.cpp
index 6b05c9e..9ca9bfa 100644
--- a/frmts/bmp/bmpdataset.cpp
+++ b/frmts/bmp/bmpdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: bmpdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: bmpdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Microsoft Windows Bitmap
  * Purpose:  Read/write MS Windows Device Independent Bitmap (DIB) files
@@ -32,7 +32,7 @@
 #include "gdal_pam.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: bmpdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: bmpdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_BMP(void);
@@ -164,7 +164,9 @@ typedef struct
 
 // Info header size in bytes:
 const unsigned int  BIH_WIN4SIZE = 40; // for BMPT_WIN4
+#if 0  /* Unused */
 const unsigned int  BIH_WIN5SIZE = 57; // for BMPT_WIN5
+#endif
 const unsigned int  BIH_OS21SIZE = 12; // for BMPT_OS21
 const unsigned int  BIH_OS22SIZE = 64; // for BMPT_OS22
 
@@ -319,7 +321,7 @@ BMPRasterBand::~BMPRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr BMPRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr BMPRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 {
     BMPDataset  *poGDS = (BMPDataset *) poDS;
@@ -859,7 +861,7 @@ BMPComprRasterBand::~BMPComprRasterBand()
 /************************************************************************/
 
 CPLErr BMPComprRasterBand::
-    IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage )
+    IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff, void * pImage )
 {
     memcpy( pImage, pabyUncomprBuf +
             (poDS->GetRasterYSize() - nBlockYOff - 1) * poDS->GetRasterXSize(),
diff --git a/frmts/bsb/bsb_read.c b/frmts/bsb/bsb_read.c
index 0ac0f4b..e7df644 100644
--- a/frmts/bsb/bsb_read.c
+++ b/frmts/bsb/bsb_read.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: bsb_read.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: bsb_read.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  BSB Reader
  * Purpose:  Low level BSB Access API Implementation (non-GDAL).
@@ -37,7 +37,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: bsb_read.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: bsb_read.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 static int BSBReadHeaderLine( BSBInfo *psInfo, char* pszLine, int nLineMaxLen, int bNO1 );
 static int BSBSeekAndCheckScanlineNumber ( BSBInfo *psInfo, int nScanline,
@@ -214,7 +214,7 @@ BSBInfo *BSBOpen( const char *pszFilename )
         return NULL;
     }
 
-    for( i = 0; i < sizeof(achTestBlock) - 4; i++ )
+    for( i = 0; (size_t)i < sizeof(achTestBlock) - 4; i++ )
     {
         /* Test for "BSB/" */
         if( achTestBlock[i+0] == 'B' && achTestBlock[i+1] == 'S' 
@@ -882,7 +882,8 @@ int BSBReadScanline( BSBInfo *psInfo, int nScanline,
     while ( iPixel < psInfo->nXSize &&
             (nScanline == psInfo->nYSize-1 ||
              psInfo->panLineOffset[nScanline+1] == -1 ||
-             VSIFTellL( fp ) - psInfo->nBufferSize + psInfo->nBufferOffset < psInfo->panLineOffset[nScanline+1]) );
+             /* TODO: Will this work for large files? */
+             (int)(VSIFTellL( fp ) - psInfo->nBufferSize + psInfo->nBufferOffset) < psInfo->panLineOffset[nScanline+1]) );
 
 /* -------------------------------------------------------------------- */
 /*      If the line buffer is not filled after reading the line in the  */
@@ -928,7 +929,7 @@ void BSBClose( BSBInfo *psInfo )
 /*                             BSBCreate()                              */
 /************************************************************************/
 
-BSBInfo *BSBCreate( const char *pszFilename, int nCreationFlags, int nVersion, 
+BSBInfo *BSBCreate( const char *pszFilename, CPL_UNUSED int nCreationFlags, int nVersion, 
                     int nXSize, int nYSize )
 
 {
diff --git a/frmts/bsb/bsbdataset.cpp b/frmts/bsb/bsbdataset.cpp
index 6745b2e..5c4048d 100644
--- a/frmts/bsb/bsbdataset.cpp
+++ b/frmts/bsb/bsbdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: bsbdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: bsbdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  BSB Reader
  * Purpose:  BSBDataset implementation for BSB format.
@@ -33,7 +33,7 @@
 #include "cpl_string.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: bsbdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: bsbdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_BSB(void);
@@ -135,7 +135,7 @@ BSBRasterBand::BSBRasterBand( BSBDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr BSBRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr BSBRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                       void * pImage )
 
 {
diff --git a/frmts/ceos/ceosdataset.cpp b/frmts/ceos/ceosdataset.cpp
index bdb72dd..080812c 100644
--- a/frmts/ceos/ceosdataset.cpp
+++ b/frmts/ceos/ceosdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ceosdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ceosdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CEOS Translator
  * Purpose:  GDALDataset driver for CEOS translator.
@@ -31,7 +31,7 @@
 #include "ceosopen.h"
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: ceosdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ceosdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_CEOS(void);
@@ -95,7 +95,7 @@ CEOSRasterBand::CEOSRasterBand( CEOSDataset *poDS, int nBand )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr CEOSRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr CEOSRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
diff --git a/frmts/ceos/ceosopen.c b/frmts/ceos/ceosopen.c
index 2feba2e..9fc099b 100644
--- a/frmts/ceos/ceosopen.c
+++ b/frmts/ceos/ceosopen.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ceosopen.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ceosopen.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CEOS Translator
  * Purpose:  Implementation of non-GDAL dependent CEOS support.
@@ -30,7 +30,7 @@
 
 #include "ceosopen.h"
 
-CPL_CVSID("$Id: ceosopen.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ceosopen.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            CEOSScanInt()                             */
@@ -275,7 +275,7 @@ CEOSImage * CEOSOpen( const char * pszFilename, const char * pszAccess )
     if( psImage->nImageRecLength <= 0 ||
         psImage->nPrefixBytes < 0 ||
         psImage->nBands > INT_MAX / psImage->nImageRecLength ||
-        psImage->nBands > INT_MAX / sizeof(int))
+        (size_t)psImage->nBands > INT_MAX / sizeof(int))
     {
         CEOSDestroyRecord( psRecord );
         CEOSClose( psImage );
diff --git a/frmts/ceos2/ceossar.c b/frmts/ceos2/ceossar.c
index c95b0a2..d87be7a 100644
--- a/frmts/ceos2/ceossar.c
+++ b/frmts/ceos2/ceossar.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ceossar.c 10645 2007-01-18 02:22:39Z warmerdam $
+ * $Id: ceossar.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ASI CEOS Translator
  * Purpose:  Functions related to CeosSARVolume_t.
@@ -29,7 +29,7 @@
 
 #include "ceos.h"
 
-CPL_CVSID("$Id: ceossar.c 10645 2007-01-18 02:22:39Z warmerdam $");
+CPL_CVSID("$Id: ceossar.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern Link_t *RecipeFunctions;
 
@@ -94,17 +94,20 @@ void CalcCeosSARImageFilePosition(CeosSARVolume_t *volume, int channel, int line
     }
 }
 
-int32 GetCeosSARImageData(CeosSARVolume_t *volume, CeosRecord_t *processed_data_record, int channel, int xoff, int xsize, int bufsize, uchar *buffer)
+int32 GetCeosSARImageData(CPL_UNUSED CeosSARVolume_t *volume,
+                          CPL_UNUSED CeosRecord_t *processed_data_record,
+                          CPL_UNUSED int channel, CPL_UNUSED int xoff, CPL_UNUSED int xsize,
+                          CPL_UNUSED int bufsize, CPL_UNUSED uchar *buffer)
 {
     return 0;
 }
 
-void DetermineCeosSARPixelOrder( CeosSARVolume_t *volume, CeosRecord_t *record )
+void DetermineCeosSARPixelOrder( CPL_UNUSED CeosSARVolume_t *volume, CPL_UNUSED CeosRecord_t *record )
 {
 
 }
 
-void GetCeosSAREmbeddedInfo(CeosSARVolume_t *volume, CeosRecord_t *processed_data_record, CeosSAREmbeddedInfo_t *info)
+void GetCeosSAREmbeddedInfo(CPL_UNUSED CeosSARVolume_t *volume, CPL_UNUSED CeosRecord_t *processed_data_record, CPL_UNUSED CeosSAREmbeddedInfo_t *info)
 {
 }
 
diff --git a/frmts/ceos2/sar_ceosdataset.cpp b/frmts/ceos2/sar_ceosdataset.cpp
index 93a9faf..5ca07fa 100644
--- a/frmts/ceos2/sar_ceosdataset.cpp
+++ b/frmts/ceos2/sar_ceosdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: sar_ceosdataset.cpp 27067 2014-03-20 22:20:43Z rouault $
+ * $Id: sar_ceosdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ASI CEOS Translator
  * Purpose:  GDALDataset driver for CEOS translator.
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: sar_ceosdataset.cpp 27067 2014-03-20 22:20:43Z rouault $");
+CPL_CVSID("$Id: sar_ceosdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_SAR_CEOS(void);
@@ -237,7 +237,7 @@ SAR_CEOSRasterBand::SAR_CEOSRasterBand( SAR_CEOSDataset *poGDS, int nBand,
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr SAR_CEOSRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr SAR_CEOSRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                        void * pImage )
 
 {
@@ -371,7 +371,7 @@ Im(SVV) = byte(10) ysca/127
 
 */
 
-CPLErr CCPRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr CCPRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -517,7 +517,7 @@ PALSARRasterBand::PALSARRasterBand( SAR_CEOSDataset *poGDS, int nBand )
 /*      Based on ERSDAC-VX-CEOS-004                                     */
 /************************************************************************/
 
-CPLErr PALSARRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr PALSARRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                      void * pImage )
 
 {
@@ -2161,7 +2161,8 @@ ProcessData( VSILFILE *fp, int fileid, CeosSARVolume_t *sar, int max_records,
             max_records--;
         if(max_bytes > 0)
         {
-            if( record->Length <= max_bytes )
+            // TODO: Make sure that this cast is safe.
+            if( (vsi_l_offset)record->Length <= max_bytes )
                 max_bytes -= record->Length;
             else {
                 CPLDebug( "SAR_CEOS", "Partial record found.  %d > " CPL_FRMT_GUIB,
diff --git a/frmts/coasp/coasp_dataset.cpp b/frmts/coasp/coasp_dataset.cpp
index 9a5bc87..d8bd220 100644
--- a/frmts/coasp/coasp_dataset.cpp
+++ b/frmts/coasp/coasp_dataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: coasp_dataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: coasp_dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DRDC Configurable Airborne SAR Processor (COASP) data reader
  * Purpose:  Support in GDAL for the DRDC COASP format data, both Metadata
@@ -39,7 +39,7 @@
 #include "cpl_vsi.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: coasp_dataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: coasp_dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_COASP(void);
@@ -292,8 +292,8 @@ COASPRasterBand::COASPRasterBand( COASPDataset *poDS, GDALDataType eDataType,
 	this->nBlockYSize = 1;
 }
 
-CPLErr COASPRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, 
-	void *pImage )
+CPLErr COASPRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff, 
+                                    void *pImage )
 {
 	if (this->fp == NULL) {
 		CPLError(CE_Fatal, 1, "file pointer freed unexpectedly\n");
diff --git a/frmts/cosar/cosar_dataset.cpp b/frmts/cosar/cosar_dataset.cpp
index dc78b0a..cd53ac2 100644
--- a/frmts/cosar/cosar_dataset.cpp
+++ b/frmts/cosar/cosar_dataset.cpp
@@ -78,9 +78,8 @@ COSARRasterBand::COSARRasterBand(COSARDataset *pDS, unsigned long nRTNB) {
 	eDataType = GDT_CInt16;
 }
 
-CPLErr COSARRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, 
-	void *pImage) {
-
+CPLErr COSARRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff, 
+                                   void *pImage) {
     unsigned long nRSFV = 0;
     unsigned long nRSLV = 0;
     COSARDataset *pCDS = (COSARDataset *) poDS;
diff --git a/frmts/ctg/ctgdataset.cpp b/frmts/ctg/ctgdataset.cpp
index b690dc4..bf9260a 100644
--- a/frmts/ctg/ctgdataset.cpp
+++ b/frmts/ctg/ctgdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ctgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ctgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CTG driver
  * Purpose:  GDALDataset driver for CTG dataset.
@@ -30,7 +30,7 @@
 #include "gdal_pam.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: ctgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ctgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_CTG(void);
@@ -194,9 +194,8 @@ CTGRasterBand::~CTGRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr CTGRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr CTGRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, CPL_UNUSED int nBlockYOff,
                                   void * pImage )
-
 {
     CTGDataset* poGDS = (CTGDataset* ) poDS;
 
diff --git a/frmts/dimap/dimapdataset.cpp b/frmts/dimap/dimapdataset.cpp
index 90828f5..425c238 100644
--- a/frmts/dimap/dimapdataset.cpp
+++ b/frmts/dimap/dimapdataset.cpp
@@ -35,7 +35,7 @@
 #include "ogr_spatialref.h"
 #include "gdal_proxy.h"
 
-CPL_CVSID("$Id: dimapdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: dimapdataset.cpp 27222 2014-04-19 18:09:01Z rouault $");
 
 CPL_C_START
 void    GDALRegister_DIMAP(void);
@@ -432,7 +432,13 @@ GDALDataset *DIMAPDataset::Open( GDALOpenInfo * poOpenInfo )
         
         CPLXMLNode *psDatasetComponent = psDatasetComponents->psChild;
 
-        for( ; psDatasetComponent != NULL; psDatasetComponent = psDatasetComponent->psNext ) 
+        if( CPLGetXMLNode(psDoc, "Raster_Data") ) 
+        {
+            osDIMAPFilename = osMDFilename; 
+        }
+
+        for( ; osDIMAPFilename.size() == 0 && psDatasetComponent != NULL;
+                psDatasetComponent = psDatasetComponent->psNext ) 
         {
             const char* pszComponentType = CPLGetXMLValue(psDatasetComponent, "COMPONENT_TYPE","");
             if( strcmp(pszComponentType, "DIMAP") == 0 )
@@ -500,7 +506,7 @@ GDALDataset *DIMAPDataset::Open( GDALOpenInfo * poOpenInfo )
                     {
                         CPLString osPath = CPLGetPath(osDIMAPFilename);
                         osSTRIPFilename = 
-                            CPLFormFilename( osPath, pszHref, NULL );
+                            CPLFormCIFilename( osPath, pszHref, NULL );
                         
                         break;
                     }
@@ -610,6 +616,12 @@ int DIMAPDataset::ReadImageInformation()
         adfGeoTransform[4] = 0.0;
         adfGeoTransform[5] = -atof(CPLGetXMLValue(psGeoLoc,"YDIM","0"));
     }
+    else
+    {
+        // Try to get geotransform from underlying raster. 
+        if ( poImageDS->GetGeoTransform(adfGeoTransform) == CE_None ) 
+            bHaveGeoTransform = TRUE; 
+    }
 
 /* -------------------------------------------------------------------- */
 /*      Collect GCPs.                                                   */
@@ -818,7 +830,7 @@ int DIMAPDataset::ReadImageInformation2()
         {
             CPLString osPath = CPLGetPath( osDIMAPFilename );
             osImageDSFilename = 
-                CPLFormFilename( osPath, pszHref, NULL );
+                CPLFormCIFilename( osPath, pszHref, NULL );
         }
         else
         {
@@ -864,14 +876,26 @@ int DIMAPDataset::ReadImageInformation2()
         adfGeoTransform[4] = 0.0;
         adfGeoTransform[5] = -atof(CPLGetXMLValue(psGeoLoc,"YDIM","0"));
     }
+    else
+    {
+        // Try to get geotransform from underlying raster. 
+        if ( poImageDS->GetGeoTransform(adfGeoTransform) == CE_None ) 
+            bHaveGeoTransform = TRUE; 
+    }
+
 
 /* -------------------------------------------------------------------- */
 /*      Collect the CRS.  For now we look only for EPSG codes.          */
 /* -------------------------------------------------------------------- */
     const char *pszSRS = CPLGetXMLValue( 
         psDoc, 
-        "Coordinate_Reference_System.Projected_CRS..PROJECTED_CRS_CODE", 
+        "Coordinate_Reference_System.Projected_CRS.PROJECTED_CRS_CODE", 
         NULL );
+    if( pszSRS == NULL )
+        pszSRS = CPLGetXMLValue( 
+            psDoc, 
+            "Coordinate_Reference_System.Geodetic_CRS.GEODETIC_CRS_CODE", 
+            NULL );
 
     if( pszSRS != NULL )
     {
diff --git a/frmts/dted/dted_ptstream.c b/frmts/dted/dted_ptstream.c
index f6d4f35..14dbcd3 100644
--- a/frmts/dted/dted_ptstream.c
+++ b/frmts/dted/dted_ptstream.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dted_ptstream.c 23425 2011-11-26 19:14:25Z rouault $
+ * $Id: dted_ptstream.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DTED Translator
  * Purpose:  DTED Point Stream Writer.
@@ -29,7 +29,7 @@
 
 #include "dted_api.h"
 
-CPL_CVSID("$Id: dted_ptstream.c 23425 2011-11-26 19:14:25Z rouault $");
+CPL_CVSID("$Id: dted_ptstream.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 typedef struct {
     char     *pszFilename;
@@ -187,7 +187,7 @@ static int DTEDPtStreamNewTile( DTEDPtStream *psStream,
 /*                           DTEDWritePtLL()                            */
 /************************************************************************/
 
-static int DTEDWritePtLL( DTEDPtStream *psStream, 
+static int DTEDWritePtLL( CPL_UNUSED DTEDPtStream *psStream, 
                           DTEDCachedFile *psCF, 
                           double dfLong, double dfLat, double dfElev )
 
diff --git a/frmts/dted/dteddataset.cpp b/frmts/dted/dteddataset.cpp
index eedb6dc..c1f3b96 100644
--- a/frmts/dted/dteddataset.cpp
+++ b/frmts/dted/dteddataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dteddataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: dteddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DTED Translator
  * Purpose:  GDALDataset driver for DTED translator.
@@ -33,7 +33,7 @@
 #include "ogr_spatialref.h"
 #include <algorithm>
 
-CPL_CVSID("$Id: dteddataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: dteddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_DTED(void);
@@ -125,7 +125,7 @@ DTEDRasterBand::DTEDRasterBand( DTEDDataset *poDS, int nBand )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr DTEDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr DTEDRasterBand::IReadBlock( int nBlockXOff, CPL_UNUSED int nBlockYOff,
                                   void * pImage )
 
 {
@@ -187,7 +187,7 @@ CPLErr DTEDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr DTEDRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff,
+CPLErr DTEDRasterBand::IWriteBlock( int nBlockXOff, CPL_UNUSED int nBlockYOff,
                                   void * pImage )
 
 {
diff --git a/frmts/e00grid/e00griddataset.cpp b/frmts/e00grid/e00griddataset.cpp
index 68e320a..ba87472 100644
--- a/frmts/e00grid/e00griddataset.cpp
+++ b/frmts/e00grid/e00griddataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: e00griddataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: e00griddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  E00 grid driver
  * Purpose:  GDALDataset driver for E00 grid dataset.
@@ -46,7 +46,7 @@
 #define E00_DOUBLE_SIZE 21
 #define VALS_PER_LINE   5
 
-CPL_CVSID("$Id: e00griddataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: e00griddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_E00GRID(void);
@@ -164,7 +164,7 @@ E00GRIDRasterBand::E00GRIDRasterBand( E00GRIDDataset *poDS, int nBand,
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr E00GRIDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr E00GRIDRasterBand::IReadBlock( int CPL_UNUSED nBlockXOff, int nBlockYOff,
                                       void * pImage )
 
 {
diff --git a/frmts/elas/elasdataset.cpp b/frmts/elas/elasdataset.cpp
index 2cbce33..e622fcd 100644
--- a/frmts/elas/elasdataset.cpp
+++ b/frmts/elas/elasdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: elasdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: elasdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ELAS Translator
  * Purpose:  Complete implementation of ELAS translator module for GDAL.
@@ -30,7 +30,7 @@
 
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: elasdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: elasdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_ELAS(void);
@@ -153,7 +153,7 @@ ELASRasterBand::ELASRasterBand( ELASDataset *poDS, int nBand )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr ELASRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr ELASRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                    void * pImage )
 
 {
@@ -188,7 +188,7 @@ CPLErr ELASRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 /*                            IWriteBlock()                             */
 /************************************************************************/
 
-CPLErr ELASRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff,
+CPLErr ELASRasterBand::IWriteBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                      void * pImage )
 
 {
diff --git a/frmts/envisat/EnvisatFile.c b/frmts/envisat/EnvisatFile.c
index 77ca5b3..3b8a93c 100644
--- a/frmts/envisat/EnvisatFile.c
+++ b/frmts/envisat/EnvisatFile.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: EnvisatFile.c 27098 2014-03-27 00:16:11Z rouault $
+ * $Id: EnvisatFile.c 27731 2014-09-24 07:58:14Z rouault $
  *
  * Project:  APP ENVISAT Support
  * Purpose:  Low Level Envisat file access (read/write) API.
@@ -33,7 +33,7 @@
 #  include "cpl_conv.h"
 #  include "EnvisatFile.h"
 
-CPL_CVSID("$Id: EnvisatFile.c 27098 2014-03-27 00:16:11Z rouault $");
+CPL_CVSID("$Id: EnvisatFile.c 27731 2014-09-24 07:58:14Z rouault $");
 
 #else
 #  include "APP/app.h"
@@ -1204,10 +1204,10 @@ Returns:
 -----------------------------------------------------------------------------*/
 
 int EnvisatFile_GetDatasetIndex( EnvisatFile *self, const char *ds_name )
-
 {
-    int		i;
     char	padded_ds_name[100];
+    size_t i;
+    int ii;
 
     /* 
      * Padd the name.  While the normal product spec says the DS_NAME will
@@ -1225,12 +1225,12 @@ int EnvisatFile_GetDatasetIndex( EnvisatFile *self, const char *ds_name )
     /* 
      * Compare only for the full length of DS_NAME we have saved.
      */
-    for( i = 0; i < self->ds_count; i++ )
+    for( ii = 0; ii < self->ds_count; ii++ )
     {
-        if( strncmp( padded_ds_name, self->ds_info[i]->ds_name, 
-                     strlen(self->ds_info[i]->ds_name) ) == 0 )
+        if( strncmp( padded_ds_name, self->ds_info[ii]->ds_name, 
+                     strlen(self->ds_info[ii]->ds_name) ) == 0 )
         {
-            return i;
+            return ii;
         }
     }
 
@@ -1739,7 +1739,7 @@ int S_NameValueList_Parse( const char *text, int text_offset,
         line_offset = (int) (next_text - text) + text_offset;
         while( *next_text != '\0' && *next_text != '\n' )
         {
-            if( line_len > sizeof(line)-1 )
+          if( (size_t)line_len > sizeof(line)-1 )
             {
                 SendError( "S_NameValueList_Parse(): "
                            "Corrupt line, longer than 1024 characters." );
diff --git a/frmts/envisat/envisatdataset.cpp b/frmts/envisat/envisatdataset.cpp
index ad29294..f38dcd2 100644
--- a/frmts/envisat/envisatdataset.cpp
+++ b/frmts/envisat/envisatdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: envisatdataset.cpp 27098 2014-03-27 00:16:11Z rouault $
+ * $Id: envisatdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  APP ENVISAT Support
  * Purpose:  Reader for ENVISAT format image data.
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: envisatdataset.cpp 27098 2014-03-27 00:16:11Z rouault $");
+CPL_CVSID("$Id: envisatdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 #include "EnvisatFile.h"
@@ -105,7 +105,7 @@ MerisL2FlagBand::~MerisL2FlagBand()
 /************************************************************************/
 /*                             IReadBlock()                             */
 /************************************************************************/
-CPLErr MerisL2FlagBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr MerisL2FlagBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                     void * pImage )
 {
     CPLAssert( nBlockXOff == 0 );
diff --git a/frmts/envisat/records.c b/frmts/envisat/records.c
index 9e19d27..9187834 100644
--- a/frmts/envisat/records.c
+++ b/frmts/envisat/records.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: records.c 22499 2011-06-04 14:45:17Z rouault $
+ * $Id: records.c 27705 2014-09-21 14:13:36Z goatbar $
  *
  * Project:  APP ENVISAT Support
  * Purpose:  Low Level Envisat file access (read/write) API.
@@ -29,7 +29,7 @@
 
 #include "records.h"
 
-CPL_CVSID("$Id: records.c 22499 2011-06-04 14:45:17Z rouault $");
+CPL_CVSID("$Id: records.c 27705 2014-09-21 14:13:36Z goatbar $");
 
 /* --- ASAR record descriptors --------------------------------------------- */
 static const EnvisatFieldDescr ASAR_ANTENNA_ELEV_PATT_ADSR[] = {
@@ -199,6 +199,7 @@ static const EnvisatFieldDescr ASAR_DOP_CENTROID_COEFFS_ADSR[] = {
     {NULL,                                                 0, EDT_Unknown,     0}
 };
 
+#if 0  /* Unused */
 static const EnvisatFieldDescr ASAR_GEOLOCATION_GRID_ADSR[] = {
     {"FIRST_ZERO_DOPPLER_TIME",                            0, EDT_MJD,         1},
     {"ATTACH_FLAG",                                       12, EDT_UByte,       1},
@@ -220,6 +221,7 @@ static const EnvisatFieldDescr ASAR_GEOLOCATION_GRID_ADSR[] = {
     /*{"SPARE_2",                                        499, EDT_UByte,      22},*/
     {NULL,                                                 0, EDT_Unknown,     0}
 };
+#endif  /* Unused */
 
 static const EnvisatFieldDescr ASAR_MAIN_PROCESSING_PARAMS_ADSR[] = {
     {"FIRST_ZERO_DOPPLER_TIME",                            0, EDT_MJD,         1},
@@ -564,6 +566,7 @@ static const EnvisatFieldDescr ASAR_SR_GR_ADSR[] = {
     {NULL,                                                 0, EDT_Unknown,     0}
 };
 
+#if 0  /* Unused */
 static const EnvisatFieldDescr ASAR_GEOLOCATION_ADSR[] = {
     {"ZERO_DOPPLER_TIME",                                  0, EDT_MJD,         1},
     {"ATTACH_FLAG",                                       12, EDT_UByte,       1},
@@ -572,6 +575,7 @@ static const EnvisatFieldDescr ASAR_GEOLOCATION_ADSR[] = {
     /*{"SPARE_1",                                         21, EDT_UByte,       4},*/
     {NULL,                                                 0, EDT_Unknown,     0}
 };
+#endif  /* Unused */
 
 static const EnvisatFieldDescr ASAR_PROCESSING_PARAMS_ADSR[] = {
     {"FIRST_ZERO_DOPPLER_TIME",                            0, EDT_MJD,         1},
diff --git a/frmts/ers/ersdataset.cpp b/frmts/ers/ersdataset.cpp
index bd4b4ef..5738ffc 100644
--- a/frmts/ers/ersdataset.cpp
+++ b/frmts/ers/ersdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ersdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ersdataset.cpp 27433 2014-06-04 19:21:16Z rouault $
  *
  * Project:  ERMapper .ers Driver
  * Purpose:  Implementation of .ers driver.
@@ -33,7 +33,7 @@
 #include "cpl_string.h"
 #include "ershdrnode.h"
 
-CPL_CVSID("$Id: ersdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ersdataset.cpp 27433 2014-06-04 19:21:16Z rouault $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -553,7 +553,15 @@ CPLErr ERSDataset::SetGeoTransform( double *padfTransform )
                    CPLString().Printf( "%.15g", adfGeoTransform[0] ) );
     poHeader->Set( "RasterInfo.RegistrationCoord.Northings", 
                    CPLString().Printf( "%.15g", adfGeoTransform[3] ) );
-    
+
+    if( CPLAtof(poHeader->Find("RasterInfo.RegistrationCellX", "0")) != 0.0 ||
+        CPLAtof(poHeader->Find("RasterInfo.RegistrationCellY", "0")) != 0.0 ) 
+    {
+        // Reset RegistrationCellX/Y to 0 if the header gets rewritten (#5493)
+        poHeader->Set("RasterInfo.RegistrationCellX", "0");
+        poHeader->Set("RasterInfo.RegistrationCellY", "0");
+    }
+
     return CE_None;
 }
 
diff --git a/frmts/georaster/georaster_dataset.cpp b/frmts/georaster/georaster_dataset.cpp
index 97091f0..495ce2c 100644
--- a/frmts/georaster/georaster_dataset.cpp
+++ b/frmts/georaster/georaster_dataset.cpp
@@ -1,2112 +1,2118 @@
-/******************************************************************************
- * $Id: $
- *
- * Name:     georaster_dataset.cpp
- * Project:  Oracle Spatial GeoRaster Driver
- * Purpose:  Implement GeoRasterDataset Methods
- * Author:   Ivan Lucena [ivan.lucena at oracle.com]
- *
- ******************************************************************************
- * Copyright (c) 2008, Ivan Lucena
+/******************************************************************************
+ * $Id: $
+ *
+ * Name:     georaster_dataset.cpp
+ * Project:  Oracle Spatial GeoRaster Driver
+ * Purpose:  Implement GeoRasterDataset Methods
+ * Author:   Ivan Lucena [ivan.lucena at oracle.com]
+ *
+ ******************************************************************************
+ * Copyright (c) 2008, Ivan Lucena
  * Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files ( the "Software" ),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *****************************************************************************/
-
-#include "cpl_error.h"
-
-#include "ogr_spatialref.h"
-
-#include "gdal.h"
-#include "gdal_priv.h"
-#include "georaster_priv.h"
-
-CPL_C_START
-void CPL_DLL GDALRegister_GEOR(void);
-CPL_C_END
-
-//  ---------------------------------------------------------------------------
-//                                                           GeoRasterDataset()
-//  ---------------------------------------------------------------------------
-
-GeoRasterDataset::GeoRasterDataset()
-{
-    bGeoTransform       = false;
-    bForcedSRID         = false;
-    poGeoRaster         = NULL;
-    papszSubdatasets    = NULL;
-    adfGeoTransform[0]  = 0.0;
-    adfGeoTransform[1]  = 1.0;
-    adfGeoTransform[2]  = 0.0;
-    adfGeoTransform[3]  = 0.0;
-    adfGeoTransform[4]  = 0.0;
-    adfGeoTransform[5]  = 1.0;
-    pszProjection       = NULL;
-    nGCPCount           = 0;
-    pasGCPList          = NULL;
-    poMaskBand          = NULL;
-    bApplyNoDataArray   = false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                          ~GeoRasterDataset()
-//  ---------------------------------------------------------------------------
-
-GeoRasterDataset::~GeoRasterDataset()
-{
-    FlushCache();
-
-    if( nGCPCount > 0 )
-    {
-        GDALDeinitGCPs( nGCPCount, pasGCPList );
-        CPLFree( pasGCPList );
-    }
-
-    delete poGeoRaster;
-
-    if( poMaskBand )
-    {
-        delete poMaskBand;
-    }
-    
-    CPLFree( pszProjection );
-    CSLDestroy( papszSubdatasets );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                   Identify()
-//  ---------------------------------------------------------------------------
-
-int GeoRasterDataset::Identify( GDALOpenInfo* poOpenInfo )
-{
-    //  -------------------------------------------------------------------
-    //  Verify georaster prefix
-    //  -------------------------------------------------------------------
-
-    char* pszFilename = poOpenInfo->pszFilename;
-
-    if( EQUALN( pszFilename, "georaster:", 10 ) == false &&
-        EQUALN( pszFilename, "geor:", 5 )       == false )
-    {
-        return false;
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                       Open()
-//  ---------------------------------------------------------------------------
-
-GDALDataset* GeoRasterDataset::Open( GDALOpenInfo* poOpenInfo )
-{
-    //  -------------------------------------------------------------------
-    //  It shouldn't have an open file pointer
-    //  -------------------------------------------------------------------
-
-    if( poOpenInfo->fp != NULL )
-    {
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Check identification string and usage
-    //  -------------------------------------------------------------------
-
-    if( ! Identify( poOpenInfo ) )
-    {
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Create a GeoRaster wrapper object
-    //  -------------------------------------------------------------------
-
-    GeoRasterWrapper* poGRW = GeoRasterWrapper::Open(
-            poOpenInfo->pszFilename,
-            poOpenInfo->eAccess == GA_Update );
-
-    if( ! poGRW )
-    {
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Create a corresponding GDALDataset
-    //  -------------------------------------------------------------------
-
-    GeoRasterDataset *poGRD;
-
-    poGRD = new GeoRasterDataset();
-
-    if( ! poGRD )
-    {
-        return NULL;
-    }
-
-    poGRD->eAccess     = poOpenInfo->eAccess;
-    poGRD->poGeoRaster = poGRW;
-
-    //  -------------------------------------------------------------------
-    //  List Subdatasets
-    //  -------------------------------------------------------------------
-
-    if( ! poGRW->bUniqueFound )
-    {
-        if( poGRD->eAccess == GA_ReadOnly )
-        {
-            poGRD->SetSubdatasets( poGRW );
-
-            if( CSLCount( poGRD->papszSubdatasets ) == 0 )
-            {
-                delete poGRD;
-                poGRD = NULL;
-            }
-        }
-        return (GDALDataset*) poGRD;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Assign GeoRaster information
-    //  -------------------------------------------------------------------
-
-    poGRD->poGeoRaster   = poGRW;
-    poGRD->nRasterXSize  = poGRW->nRasterColumns;
-    poGRD->nRasterYSize  = poGRW->nRasterRows;
-    poGRD->nBands        = poGRW->nRasterBands;
-
-    if( poGRW->bIsReferenced )
-    {
-        poGRD->adfGeoTransform[1] = poGRW->dfXCoefficient[0];
-        poGRD->adfGeoTransform[2] = poGRW->dfXCoefficient[1];
-        poGRD->adfGeoTransform[0] = poGRW->dfXCoefficient[2];
-        poGRD->adfGeoTransform[4] = poGRW->dfYCoefficient[0];
-        poGRD->adfGeoTransform[5] = poGRW->dfYCoefficient[1];
-        poGRD->adfGeoTransform[3] = poGRW->dfYCoefficient[2];
-    }
-
-    //  -------------------------------------------------------------------
-    //  Copy RPC values to RPC metadata domain
-    //  -------------------------------------------------------------------
-
-    if( poGRW->phRPC )
-    {
-        char **papszRPC_MD = RPCInfoToMD( poGRW->phRPC );
-        char **papszSanitazed = NULL;
-
-        int i = 0;
-        int n = CSLCount( papszRPC_MD );
-
-        for( i = 0; i < n; i++ )
-        {
-            if ( EQUALN( papszRPC_MD[i], "MIN_LAT", 7 )  ||
-                 EQUALN( papszRPC_MD[i], "MIN_LONG", 8 ) ||
-                 EQUALN( papszRPC_MD[i], "MAX_LAT", 7 )  ||
-                 EQUALN( papszRPC_MD[i], "MAX_LONG", 8 ) )
-            {
-                continue;
-            }
-            papszSanitazed = CSLAddString( papszSanitazed, papszRPC_MD[i] );
-        }
-
-        poGRD->SetMetadata( papszSanitazed, "RPC" );
-
-        CSLDestroy( papszRPC_MD );
-        CSLDestroy( papszSanitazed );
-    }
-
-    //  -------------------------------------------------------------------
-    //  Load mask band
-    //  -------------------------------------------------------------------
-
-    poGRW->bHasBitmapMask = EQUAL( "TRUE", CPLGetXMLValue( poGRW->phMetadata,
-                          "layerInfo.objectLayer.bitmapMask", "FALSE" ) );
-
-    if( poGRW->bHasBitmapMask )
-    {
-        poGRD->poMaskBand = new GeoRasterRasterBand( poGRD, 0, DEFAULT_BMP_MASK );
-    }
-    
-    //  -------------------------------------------------------------------
-    //  Check for filter Nodata environment variable, default is YES
-    //  -------------------------------------------------------------------
-
-    const char *pszGEOR_FILTER_NODATA =
-        CPLGetConfigOption( "GEOR_FILTER_NODATA_VALUES", "NO" );
-
-    if( ! EQUAL(pszGEOR_FILTER_NODATA, "NO") )
-    {
-        poGRD->bApplyNoDataArray = true;
-    }
-    //  -------------------------------------------------------------------
-    //  Create bands
-    //  -------------------------------------------------------------------
-
-    int i = 0;
-    int nBand = 0;
-
-    for( i = 0; i < poGRD->nBands; i++ )
-    {
-        nBand = i + 1;
-        poGRD->SetBand( nBand, new GeoRasterRasterBand( poGRD, nBand, 0 ) );
-    }
-
-    //  -------------------------------------------------------------------
-    //  Set IMAGE_STRUCTURE metadata information
-    //  -------------------------------------------------------------------
-
-    if( poGRW->nBandBlockSize == 1 )
-    {
-        poGRD->SetMetadataItem( "INTERLEAVE", "BAND", "IMAGE_STRUCTURE" );
-    }
-    else
-    {
-        if( EQUAL( poGRW->sInterleaving.c_str(), "BSQ" ) )
-        {
-            poGRD->SetMetadataItem( "INTERLEAVE", "BAND", "IMAGE_STRUCTURE" );
-        }
-        else if( EQUAL( poGRW->sInterleaving.c_str(), "BIP" ) )
-        {
-            poGRD->SetMetadataItem( "INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE" );
-        }
-        else if( EQUAL( poGRW->sInterleaving.c_str(), "BIL" ) )
-        {
-            poGRD->SetMetadataItem( "INTERLEAVE", "LINE", "IMAGE_STRUCTURE" );
-        }
-    }
-
-    poGRD->SetMetadataItem( "COMPRESSION", CPLGetXMLValue( poGRW->phMetadata,
-        "rasterInfo.compression.type", "NONE" ), "IMAGE_STRUCTURE" );
-
-    if( EQUALN( poGRW->sCompressionType.c_str(), "JPEG", 4 ) )
-    {
-        poGRD->SetMetadataItem( "COMPRESS_QUALITY",
-            CPLGetXMLValue( poGRW->phMetadata,
-            "rasterInfo.compression.quality", "0" ), "IMAGE_STRUCTURE" );
-    }
-
-    if( EQUAL( poGRW->sCellDepth.c_str(), "1BIT" ) )
-    {
-        poGRD->SetMetadataItem( "NBITS", "1", "IMAGE_STRUCTURE" );
-    }
-
-    if( EQUAL( poGRW->sCellDepth.c_str(), "2BIT" ) )
-    {
-        poGRD->SetMetadataItem( "NBITS", "2", "IMAGE_STRUCTURE" );
-    }
-
-    if( EQUAL( poGRW->sCellDepth.c_str(), "4BIT" ) )
-    {
-        poGRD->SetMetadataItem( "NBITS", "4", "IMAGE_STRUCTURE" );
-    }
-
-    //  -------------------------------------------------------------------
-    //  Set Metadata on "ORACLE" domain
-    //  -------------------------------------------------------------------
-
-    char* pszDoc = CPLSerializeXMLTree( poGRW->phMetadata );
-
-    poGRD->SetMetadataItem( "TABLE_NAME", CPLSPrintf( "%s%s",
-        poGRW->sSchema.c_str(),
-        poGRW->sTable.c_str()), "ORACLE" );
-
-    poGRD->SetMetadataItem( "COLUMN_NAME",
-        poGRW->sColumn.c_str(), "ORACLE" );
-
-    poGRD->SetMetadataItem( "RDT_TABLE_NAME",
-        poGRW->sDataTable.c_str(), "ORACLE" );
-
-    poGRD->SetMetadataItem( "RASTER_ID", CPLSPrintf( "%d",
-        poGRW->nRasterId ), "ORACLE" );
-
-    poGRD->SetMetadataItem( "SRID", CPLSPrintf( "%d",
-        poGRW->nSRID ), "ORACLE" );
-
-    poGRD->SetMetadataItem( "WKT", poGRW->sWKText.c_str(), "ORACLE" );
-
-    poGRD->SetMetadataItem( "METADATA", pszDoc, "ORACLE" );
-
-    CPLFree( pszDoc );
-
-    //  -------------------------------------------------------------------
-    //  Return a GDALDataset
-    //  -------------------------------------------------------------------
-
-    return (GDALDataset*) poGRD;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     Create()
-//  ---------------------------------------------------------------------------
-
-GDALDataset *GeoRasterDataset::Create( const char *pszFilename,
-                                       int nXSize,
-                                       int nYSize,
-                                       int nBands, 
-                                       GDALDataType eType,
-                                       char **papszOptions )
-{
-    //  -------------------------------------------------------------------
-    //  Check for supported Data types
-    //  -------------------------------------------------------------------
-
-    const char* pszCellDepth = OWSetDataType( eType );
-
-    if( EQUAL( pszCellDepth, "Unknown" ) )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-            "Attempt to create GeoRaster with unsupported data type (%s)",
-            GDALGetDataTypeName( eType ) );
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Open the Dataset
-    //  -------------------------------------------------------------------
-
-    GeoRasterDataset* poGRD = NULL;
-
-    poGRD = (GeoRasterDataset*) GDALOpen( pszFilename, GA_Update );
-
-    if( ! poGRD )
-    {
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Get the GeoRaster
-    //  -------------------------------------------------------------------
-
-    GeoRasterWrapper* poGRW = poGRD->poGeoRaster;
-
-    if( ! poGRW )
-    {
-        delete poGRD;
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Set basic information and default values
-    //  -------------------------------------------------------------------
-
-    poGRW->nRasterColumns   = nXSize;
-    poGRW->nRasterRows      = nYSize;
-    poGRW->nRasterBands     = nBands;
-    poGRW->sCellDepth       = pszCellDepth;
-    poGRW->nRowBlockSize    = DEFAULT_BLOCK_ROWS;
-    poGRW->nColumnBlockSize = DEFAULT_BLOCK_COLUMNS;
-    poGRW->nBandBlockSize   = 1;
-
-    if( poGRW->bUniqueFound )
-    {
-        poGRW->PrepareToOverwrite();
-    }
-
-    //  -------------------------------------------------------------------
-    //  Check the create options to use in initialization
-    //  -------------------------------------------------------------------
-
-    const char* pszFetched  = "";
-    char* pszDescription    = NULL;
-    char* pszInsert         = NULL;
-    int   nQuality          = -1;
-
-    if( ! poGRW->sTable.empty() )
-    {
-        pszFetched = CSLFetchNameValue( papszOptions, "DESCRIPTION" );
-
-        if( pszFetched )
-        {
-            pszDescription  = CPLStrdup( pszFetched );
-        }
-    }
-
-    if( poGRW->sTable.empty() )
-    {
-        poGRW->sTable = "GDAL_IMPORT";
-        poGRW->sDataTable = "GDAL_RDT";
-    }
-
-    if( poGRW->sColumn.empty() )
-    {
-        poGRW->sColumn = "RASTER";
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "INSERT" );
-
-    if( pszFetched )
-    {
-        pszInsert = CPLStrdup( pszFetched );
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKXSIZE" );
-
-    if( pszFetched )
-    {
-        poGRW->nColumnBlockSize = atoi( pszFetched );
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKYSIZE" );
-
-    if( pszFetched )
-    {
-        poGRW->nRowBlockSize = atoi( pszFetched );
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "NBITS" );
-
-    if( pszFetched != NULL )
-    {
-        poGRW->sCellDepth = CPLSPrintf( "%dBIT", atoi( pszFetched ) );
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "COMPRESS" );
-
-    if( pszFetched != NULL &&
-        ( EQUALN( pszFetched, "JPEG", 4 ) ||
-          EQUAL( pszFetched, "DEFLATE" ) ) )
-    {
-        poGRW->sCompressionType = pszFetched;
-    }
-    else
-    {
-        poGRW->sCompressionType = "NONE";
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "QUALITY" );
-
-    if( pszFetched )
-    {
-        poGRW->nCompressQuality = atoi( pszFetched );
-        nQuality = poGRW->nCompressQuality;
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "INTERLEAVE" );
-
-    bool bInterleve_ind = false;
-
-    if( pszFetched )
-    {
-        bInterleve_ind = true;
-
-        if( EQUAL( pszFetched, "BAND" ) ||  EQUAL( pszFetched, "BSQ" ) )
-        {
-            poGRW->sInterleaving = "BSQ";
-        }
-        if( EQUAL( pszFetched, "LINE" ) ||  EQUAL( pszFetched, "BIL" ) )
-        {
-            poGRW->sInterleaving = "BIL";
-        }
-        if( EQUAL( pszFetched, "PIXEL" ) ||  EQUAL( pszFetched, "BIP" ) )
-        {
-            poGRW->sInterleaving = "BIP";
-        }
-    }
-    else
-    {
-        if( EQUAL( poGRW->sCompressionType.c_str(), "NONE" ) == false )
-        {
-            poGRW->sInterleaving = "BIP";
-        }
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKBSIZE" );
-
-    if( pszFetched )
-    {
-        poGRW->nBandBlockSize = atoi( pszFetched );
-    }
-    else
-    {
-        if( ! EQUAL( poGRW->sCompressionType.c_str(), "NONE" ) &&
-          ( nBands == 3 || nBands == 4 ) )
-        {
-            poGRW->nBandBlockSize = nBands;
-        }
-    }
-
-    if( bInterleve_ind == false && 
-      ( poGRW->nBandBlockSize == 3 || poGRW->nBandBlockSize == 4 ) ) 
-    {
-      poGRW->sInterleaving = "BIP";
-    }
-
-    if( EQUALN( poGRW->sCompressionType.c_str(), "JPEG", 4 ) )
-    {
-        if( ! EQUAL( poGRW->sInterleaving.c_str(), "BIP" ) )
-        {
-            CPLError( CE_Warning, CPLE_IllegalArg, 
-                "compress=JPEG assumes interleave=BIP" );
-            poGRW->sInterleaving = "BIP";
-        }
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKING" );
-
-    if( pszFetched )
-    {
-        if( EQUAL( pszFetched, "NO" ) )
-        {
-            poGRW->bBlocking = false;
-        }
-
-        if( EQUAL( pszFetched, "OPTIMALPADDING" ) )
-        {
-            if( poGRW->poConnection->GetVersion() < 11 )
-            {
-                CPLError( CE_Warning, CPLE_IllegalArg, 
-                    "BLOCKING=OPTIMALPADDING not supported on Oracle older than 11g" );
-            }
-            else
-            {
-                poGRW->bAutoBlocking = true;
-                poGRW->bBlocking = true;
-            }
-        }
-    }
-
-    //  -------------------------------------------------------------------
-    //  Validate options
-    //  -------------------------------------------------------------------
-
-    if( pszDescription && poGRW->bUniqueFound )
-    {
-        CPLError( CE_Failure, CPLE_IllegalArg, 
-            "Option (DESCRIPTION) cannot be used on a existing GeoRaster." );
-        delete poGRD;
-        return NULL;
-    }
-
-    if( pszInsert && poGRW->bUniqueFound )
-    {
-        CPLError( CE_Failure, CPLE_IllegalArg, 
-            "Option (INSERT) cannot be used on a existing GeoRaster." );
-        delete poGRD;
-        return NULL;
-    }
-
-    /* Compression JPEG-B is deprecated. It should be able to read but to
-     * to create new GeoRaster on databases with that compression option.
-     *
-     * TODO: Remove that options on next release.
-     */
-    if( EQUAL( poGRW->sCompressionType.c_str(), "JPEG-B" ) )
-    {
-        CPLError( CE_Failure, CPLE_IllegalArg,
-            "Option (COMPRESS=%s) is deprecated and cannot be used.",
-            poGRW->sCompressionType.c_str() );
-        delete poGRD;
-        return NULL;
-    }
-
-    if( EQUAL( poGRW->sCompressionType.c_str(), "JPEG-F" ) )
-    {
-        /* JPEG-F can only compress byte data type
-         */
-        if( eType != GDT_Byte )
-        {
-            CPLError( CE_Failure, CPLE_IllegalArg, 
-                "Option (COMPRESS=%s) can only be used with Byte data type.",
-                poGRW->sCompressionType.c_str() );
-            delete poGRD;
-            return NULL;
-        }
-
-        /* JPEG-F can compress one band per block or 3 for RGB
-         * or 4 for RGBA.
-         */
-        if( ( poGRW->nBandBlockSize != 1 &&
-              poGRW->nBandBlockSize != 3 &&
-              poGRW->nBandBlockSize != 4 ) ||
-          ( ( poGRW->nBandBlockSize != 1 &&
-            ( poGRW->nBandBlockSize != poGRW->nRasterBands ) ) ) )
-        {
-            CPLError( CE_Failure, CPLE_IllegalArg,
-                "Option (COMPRESS=%s) requires BLOCKBSIZE to be 1 (for any "
-                "number of bands), 3 (for 3 bands RGB) and 4 (for 4 bands RGBA).",
-                poGRW->sCompressionType.c_str() );
-            delete poGRD;
-            return NULL;
-        }
-
-        /* There is a limite on how big a compressed block can be.
-         */
-        if( ( poGRW->nColumnBlockSize * 
-              poGRW->nRowBlockSize *
-              poGRW->nBandBlockSize *
-              ( GDALGetDataTypeSize( eType ) / 8 ) ) > ( 50 * 1024 * 1024 ) )
-        {
-            CPLError( CE_Failure, CPLE_IllegalArg, 
-                "Option (COMPRESS=%s) each data block must not exceed 50Mb. "
-                "Consider reducing BLOCK{X,Y,B}XSIZE.",
-                poGRW->sCompressionType.c_str() );
-            delete poGRD;
-            return NULL;
-        }
-    }
-
-    if( EQUAL( poGRW->sCompressionType.c_str(), "DEFLATE" ) )
-    {
-        if( ( poGRW->nColumnBlockSize * 
-              poGRW->nRowBlockSize *
-              poGRW->nBandBlockSize *
-              ( GDALGetDataTypeSize( eType ) / 8 ) ) > ( 1024 * 1024 * 1024 ) )
-        {
-            CPLError( CE_Failure, CPLE_IllegalArg, 
-                "For (COMPRESS=%s) each data block must not exceed 1Gb. "
-                "Consider reducing BLOCK{X,Y,B}XSIZE.",
-                poGRW->sCompressionType.c_str() );
-            delete poGRD;
-            return NULL;
-        }
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "OBJECTTABLE" );
-
-    if( pszFetched )
-    {
-        int nVersion = poGRW->poConnection->GetVersion();
-        if( nVersion <= 11 )
-        {
-            CPLError( CE_Failure, CPLE_IllegalArg, 
-                "Driver create-option OBJECTTABLE not "
-                "supported on Oracle %d", nVersion );
-            delete poGRD;
-            return NULL;
-        }
-    }
-
-    poGRD->poGeoRaster->bCreateObjectTable = (bool)
-        CSLFetchBoolean( papszOptions, "OBJECTTABLE", FALSE );
-
-    //  -------------------------------------------------------------------
-    //  Create a SDO_GEORASTER object on the server
-    //  -------------------------------------------------------------------
-
-    bool bSucced = poGRW->Create( pszDescription, pszInsert, poGRW->bUniqueFound );
-
-    CPLFree( pszInsert );
-    CPLFree( pszDescription );
-
-    if( ! bSucced )
-    {
-        delete poGRD;
-        return NULL;
-    }
-    
-    //  -------------------------------------------------------------------
-    //  Prepare an identification string
-    //  -------------------------------------------------------------------
-
-    char szStringId[OWTEXT];
-
-    strcpy( szStringId, CPLSPrintf( "georaster:%s,%s,%s,%s,%d",
-        poGRW->poConnection->GetUser(),
-        poGRW->poConnection->GetPassword(),
-        poGRW->poConnection->GetServer(),
-        poGRW->sDataTable.c_str(),
-        poGRW->nRasterId ) );
-
-    delete poGRD;
-
-    poGRD = (GeoRasterDataset*) GDALOpen( szStringId, GA_Update );
-
-    if( ! poGRD )
-    {
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Load aditional options
-    //  -------------------------------------------------------------------
-
-    pszFetched = CSLFetchNameValue( papszOptions, "VATNAME" );
-
-    if( pszFetched )
-    {
-        poGRW->sValueAttributeTab = pszFetched;
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "SRID" );
-
-    if( pszFetched )
-    {
-        poGRD->bForcedSRID = true;
-        poGRD->poGeoRaster->SetGeoReference( atoi( pszFetched ) );
-    }
-
-    poGRD->poGeoRaster->bGenSpatialIndex = (bool)
-        CSLFetchBoolean( papszOptions, "SPATIALEXTENT", TRUE );
-
-    pszFetched = CSLFetchNameValue( papszOptions, "EXTENTSRID" );
-
-    if( pszFetched )
-    {
-        poGRD->poGeoRaster->nExtentSRID = atoi( pszFetched );
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "COORDLOCATION" );
-
-    if( pszFetched )
-    {
-        if( EQUAL( pszFetched, "CENTER" ) )
-        {
-            poGRD->poGeoRaster->eModelCoordLocation = MCL_CENTER;
-        }
-        else if( EQUAL( pszFetched, "UPPERLEFT" ) )
-        {
-            poGRD->poGeoRaster->eModelCoordLocation = MCL_UPPERLEFT;
-        }
-        else 
-        {
-            CPLError( CE_Warning, CPLE_IllegalArg, 
-                "Incorrect COORDLOCATION (%s)", pszFetched );
-        }
-    }
-
-    if ( nQuality > 0 )
-    {
-        poGRD->poGeoRaster->nCompressQuality = nQuality;
-    }
-
-
-    pszFetched = CSLFetchNameValue( papszOptions, "GENPYRAMID" );
-
-    if( pszFetched != NULL )
-    {
-        if (!(EQUAL(pszFetched, "NN") ||
-              EQUAL(pszFetched, "BILINEAR") ||
-              EQUAL(pszFetched, "BIQUADRATIC") ||
-              EQUAL(pszFetched, "CUBIC") ||
-              EQUAL(pszFetched, "AVERAGE4") ||
-              EQUAL(pszFetched, "AVERAGE16")))
-        {
-            CPLError( CE_Warning, CPLE_IllegalArg, "Wrong resample method for pyramid (%s)", pszFetched);
-        }
-
-        poGRD->poGeoRaster->bGenPyramid = true;
-        poGRD->poGeoRaster->sPyramidResampling = pszFetched;
-    }
-
-    pszFetched = CSLFetchNameValue( papszOptions, "GENPYRLEVELS" );
-
-    if( pszFetched != NULL )
-    {
-        poGRD->poGeoRaster->bGenPyramid = true;
-        poGRD->poGeoRaster->nPyramidLevels = atoi(pszFetched);
-    }
-
-    //  -------------------------------------------------------------------
-    //  Return a new Dataset
-    //  -------------------------------------------------------------------
-
-    return (GDALDataset*) poGRD;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                 CreateCopy()
-//  ---------------------------------------------------------------------------
-
-GDALDataset *GeoRasterDataset::CreateCopy( const char* pszFilename,
-                                           GDALDataset* poSrcDS,
-                                           int bStrict,
-                                           char** papszOptions,
-                                           GDALProgressFunc pfnProgress,
-                                           void* pProgressData )
-{
-    (void) bStrict;
-
-    int nBands = poSrcDS->GetRasterCount();
-    if (nBands == 0)
-    {
-        CPLError( CE_Failure, CPLE_NotSupported, 
-        "GeoRaster driver does not support source dataset with zero band.\n");
-        return NULL;
-    }
-
-    GDALRasterBand* poBand = poSrcDS->GetRasterBand( 1 );
-    GDALDataType    eType  = poBand->GetRasterDataType();
-
-    //  -----------------------------------------------------------
-    //  Create a GeoRaster on the server or select one to overwrite
-    //  -----------------------------------------------------------
-
-    GeoRasterDataset *poDstDS;
-
-    poDstDS = (GeoRasterDataset *) GeoRasterDataset::Create( pszFilename,
-        poSrcDS->GetRasterXSize(),
-        poSrcDS->GetRasterYSize(),
-        poSrcDS->GetRasterCount(),
-        eType, papszOptions );
-
-    if( poDstDS == NULL )
-    {
-        return NULL;
-    }
-
-    //  -----------------------------------------------------------
-    //  Copy information to the dataset
-    //  -----------------------------------------------------------
-
-    double adfTransform[6];
-
-    if ( poSrcDS->GetGeoTransform( adfTransform ) == CE_None )
-    {
-        if ( ! ( adfTransform[0] == 0.0 && 
-                 adfTransform[1] == 1.0 &&
-                 adfTransform[2] == 0.0 &&
-                 adfTransform[3] == 0.0 &&
-                 adfTransform[4] == 0.0 &&
-                 adfTransform[5] == 1.0 ) ) 
-        {
-            poDstDS->SetGeoTransform( adfTransform );
-        }
-    }
-
-    if( ! poDstDS->bForcedSRID ) /* forced by create option SRID */
-    {
-        poDstDS->SetProjection( poSrcDS->GetProjectionRef() );
-    }
-
-    // --------------------------------------------------------------------
-    //      Copy RPC 
-    // --------------------------------------------------------------------
-
-    char **papszRPCMetadata = GDALGetMetadata( poSrcDS, "RPC" );
-
-    if ( papszRPCMetadata != NULL )
-    {
-        poDstDS->poGeoRaster->phRPC = (GDALRPCInfo*) VSIMalloc( sizeof(GDALRPCInfo) );
-        GDALExtractRPCInfo( papszRPCMetadata, poDstDS->poGeoRaster->phRPC );
-    }
-
-    // --------------------------------------------------------------------
-    //      Copy information to the raster bands
-    // --------------------------------------------------------------------
-
-    int    bHasNoDataValue = FALSE;
-    double dfNoDataValue = 0.0;
-    double dfMin = 0.0, dfMax = 0.0, dfStdDev = 0.0, dfMean = 0.0;
-    double dfMedian = 0.0, dfMode = 0.0;
-    int    iBand = 0;
-
-    for( iBand = 1; iBand <= poSrcDS->GetRasterCount(); iBand++ )
-    {
-        GDALRasterBand*      poSrcBand = poSrcDS->GetRasterBand( iBand );
-        GeoRasterRasterBand* poDstBand = (GeoRasterRasterBand*) 
-                                         poDstDS->GetRasterBand( iBand );
-
-        // ----------------------------------------------------------------
-        //  Copy Color Table
-        // ----------------------------------------------------------------
-
-        GDALColorTable* poColorTable = poSrcBand->GetColorTable(); 
-
-        if( poColorTable )
-        {
-            poDstBand->SetColorTable( poColorTable );
-        }
-
-        // ----------------------------------------------------------------
-        //  Copy statitics information, without median and mode
-        // ----------------------------------------------------------------
-
-        if( poSrcBand->GetStatistics( false, false, &dfMin, &dfMax,
-            &dfMean, &dfStdDev ) == CE_None )
-        {
-            poDstBand->SetStatistics( dfMin, dfMax, dfMean, dfStdDev );
-
-            /* That will not be recorded in the GeoRaster metadata since it
-             * doesn't have median and mode, so those values are only useful
-             * at runtime.
-             */
-        }
-
-        // ----------------------------------------------------------------
-        //  Copy statitics metadata information, including median and mode
-        // ----------------------------------------------------------------
-
-        const char *pszMin     = poSrcBand->GetMetadataItem( "STATISTICS_MINIMUM" );
-        const char *pszMax     = poSrcBand->GetMetadataItem( "STATISTICS_MAXIMUM" );
-        const char *pszMean    = poSrcBand->GetMetadataItem( "STATISTICS_MEAN" );
-        const char *pszMedian  = poSrcBand->GetMetadataItem( "STATISTICS_MEDIAN" );
-        const char *pszMode    = poSrcBand->GetMetadataItem( "STATISTICS_MODE" );
-        const char *pszStdDev  = poSrcBand->GetMetadataItem( "STATISTICS_STDDEV" );
-        const char *pszSkipFX  = poSrcBand->GetMetadataItem( "STATISTICS_SKIPFACTORX" );
-        const char *pszSkipFY  = poSrcBand->GetMetadataItem( "STATISTICS_SKIPFACTORY" );
-
-        if ( pszMin    != NULL && pszMax  != NULL && pszMean   != NULL &&
-             pszMedian != NULL && pszMode != NULL && pszStdDev != NULL )
-        {
-            dfMin        = CPLScanDouble( pszMin, MAX_DOUBLE_STR_REP );
-            dfMax        = CPLScanDouble( pszMax, MAX_DOUBLE_STR_REP );
-            dfMean       = CPLScanDouble( pszMean, MAX_DOUBLE_STR_REP );
-            dfMedian     = CPLScanDouble( pszMedian, MAX_DOUBLE_STR_REP );
-            dfMode       = CPLScanDouble( pszMode, MAX_DOUBLE_STR_REP );
-
-            if ( ! ( ( dfMin    > dfMax ) ||
-                     ( dfMean   > dfMax ) || ( dfMean   < dfMin ) ||
-                     ( dfMedian > dfMax ) || ( dfMedian < dfMin ) ||
-                     ( dfMode   > dfMax ) || ( dfMode   < dfMin ) ) )
-            {
-                if ( ! pszSkipFX )
-                {
-                    pszSkipFX = pszSkipFY != NULL ? pszSkipFY : "1";
-                }
-
-                poDstBand->poGeoRaster->SetStatistics( iBand,
-                                                       pszMin, pszMax, pszMean, 
-                                                       pszMedian, pszMode,
-                                                       pszStdDev, pszSkipFX );
-            }
-        }
-
-        // ----------------------------------------------------------------
-        //  Copy Raster Attribute Table (RAT)
-        // ----------------------------------------------------------------
-
-        GDALRasterAttributeTableH poRAT = GDALGetDefaultRAT( poSrcBand );
-
-        if( poRAT != NULL )
-        {
-            poDstBand->SetDefaultRAT( (GDALRasterAttributeTable*) poRAT );
-        }
-
-        // ----------------------------------------------------------------
-        //  Copy NoData Value
-        // ----------------------------------------------------------------
-
-        dfNoDataValue = poSrcBand->GetNoDataValue( &bHasNoDataValue );
-
-        if( bHasNoDataValue )
-        {
-            poDstBand->SetNoDataValue( dfNoDataValue );
-        }
-    }
-
-    // --------------------------------------------------------------------
-    //  Copy actual imagery.
-    // --------------------------------------------------------------------
-
-    int nXSize = poDstDS->GetRasterXSize();
-    int nYSize = poDstDS->GetRasterYSize();
-
-    int nBlockXSize = 0;
-    int nBlockYSize = 0;
-
-    poDstDS->GetRasterBand( 1 )->GetBlockSize( &nBlockXSize, &nBlockYSize );
-
-    void *pData = VSIMalloc( nBlockXSize * nBlockYSize *
-        GDALGetDataTypeSize( eType ) / 8 );
-
-    if( pData == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory,
-            "GeoRaster::CreateCopy : Out of memory " );
-        delete poDstDS;
-        return NULL;
-    }
-
-    int iYOffset = 0;
-    int iXOffset = 0;
-    int iXBlock  = 0;
-    int iYBlock  = 0;
-    int nBlockCols = 0;
-    int nBlockRows = 0;
-    CPLErr eErr = CE_None;
-
-    int nPixelSize = GDALGetDataTypeSize( 
-        poSrcDS->GetRasterBand(1)->GetRasterDataType() ) / 8;
-
-    if( poDstDS->poGeoRaster->nBandBlockSize == 1)
-    {
-        // ----------------------------------------------------------------
-        //  Band order
-        // ----------------------------------------------------------------
-
-        int nBandCount = poSrcDS->GetRasterCount();
-
-        for( iBand = 1; iBand <= nBandCount; iBand++ )
-        {
-            GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand );
-            GDALRasterBand *poDstBand = poDstDS->GetRasterBand( iBand );
-
-            for( iYOffset = 0, iYBlock = 0;
-                 iYOffset < nYSize;
-                 iYOffset += nBlockYSize, iYBlock++ )
-            {
-
-                for( iXOffset = 0, iXBlock = 0;
-                     iXOffset < nXSize;
-                     iXOffset += nBlockXSize, iXBlock++ )
-                {
-
-                    nBlockCols = MIN( nBlockXSize, nXSize - iXOffset );
-                    nBlockRows = MIN( nBlockYSize, nYSize - iYOffset );
-
-                    eErr = poSrcBand->RasterIO( GF_Read,
-                        iXOffset, iYOffset,
-                        nBlockCols, nBlockRows, pData,
-                        nBlockCols, nBlockRows, eType,
-                        nPixelSize,
-                        nPixelSize * nBlockXSize );
-
-                    if( eErr != CE_None )
-                    {
-                        return NULL;
-                    }
-
-                    eErr = poDstBand->WriteBlock( iXBlock, iYBlock, pData );
-
-                    if( eErr != CE_None )
-                    {
-                        return NULL;
-                    }
-                }
-
-                if( ( eErr == CE_None ) && ( ! pfnProgress(
-                      ( ( iBand - 1) / (float) nBandCount ) +
-                      ( iYOffset + nBlockRows ) / (float) (nYSize * nBandCount),
-                      NULL, pProgressData ) ) )
-                {
-                    eErr = CE_Failure;
-                    CPLError( CE_Failure, CPLE_UserInterrupt,
-                        "User terminated CreateCopy()" );
-                }
-            }
-        }
-    }
-    else
-    {
-        // ----------------------------------------------------------------
-        //  Block order
-        // ----------------------------------------------------------------
-
-        poDstDS->poGeoRaster->SetWriteOnly( true );
-
-        for( iYOffset = 0, iYBlock = 0;
-             iYOffset < nYSize;
-             iYOffset += nBlockYSize, iYBlock++ )
-        {
-            for( iXOffset = 0, iXBlock = 0;
-                 iXOffset < nXSize;
-                 iXOffset += nBlockXSize, iXBlock++ )
-            {
-                nBlockCols = MIN( nBlockXSize, nXSize - iXOffset );
-                nBlockRows = MIN( nBlockYSize, nYSize - iYOffset );
-
-                for( iBand = 1;
-                     iBand <= poSrcDS->GetRasterCount();
-                     iBand++ )
-                {
-                    GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand );
-                    GDALRasterBand *poDstBand = poDstDS->GetRasterBand( iBand );
-
-                    eErr = poSrcBand->RasterIO( GF_Read,
-                        iXOffset, iYOffset,
-                        nBlockCols, nBlockRows, pData,
-                        nBlockCols, nBlockRows, eType,
-                        nPixelSize,
-                        nPixelSize * nBlockXSize );
-
-                    if( eErr != CE_None )
-                    {
-                        return NULL;
-                    }
-
-                    eErr = poDstBand->WriteBlock( iXBlock, iYBlock, pData );
-
-                    if( eErr != CE_None )
-                    {
-                        return NULL;
-                    }
-                }
-
-            }
-
-            if( ( eErr == CE_None ) && ( ! pfnProgress(
-                ( iYOffset + nBlockRows ) / (double) nYSize, NULL,
-                    pProgressData ) ) )
-            {
-                eErr = CE_Failure;
-                CPLError( CE_Failure, CPLE_UserInterrupt,
-                    "User terminated CreateCopy()" );
-            }
-        }
-    }
-
-    CPLFree( pData );
-
-    // --------------------------------------------------------------------
-    //      Finalize
-    // --------------------------------------------------------------------
-
-    poDstDS->FlushCache();
-
-    if( pfnProgress )
-    {
-        printf( "Ouput dataset: (georaster:%s/%s@%s,%s,%d) on %s%s,%s\n",
-            poDstDS->poGeoRaster->poConnection->GetUser(),
-            poDstDS->poGeoRaster->poConnection->GetPassword(),
-            poDstDS->poGeoRaster->poConnection->GetServer(),
-            poDstDS->poGeoRaster->sDataTable.c_str(),
-            poDstDS->poGeoRaster->nRasterId,
-            poDstDS->poGeoRaster->sSchema.c_str(),
-            poDstDS->poGeoRaster->sTable.c_str(),
-            poDstDS->poGeoRaster->sColumn.c_str() );
-    }
-
-    return poDstDS;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                  IRasterIO()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::IRasterIO( GDALRWFlag eRWFlag,
-                                    int nXOff, int nYOff, int nXSize, int nYSize,
-                                    void *pData, int nBufXSize, int nBufYSize,
-                                    GDALDataType eBufType,
-                                    int nBandCount, int *panBandMap,
-                                    int nPixelSpace, int nLineSpace, int nBandSpace )
-
-{
-    if( poGeoRaster->nBandBlockSize > 1 )
-    {
-        return GDALDataset::BlockBasedRasterIO( eRWFlag,
-            nXOff, nYOff, nXSize, nYSize,
-            pData, nBufXSize, nBufYSize, eBufType,
-            nBandCount, panBandMap, nPixelSpace,
-            nLineSpace, nBandSpace );
-    }
-    else
-    {
-        return GDALDataset::IRasterIO( eRWFlag,
-            nXOff, nYOff, nXSize, nYSize,
-            pData, nBufXSize, nBufYSize, eBufType,
-            nBandCount, panBandMap,
-            nPixelSpace, nLineSpace, nBandSpace );
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                 FlushCache()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterDataset::FlushCache()
-{
-    GDALDataset::FlushCache();
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            GetGeoTransform()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::GetGeoTransform( double *padfTransform )
-{
-    if( poGeoRaster->phRPC )
-    {
-        return CE_Failure;
-    }
-
-    if( poGeoRaster->nSRID == 0 )
-    {
-        return CE_Failure;
-    }
-    
-    memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 );
-
-    bGeoTransform = true;
-
-    return CE_None;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                           GetProjectionRef()
-//  ---------------------------------------------------------------------------
-
-const char* GeoRasterDataset::GetProjectionRef( void )
-{
-    if( poGeoRaster->phRPC )
-    {
-        return "";
-    }
-
-    if( ! poGeoRaster->bIsReferenced )
-    {
-        return "";
-    }
-
-    if( poGeoRaster->nSRID == UNKNOWN_CRS || poGeoRaster->nSRID == 0 )
-    {
-        return "";
-    }
-
-    if( pszProjection )
-    {
-        return pszProjection;
-    }
-
-    OGRSpatialReference oSRS;
-
-    // --------------------------------------------------------------------
-    // Check if the SRID is a valid EPSG code
-    // --------------------------------------------------------------------
-
-    if( oSRS.importFromEPSG( poGeoRaster->nSRID ) == OGRERR_NONE )
-    {
-        /*
-         * Ignores the WKT from Oracle and use the one from GDAL's
-         * EPSG tables. That would ensure that other drivers/software
-         * will recognizize the parameters.
-         */
-
-        if( oSRS.exportToWkt( &pszProjection ) == OGRERR_NONE )
-        {
-            return pszProjection;
-        }
-    }
-
-    // --------------------------------------------------------------------
-    // Try to interpreter the WKT text
-    // --------------------------------------------------------------------
-
-    char* pszWKText = CPLStrdup( poGeoRaster->sWKText );
-
-    if( ! ( oSRS.importFromWkt( &pszWKText ) == OGRERR_NONE && oSRS.GetRoot() ) )
-    {
-        return "";
-    }
-
-    // ----------------------------------------------------------------
-    // Decorate with EPSG Authority codes
-    // ----------------------------------------------------------------
-
-    oSRS.SetAuthority( oSRS.GetRoot()->GetValue(), "EPSG", poGeoRaster->nSRID );
-
-    int nSpher = OWParseEPSG( oSRS.GetAttrValue("GEOGCS|DATUM|SPHEROID") );
-
-    if( nSpher > 0 )
-    {
-        oSRS.SetAuthority( "GEOGCS|DATUM|SPHEROID", "EPSG", nSpher );
-    }
-
-    int nDatum = OWParseEPSG( oSRS.GetAttrValue("GEOGCS|DATUM") );
-
-    if( nDatum > 0 )
-    {
-        oSRS.SetAuthority( "GEOGCS|DATUM", "EPSG", nDatum );
-    }
-
-    // ----------------------------------------------------------------
-    // Checks for Projection info
-    // ----------------------------------------------------------------
-
-    const char *pszProjName = oSRS.GetAttrValue( "PROJECTION" );
-
-    if( pszProjName )
-    {
-        int nProj = OWParseEPSG( pszProjName );
-
-        // ----------------------------------------------------------------
-        // Decorate with EPSG Authority
-        // ----------------------------------------------------------------
-
-        if( nProj > 0 )
-        {
-            oSRS.SetAuthority( "PROJECTION", "EPSG", nProj );
-        }
-
-        // ----------------------------------------------------------------
-        // Translate projection names to GDAL's standards
-        // ----------------------------------------------------------------
-
-        if ( EQUAL( pszProjName, "Transverse Mercator" ) )
-        {
-            oSRS.SetProjection( SRS_PT_TRANSVERSE_MERCATOR );
-        }
-        else if ( EQUAL( pszProjName, "Albers Conical Equal Area" ) )
-        {
-            oSRS.SetProjection( SRS_PT_ALBERS_CONIC_EQUAL_AREA );
-        }
-        else if ( EQUAL( pszProjName, "Azimuthal Equidistant" ) )
-        {
-            oSRS.SetProjection( SRS_PT_AZIMUTHAL_EQUIDISTANT );
-        }
-        else if ( EQUAL( pszProjName, "Miller Cylindrical" ) )
-        {
-            oSRS.SetProjection( SRS_PT_MILLER_CYLINDRICAL );
-        }
-        else if ( EQUAL( pszProjName, "Hotine Oblique Mercator" ) )
-        {
-            oSRS.SetProjection( SRS_PT_HOTINE_OBLIQUE_MERCATOR );
-        }
-        else if ( EQUAL( pszProjName, "Wagner IV" ) )
-        {
-            oSRS.SetProjection( SRS_PT_WAGNER_IV );
-        }
-        else if ( EQUAL( pszProjName, "Wagner VII" ) )
-        {
-            oSRS.SetProjection( SRS_PT_WAGNER_VII );
-        }
-        else if ( EQUAL( pszProjName, "Eckert IV" ) )
-        {
-            oSRS.SetProjection( SRS_PT_ECKERT_IV );
-        }
-        else if ( EQUAL( pszProjName, "Eckert VI" ) )
-        {
-            oSRS.SetProjection( SRS_PT_ECKERT_VI );
-        }
-        else if ( EQUAL( pszProjName, "New Zealand Map Grid" ) )
-        {
-            oSRS.SetProjection( SRS_PT_NEW_ZEALAND_MAP_GRID );
-        }
-        else if ( EQUAL( pszProjName, "Lambert Conformal Conic" ) )
-        {
-            oSRS.SetProjection( SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP );
-            //?? One ot two parameters?
-        }
-        else if ( EQUAL( pszProjName, "Lambert Azimuthal Equal Area" ) )
-        {
-            oSRS.SetProjection( SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA );
-        }
-        else if ( EQUAL( pszProjName, "Van der Grinten" ) )
-        {
-            oSRS.SetProjection( SRS_PT_VANDERGRINTEN );
-        }
-        else if ( EQUAL(
-            pszProjName, "Lambert Conformal Conic (Belgium 1972)" ) )
-        {
-            oSRS.SetProjection( SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP_BELGIUM );
-        }
-        else if ( EQUAL( pszProjName, "Cylindrical Equal Area" ) )
-        {
-            oSRS.SetProjection( SRS_PT_CYLINDRICAL_EQUAL_AREA );
-        }
-        else if ( EQUAL( pszProjName, "Interrupted Goode Homolosine" ) )
-        {
-            oSRS.SetProjection( SRS_PT_GOODE_HOMOLOSINE );
-        }
-    }
-
-    oSRS.exportToWkt( &pszProjection );
-
-    return pszProjection;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            SetGeoTransform()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::SetGeoTransform( double *padfTransform )
-{
-    memcpy( adfGeoTransform, padfTransform, sizeof( double ) * 6 );
-
-    poGeoRaster->dfXCoefficient[0] = adfGeoTransform[1];
-    poGeoRaster->dfXCoefficient[1] = adfGeoTransform[2];
-    poGeoRaster->dfXCoefficient[2] = adfGeoTransform[0];
-    poGeoRaster->dfYCoefficient[0] = adfGeoTransform[4];
-    poGeoRaster->dfYCoefficient[1] = adfGeoTransform[5];
-    poGeoRaster->dfYCoefficient[2] = adfGeoTransform[3];
-
-    bGeoTransform = true;
-    
-    return CE_None;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              SetProjection()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::SetProjection( const char *pszProjString )
-{
-    OGRSpatialReference oSRS;
-
-    char* pszWKT = CPLStrdup( pszProjString );
-
-    OGRErr eOGRErr = oSRS.importFromWkt( &pszWKT );
-
-    if( eOGRErr != OGRERR_NONE )
-    {
-        poGeoRaster->SetGeoReference( DEFAULT_CRS );
-
-        return CE_Failure;
-    }
-
-    // --------------------------------------------------------------------
-    // Try to extract EPGS authority code
-    // --------------------------------------------------------------------
-
-    const char *pszAuthName = NULL, *pszAuthCode = NULL;
-
-    if( oSRS.IsGeographic() )
-    {
-        pszAuthName = oSRS.GetAuthorityName( "GEOGCS" );
-        pszAuthCode = oSRS.GetAuthorityCode( "GEOGCS" );
-    }
-    else if( oSRS.IsProjected() )
-    {
-        pszAuthName = oSRS.GetAuthorityName( "PROJCS" );
-        pszAuthCode = oSRS.GetAuthorityCode( "PROJCS" );
-    }
-
-    if( pszAuthName != NULL && pszAuthCode != NULL )
-    {
-        if( EQUAL( pszAuthName, "Oracle" ) || 
-            EQUAL( pszAuthName, "EPSG" ) )
-        {
-            poGeoRaster->SetGeoReference( atoi( pszAuthCode ) );
-            return CE_None;
-        }
-    }
-
-    // ----------------------------------------------------------------
-    // Convert SRS into old style format (SF-SQL 1.0)
-    // ----------------------------------------------------------------
-
-    OGRSpatialReference *poSRS2 = oSRS.Clone();
-    
-    poSRS2->StripCTParms();
-
-    double dfAngularUnits = poSRS2->GetAngularUnits( NULL );
-    
-    if( fabs(dfAngularUnits - 0.0174532925199433) < 0.0000000000000010 )
-    {
-        /* match the precision used on Oracle for that particular value */
-
-        poSRS2->SetAngularUnits( "Decimal Degree", 0.0174532925199433 );
-    }
-
-    char* pszCloneWKT = NULL;
-
-    if( poSRS2->exportToWkt( &pszCloneWKT ) != OGRERR_NONE )
-    {
-        delete poSRS2;
-        return CE_Failure;
-    }
-    
-    // --------------------------------------------------------------------
-    // Search by simplified WKT or insert it as a user defined
-    // --------------------------------------------------------------------
-
-    OWConnection* poConnection  = poGeoRaster->poConnection;
-    OWStatement* poStmt = NULL;
-    int nMaxSRID = 0;
-
-    poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "DECLARE\n"
-        "  MAX_SRID NUMBER := 0;\n"
-        "BEGIN\n"
-        "  SELECT SRID INTO MAX_SRID FROM MDSYS.CS_SRS WHERE WKTEXT = '%s';\n"
-        "  EXCEPTION\n"
-        "    WHEN no_data_found THEN\n"
-        "      SELECT MAX(SRID) INTO MAX_SRID FROM MDSYS.CS_SRS;\n"
-        "      MAX_SRID := MAX_SRID + 1;\n"
-        "      INSERT INTO MDSYS.CS_SRS (SRID, WKTEXT, CS_NAME)\n"
-        "        VALUES (MAX_SRID, '%s', '%s');\n"
-        "END;",
-            pszCloneWKT,
-            pszCloneWKT,
-            oSRS.GetRoot()->GetChild(0)->GetValue() ) );
-
-    poStmt->Define( &nMaxSRID );
-
-    CPLErr eError = CE_None;
-
-    if( poStmt->Execute() )
-    {
-        poGeoRaster->SetGeoReference( nMaxSRID ); //TODO change that method
-        poGeoRaster->sWKText = pszCloneWKT;
-    }
-    else
-    {
-        poGeoRaster->SetGeoReference( UNKNOWN_CRS );
-        poGeoRaster->sWKText = "";
-
-        CPLError( CE_Warning, CPLE_UserInterrupt,
-            "Insufficient privileges to insert reference system to "
-            "MDSYS.CS_SRS table." );
-        eError = CE_Warning;
-    }
-
-    CPLFree( pszCloneWKT );
-    
-    return eError;
-}
-
-/************************************************************************/
-/*                      GetMetadataDomainList()                         */
-/************************************************************************/
-
-char **GeoRasterDataset::GetMetadataDomainList()
-{
-    return BuildMetadataDomainList(GDALDataset::GetMetadataDomainList(),
-                                   TRUE,
-                                   "SUBDATASETS", NULL);
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                GetMetadata()
-//  ---------------------------------------------------------------------------
-
-char **GeoRasterDataset::GetMetadata( const char *pszDomain )
-{
-    if( pszDomain != NULL && EQUALN( pszDomain, "SUBDATASETS", 11 ) )
-        return papszSubdatasets;
-    else
-        return GDALDataset::GetMetadata( pszDomain );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     Delete()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::Delete( const char* pszFilename )
-{
-    (void) pszFilename;
-/***
-    GeoRasterDataset* poGRD = NULL;
-
-    poGRD = (GeoRasterDataset*) GDALOpen( pszFilename, GA_Update );
-
-    if( ! poGRD )
-    {
-        return CE_Failure;
-    }
-
-    if( ! poGRD->poGeoRaster->Delete() )
-    {
-        return CE_Failure;
-    }
-***/
-    return CE_None;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                             SetSubdatasets()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterDataset::SetSubdatasets( GeoRasterWrapper* poGRW )
-{
-    OWConnection* poConnection  = poGRW->poConnection;
-    OWStatement* poStmt = NULL;
-
-    //  -----------------------------------------------------------
-    //  List all the GeoRaster Tables of that User/Database
-    //  -----------------------------------------------------------
-
-    if( poGRW->sTable.empty() &&
-        poGRW->sColumn.empty() )
-    {
-        poStmt = poConnection->CreateStatement( 
-            "SELECT   DISTINCT TABLE_NAME, OWNER FROM ALL_SDO_GEOR_SYSDATA\n"
-            "  ORDER  BY TABLE_NAME ASC" );
-        
-        char szTable[OWNAME];
-        char szOwner[OWNAME];
-
-        poStmt->Define( szTable );
-        poStmt->Define( szOwner );
-
-        if( poStmt->Execute() )
-        {
-            int nCount = 1;
-
-            do
-            {
-                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                    CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
-                    CPLSPrintf( "geor:%s/%s@%s,%s.%s",
-                        poConnection->GetUser(), poConnection->GetPassword(),
-                        poConnection->GetServer(), szOwner, szTable ) );
-
-                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                    CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
-                    CPLSPrintf( "%s.Table=%s", szOwner, szTable ) );
-
-                nCount++;
-            }
-            while( poStmt->Fetch() );
-        }
-
-        return;
-    }
-
-    //  -----------------------------------------------------------
-    //  List all the GeoRaster Columns of that Table
-    //  -----------------------------------------------------------
-
-    if( ! poGRW->sTable.empty() &&
-          poGRW->sColumn.empty() )
-    {
-        poStmt = poConnection->CreateStatement( CPLSPrintf(
-            "SELECT   DISTINCT COLUMN_NAME, OWNER FROM ALL_SDO_GEOR_SYSDATA\n"
-            "  WHERE  TABLE_NAME = UPPER('%s')\n"
-            "  ORDER  BY COLUMN_NAME ASC",
-                poGRW->sTable.c_str() ) );
-
-        char szColumn[OWNAME];
-        char szOwner[OWNAME];
-
-        poStmt->Define( szColumn );
-        poStmt->Define( szOwner );
-        
-        if( poStmt->Execute() )
-        {
-            int nCount = 1;
-
-            do
-            {
-                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                    CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
-                    CPLSPrintf( "geor:%s/%s@%s,%s.%s,%s",
-                        poConnection->GetUser(), poConnection->GetPassword(),
-                        poConnection->GetServer(), szOwner,
-                        poGRW->sTable.c_str(), szColumn ) );
-
-                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                    CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
-                    CPLSPrintf( "Table=%s.%s Column=%s", szOwner,
-                        poGRW->sTable.c_str(), szColumn ) );
-
-                nCount++;
-            }
-            while( poStmt->Fetch() );
-        }
-        
-        return;
-    }
-
-    //  -----------------------------------------------------------
-    //  List all the rows that contains GeoRaster on Table/Column/Where
-    //  -----------------------------------------------------------
-
-    CPLString osAndWhere = "";
-
-    if( ! poGRW->sWhere.empty() )
-    {
-        osAndWhere = CPLSPrintf( "AND %s", poGRW->sWhere.c_str() );
-    }
-
-    poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "SELECT T.%s.RASTERDATATABLE, T.%s.RASTERID, \n"
-        "  extractValue(t.%s.metadata, "
-"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"ROW\"]/size','%s'),\n"
-        "  extractValue(t.%s.metadata, "
-"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"COLUMN\"]/size','%s'),\n"
-        "  extractValue(t.%s.metadata, "
-"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"BAND\"]/size','%s'),\n"
-        "  extractValue(t.%s.metadata, "
-"'/georasterMetadata/rasterInfo/cellDepth','%s'),\n"
-        "  extractValue(t.%s.metadata, "
-"'/georasterMetadata/spatialReferenceInfo/SRID','%s')\n"
-        "  FROM   %s%s T\n"
-        "  WHERE  %s IS NOT NULL %s\n"
-        "  ORDER  BY T.%s.RASTERDATATABLE ASC,\n"
-        "            T.%s.RASTERID ASC",
-        poGRW->sColumn.c_str(), poGRW->sColumn.c_str(),
-        poGRW->sColumn.c_str(), OW_XMLNS,
-        poGRW->sColumn.c_str(), OW_XMLNS,
-        poGRW->sColumn.c_str(), OW_XMLNS,
-        poGRW->sColumn.c_str(), OW_XMLNS,
-        poGRW->sColumn.c_str(), OW_XMLNS,
-        poGRW->sSchema.c_str(), poGRW->sTable.c_str(),
-        poGRW->sColumn.c_str(), osAndWhere.c_str(),
-        poGRW->sColumn.c_str(), poGRW->sColumn.c_str() ) );
-
-    char szDataTable[OWNAME];
-    char szRasterId[OWNAME];
-    char szRows[OWNAME];
-    char szColumns[OWNAME];
-    char szBands[OWNAME];
-    char szCellDepth[OWNAME];
-    char szSRID[OWNAME];
-
-    poStmt->Define( szDataTable );
-    poStmt->Define( szRasterId );
-    poStmt->Define( szRows );
-    poStmt->Define( szColumns );
-    poStmt->Define( szBands );
-    poStmt->Define( szCellDepth );
-    poStmt->Define( szSRID );
-
-    if( poStmt->Execute() )
-    {
-        int nCount = 1;
-
-        do
-        {
-            papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
-                CPLSPrintf( "geor:%s/%s@%s,%s,%s",
-                    poConnection->GetUser(), poConnection->GetPassword(),
-                    poConnection->GetServer(), szDataTable, szRasterId ) );
-
-            const char* pszXBands = "";
-
-            if( ! EQUAL( szBands, "" ) )
-            {
-                pszXBands = CPLSPrintf( "x%s", szBands );
-            }
-
-            papszSubdatasets = CSLSetNameValue( papszSubdatasets,
-                CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
-                CPLSPrintf( "[%sx%s%s] CellDepth=%s SRID=%s",
-                    szRows, szColumns, pszXBands,
-                    szCellDepth, szSRID ) );
-
-            nCount++;
-        }
-        while( poStmt->Fetch() );
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                    SetGCPs()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::SetGCPs( int, const GDAL_GCP *, const char * )
-{
-    return CE_None;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                           GetGCPProjection()
-//  ---------------------------------------------------------------------------
-
-const char* GeoRasterDataset::GetGCPProjection()
-
-{
-    if( nGCPCount > 0 )
-        return pszProjection;
-    else
-        return "";
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            IBuildOverviews()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::IBuildOverviews( const char* pszResampling,
-                                          int nOverviews,
-                                          int* panOverviewList,
-                                          int nListBands,
-                                          int* panBandList,
-                                          GDALProgressFunc pfnProgress,
-                                          void* pProgressData )
-{
-    (void) panBandList;
-    (void) nListBands;
-
-    //  ---------------------------------------------------------------
-    //  Can't update on read-only access mode
-    //  ---------------------------------------------------------------
-
-    if( GetAccess() != GA_Update )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-            "Can't build overviews/pyramids on read-only access." );
-        return CE_Failure;
-    }
-
-    //  ---------------------------------------------------------------
-    //  Uses internal sdo_generatePyramid at PL/SQL?
-    //  ---------------------------------------------------------------
-
-    bool bInternal = true;
-
-    const char *pszGEOR_INTERNAL_PYR = CPLGetConfigOption( "GEOR_INTERNAL_PYR",
-        "YES" );
-
-    if( EQUAL(pszGEOR_INTERNAL_PYR, "NO") )
-    {
-        bInternal = false;
-    }
-        
-    //  -----------------------------------------------------------
-    //  Pyramids applies to the whole dataset not to a specific band
-    //  -----------------------------------------------------------
-
-    if( nBands < GetRasterCount())
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-            "Invalid GeoRaster Pyramids band selection" );
-        return CE_Failure;
-    }
-
-    //  ---------------------------------------------------------------
-    //  Initialize progress reporting
-    //  ---------------------------------------------------------------
-
-    if( ! pfnProgress( 0.1, NULL, pProgressData ) )
-    {
-        CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
-        return CE_Failure;
-    }
-
-    //  ---------------------------------------------------------------
-    //  Clear existing overviews
-    //  ---------------------------------------------------------------
-
-    if( nOverviews == 0 )
-    {
-        poGeoRaster->DeletePyramid();
-        return CE_None;
-    }
-
-    //  -----------------------------------------------------------
-    //  Pyramids levels can not be treated individually
-    //  -----------------------------------------------------------
-
-    if( nOverviews > 0 )
-    {
-        int i;
-        for( i = 1; i < nOverviews; i++ )
-        {
-            //  -----------------------------------------------------------
-            //  Power of 2, starting on 2, e.g. 2, 4, 8, 16, 32, 64, 128
-            //  -----------------------------------------------------------
-
-            if( panOverviewList[0] != 2 ||
-              ( panOverviewList[i] != panOverviewList[i-1] * 2 ) )
-            {
-                CPLError( CE_Failure, CPLE_AppDefined,
-                    "Invalid GeoRaster Pyramids levels." );        
-                return CE_Failure;
-            }
-        }
-    }
-
-    //  -----------------------------------------------------------
-    //  Re-sampling method: 
-    //    NN, BILINEAR, AVERAGE4, AVERAGE16 and CUBIC
-    //  -----------------------------------------------------------
-
-    char szMethod[OWNAME];
-
-    if( EQUAL( pszResampling, "NEAREST" ) )
-    {
-        strcpy( szMethod, "NN" );
-    }
-    else if( EQUALN( pszResampling, "AVERAGE", 7 ) )
-    {
-        strcpy( szMethod, "AVERAGE4" );
-    }
-    else
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, "Invalid resampling method" );
-        return CE_Failure;
-    }
-
-    //  -----------------------------------------------------------
-    //  Generate pyramids on poGeoRaster
-    //  -----------------------------------------------------------
-
-    if( ! poGeoRaster->GeneratePyramid( nOverviews, szMethod, bInternal ) )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, "Error generating pyramid" );
-        return CE_Failure;
-    }
-
-    //  -----------------------------------------------------------
-    //  If Pyramid was done internally on the server exit here
-    //  -----------------------------------------------------------
-    
-    if( bInternal )
-    {
-        pfnProgress( 1 , NULL, pProgressData );
-        return CE_None;
-    }
-
-    //  -----------------------------------------------------------
-    //  Load the pyramids data using GDAL methods
-    //  -----------------------------------------------------------
-
-    CPLErr eErr = CE_None;
-
-    int i = 0;
-
-    for( i = 0; i < nBands; i++ )
-    {
-        GeoRasterRasterBand* poBand = (GeoRasterRasterBand*) papoBands[i];
-
-        //  -------------------------------------------------------
-        //  Clean up previous overviews
-        //  -------------------------------------------------------
-
-        int j = 0;
-
-        if( poBand->nOverviewCount && poBand->papoOverviews )
-        {
-            for( j = 0; j < poBand->nOverviewCount; j++ )
-            {
-                delete poBand->papoOverviews[j];
-            }
-            CPLFree( poBand->papoOverviews );
-        }
-
-        //  -------------------------------------------------------
-        //  Create new band's overviews list
-        //  -------------------------------------------------------
-
-        poBand->nOverviewCount = poGeoRaster->nPyramidMaxLevel;
-        poBand->papoOverviews  = (GeoRasterRasterBand**) VSIMalloc(
-                sizeof(GeoRasterRasterBand*) * poBand->nOverviewCount );
-
-        for( j = 0; j < poBand->nOverviewCount; j++ )
-        {
-          poBand->papoOverviews[j] = new GeoRasterRasterBand(
-                (GeoRasterDataset*) this, ( i + 1 ), ( j + 1 ) );
-        }
-    }
-
-    //  -----------------------------------------------------------
-    //  Load band's overviews
-    //  -----------------------------------------------------------
-
-    for( i = 0; i < nBands; i++ )
-    {
-        GeoRasterRasterBand* poBand = (GeoRasterRasterBand*) papoBands[i];
-
-        void *pScaledProgressData = GDALCreateScaledProgress( 
-            i / (double) nBands, ( i + 1) / (double) nBands, 
-            pfnProgress, pProgressData );
-
-        eErr = GDALRegenerateOverviews(
-            (GDALRasterBandH) poBand,
-            poBand->nOverviewCount,
-            (GDALRasterBandH*) poBand->papoOverviews,
-            pszResampling,
-            GDALScaledProgress,
-            pScaledProgressData );
-
-        GDALDestroyScaledProgress( pScaledProgressData );
-    }
-
-    return eErr;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                             CreateMaskBand()
-//  ---------------------------------------------------------------------------
-
-CPLErr GeoRasterDataset::CreateMaskBand( int nFlags )
-{
-    (void) nFlags;
-
-    if( ! poGeoRaster->InitializeMask( DEFAULT_BMP_MASK,
-            poGeoRaster->nRowBlockSize,
-            poGeoRaster->nColumnBlockSize,
-            poGeoRaster->nTotalRowBlocks,
-            poGeoRaster->nTotalColumnBlocks,
-            poGeoRaster->nTotalBandBlocks ) )
-    {
-        return CE_Failure;
-    }
-    
-    poGeoRaster->bHasBitmapMask = true;
-
-    return CE_None;
-}
-
-/*****************************************************************************/
-/*                          GDALRegister_GEOR                                */
-/*****************************************************************************/
-
-void CPL_DLL GDALRegister_GEOR()
-{
-    GDALDriver* poDriver;
-
-    if (! GDAL_CHECK_VERSION("GeoRaster driver"))
-        return;
-
-    if( GDALGetDriverByName( "GeoRaster" ) == NULL )
-    {
-        poDriver = new GDALDriver();
-
-        poDriver->SetDescription(  "GeoRaster" );
-        poDriver->SetMetadataItem( GDAL_DMD_LONGNAME,
-                                   "Oracle Spatial GeoRaster" );
-        poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_georaster.html" );
-        poDriver->SetMetadataItem( GDAL_DMD_SUBDATASETS, "YES" );
-        poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
-                                   "Byte UInt16 Int16 UInt32 Int32 Float32 "
-                                   "Float64 CFloat32 CFloat64" );
-        poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
-"<CreationOptionList>"
-"  <Option name='DESCRIPTION' type='string' description='Table Description'/>"
-"  <Option name='INSERT'      type='string' description='Column Values'/>"
-"  <Option name='BLOCKXSIZE'  type='int'    description='Column Block Size' "
-                                           "default='512'/>"
-"  <Option name='BLOCKYSIZE'  type='int'    description='Row Block Size' "
-                                           "default='512'/>"
-"  <Option name='BLOCKBSIZE'  type='int'    description='Band Block Size'/>"
-"  <Option name='BLOCKING'    type='string-select' default='YES'>"
-"       <Value>YES</Value>"
-"       <Value>NO</Value>"
-"       <Value>OPTIMALPADDING</Value>"
-"  </Option>"
-"  <Option name='SRID'        type='int'    description='Overwrite EPSG code'/>"
-"  <Option name='GENPYRAMID'  type='string-select' "
-" description='Generate Pyramid, inform resampling method'>"
-"       <Value>NN</Value>"
-"       <Value>BILINEAR</Value>"
-"       <Value>BIQUADRATIC</Value>"
-"       <Value>CUBIC</Value>"
-"       <Value>AVERAGE4</Value>"
-"       <Value>AVERAGE16</Value>"
-"  </Option>"
-"  <Option name='GENPYRLEVELS'  type='int'  description='Number of pyramid level to generate'/>"
-"  <Option name='OBJECTTABLE' type='boolean' "
-                                           "description='Create RDT as object table'/>"
-"  <Option name='SPATIALEXTENT' type='boolean' "
-                                           "description='Generate Spatial Extent' "
-                                           "default='TRUE'/>"
-"  <Option name='EXTENTSRID'  type='int'    description='Spatial ExtentSRID code'/>"
-"  <Option name='COORDLOCATION'    type='string-select' default='CENTER'>"
-"       <Value>CENTER</Value>"
-"       <Value>UPPERLEFT</Value>"
-"  </Option>"
-"  <Option name='VATNAME'     type='string' description='Value Attribute Table Name'/>"
-"  <Option name='NBITS'       type='int'    description='BITS for sub-byte "
-                                           "data types (1,2,4) bits'/>"
-"  <Option name='INTERLEAVE'  type='string-select'>"
-"       <Value>BSQ</Value>"
-"       <Value>BIP</Value>"
-"       <Value>BIL</Value>"
-"   </Option>"
-"  <Option name='COMPRESS'    type='string-select'>"
-"       <Value>NONE</Value>"
-"       <Value>JPEG-B</Value>"
-"       <Value>JPEG-F</Value>"
-"       <Value>DEFLATE</Value>"
-"  </Option>"
-"  <Option name='QUALITY'     type='int'    description='JPEG quality 0..100' "
-                                           "default='75'/>"
-"</CreationOptionList>" );
-
-        poDriver->pfnOpen       = GeoRasterDataset::Open;
-        poDriver->pfnCreate     = GeoRasterDataset::Create;
-        poDriver->pfnCreateCopy = GeoRasterDataset::CreateCopy;
-        poDriver->pfnIdentify   = GeoRasterDataset::Identify;
-        poDriver->pfnDelete     = GeoRasterDataset::Delete;
-
-        GetGDALDriverManager()->RegisterDriver( poDriver );
-    }
-}
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files ( the "Software" ),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *****************************************************************************/
+
+#include "cpl_error.h"
+
+#include "ogr_spatialref.h"
+
+#include "gdal.h"
+#include "gdal_priv.h"
+#include "georaster_priv.h"
+
+CPL_C_START
+void CPL_DLL GDALRegister_GEOR(void);
+CPL_C_END
+
+//  ---------------------------------------------------------------------------
+//                                                           GeoRasterDataset()
+//  ---------------------------------------------------------------------------
+
+GeoRasterDataset::GeoRasterDataset()
+{
+    bGeoTransform       = false;
+    bForcedSRID         = false;
+    poGeoRaster         = NULL;
+    papszSubdatasets    = NULL;
+    adfGeoTransform[0]  = 0.0;
+    adfGeoTransform[1]  = 1.0;
+    adfGeoTransform[2]  = 0.0;
+    adfGeoTransform[3]  = 0.0;
+    adfGeoTransform[4]  = 0.0;
+    adfGeoTransform[5]  = 1.0;
+    pszProjection       = NULL;
+    nGCPCount           = 0;
+    pasGCPList          = NULL;
+    poMaskBand          = NULL;
+    bApplyNoDataArray   = false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                          ~GeoRasterDataset()
+//  ---------------------------------------------------------------------------
+
+GeoRasterDataset::~GeoRasterDataset()
+{
+    FlushCache();
+
+    if( nGCPCount > 0 )
+    {
+        GDALDeinitGCPs( nGCPCount, pasGCPList );
+        CPLFree( pasGCPList );
+    }
+
+    delete poGeoRaster;
+
+    if( poMaskBand )
+    {
+        delete poMaskBand;
+    }
+    
+    CPLFree( pszProjection );
+    CSLDestroy( papszSubdatasets );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                   Identify()
+//  ---------------------------------------------------------------------------
+
+int GeoRasterDataset::Identify( GDALOpenInfo* poOpenInfo )
+{
+    //  -------------------------------------------------------------------
+    //  Verify georaster prefix
+    //  -------------------------------------------------------------------
+
+    char* pszFilename = poOpenInfo->pszFilename;
+
+    if( EQUALN( pszFilename, "georaster:", 10 ) == false &&
+        EQUALN( pszFilename, "geor:", 5 )       == false )
+    {
+        return false;
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                       Open()
+//  ---------------------------------------------------------------------------
+
+GDALDataset* GeoRasterDataset::Open( GDALOpenInfo* poOpenInfo )
+{
+    //  -------------------------------------------------------------------
+    //  It shouldn't have an open file pointer
+    //  -------------------------------------------------------------------
+
+    if( poOpenInfo->fp != NULL )
+    {
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Check identification string and usage
+    //  -------------------------------------------------------------------
+
+    if( ! Identify( poOpenInfo ) )
+    {
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Create a GeoRaster wrapper object
+    //  -------------------------------------------------------------------
+
+    GeoRasterWrapper* poGRW = GeoRasterWrapper::Open(
+            poOpenInfo->pszFilename,
+            poOpenInfo->eAccess == GA_Update );
+
+    if( ! poGRW )
+    {
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Create a corresponding GDALDataset
+    //  -------------------------------------------------------------------
+
+    GeoRasterDataset *poGRD;
+
+    poGRD = new GeoRasterDataset();
+
+    if( ! poGRD )
+    {
+        return NULL;
+    }
+
+    poGRD->eAccess     = poOpenInfo->eAccess;
+    poGRD->poGeoRaster = poGRW;
+
+    //  -------------------------------------------------------------------
+    //  List Subdatasets
+    //  -------------------------------------------------------------------
+
+    if( ! poGRW->bUniqueFound )
+    {
+        if( poGRD->eAccess == GA_ReadOnly )
+        {
+            poGRD->SetSubdatasets( poGRW );
+
+            if( CSLCount( poGRD->papszSubdatasets ) == 0 )
+            {
+                delete poGRD;
+                poGRD = NULL;
+            }
+        }
+        return (GDALDataset*) poGRD;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Assign GeoRaster information
+    //  -------------------------------------------------------------------
+
+    poGRD->poGeoRaster   = poGRW;
+    poGRD->nRasterXSize  = poGRW->nRasterColumns;
+    poGRD->nRasterYSize  = poGRW->nRasterRows;
+    poGRD->nBands        = poGRW->nRasterBands;
+
+    if( poGRW->bIsReferenced )
+    {
+        poGRD->adfGeoTransform[1] = poGRW->dfXCoefficient[0];
+        poGRD->adfGeoTransform[2] = poGRW->dfXCoefficient[1];
+        poGRD->adfGeoTransform[0] = poGRW->dfXCoefficient[2];
+        poGRD->adfGeoTransform[4] = poGRW->dfYCoefficient[0];
+        poGRD->adfGeoTransform[5] = poGRW->dfYCoefficient[1];
+        poGRD->adfGeoTransform[3] = poGRW->dfYCoefficient[2];
+    }
+
+    //  -------------------------------------------------------------------
+    //  Copy RPC values to RPC metadata domain
+    //  -------------------------------------------------------------------
+
+    if( poGRW->phRPC )
+    {
+        char **papszRPC_MD = RPCInfoToMD( poGRW->phRPC );
+        char **papszSanitazed = NULL;
+
+        int i = 0;
+        int n = CSLCount( papszRPC_MD );
+
+        for( i = 0; i < n; i++ )
+        {
+            if ( EQUALN( papszRPC_MD[i], "MIN_LAT", 7 )  ||
+                 EQUALN( papszRPC_MD[i], "MIN_LONG", 8 ) ||
+                 EQUALN( papszRPC_MD[i], "MAX_LAT", 7 )  ||
+                 EQUALN( papszRPC_MD[i], "MAX_LONG", 8 ) )
+            {
+                continue;
+            }
+            papszSanitazed = CSLAddString( papszSanitazed, papszRPC_MD[i] );
+        }
+
+        poGRD->SetMetadata( papszSanitazed, "RPC" );
+
+        CSLDestroy( papszRPC_MD );
+        CSLDestroy( papszSanitazed );
+    }
+
+    //  -------------------------------------------------------------------
+    //  Load mask band
+    //  -------------------------------------------------------------------
+
+    poGRW->bHasBitmapMask = EQUAL( "TRUE", CPLGetXMLValue( poGRW->phMetadata,
+                          "layerInfo.objectLayer.bitmapMask", "FALSE" ) );
+
+    if( poGRW->bHasBitmapMask )
+    {
+        poGRD->poMaskBand = new GeoRasterRasterBand( poGRD, 0, DEFAULT_BMP_MASK );
+    }
+    
+    //  -------------------------------------------------------------------
+    //  Check for filter Nodata environment variable, default is YES
+    //  -------------------------------------------------------------------
+
+    const char *pszGEOR_FILTER_NODATA =
+        CPLGetConfigOption( "GEOR_FILTER_NODATA_VALUES", "NO" );
+
+    if( ! EQUAL(pszGEOR_FILTER_NODATA, "NO") )
+    {
+        poGRD->bApplyNoDataArray = true;
+    }
+    //  -------------------------------------------------------------------
+    //  Create bands
+    //  -------------------------------------------------------------------
+
+    int i = 0;
+    int nBand = 0;
+
+    for( i = 0; i < poGRD->nBands; i++ )
+    {
+        nBand = i + 1;
+        poGRD->SetBand( nBand, new GeoRasterRasterBand( poGRD, nBand, 0 ) );
+    }
+
+    //  -------------------------------------------------------------------
+    //  Set IMAGE_STRUCTURE metadata information
+    //  -------------------------------------------------------------------
+
+    if( poGRW->nBandBlockSize == 1 )
+    {
+        poGRD->SetMetadataItem( "INTERLEAVE", "BAND", "IMAGE_STRUCTURE" );
+    }
+    else
+    {
+        if( EQUAL( poGRW->sInterleaving.c_str(), "BSQ" ) )
+        {
+            poGRD->SetMetadataItem( "INTERLEAVE", "BAND", "IMAGE_STRUCTURE" );
+        }
+        else if( EQUAL( poGRW->sInterleaving.c_str(), "BIP" ) )
+        {
+            poGRD->SetMetadataItem( "INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE" );
+        }
+        else if( EQUAL( poGRW->sInterleaving.c_str(), "BIL" ) )
+        {
+            poGRD->SetMetadataItem( "INTERLEAVE", "LINE", "IMAGE_STRUCTURE" );
+        }
+    }
+
+    poGRD->SetMetadataItem( "COMPRESSION", CPLGetXMLValue( poGRW->phMetadata,
+        "rasterInfo.compression.type", "NONE" ), "IMAGE_STRUCTURE" );
+
+    if( EQUALN( poGRW->sCompressionType.c_str(), "JPEG", 4 ) )
+    {
+        poGRD->SetMetadataItem( "COMPRESS_QUALITY",
+            CPLGetXMLValue( poGRW->phMetadata,
+            "rasterInfo.compression.quality", "0" ), "IMAGE_STRUCTURE" );
+    }
+
+    if( EQUAL( poGRW->sCellDepth.c_str(), "1BIT" ) )
+    {
+        poGRD->SetMetadataItem( "NBITS", "1", "IMAGE_STRUCTURE" );
+    }
+
+    if( EQUAL( poGRW->sCellDepth.c_str(), "2BIT" ) )
+    {
+        poGRD->SetMetadataItem( "NBITS", "2", "IMAGE_STRUCTURE" );
+    }
+
+    if( EQUAL( poGRW->sCellDepth.c_str(), "4BIT" ) )
+    {
+        poGRD->SetMetadataItem( "NBITS", "4", "IMAGE_STRUCTURE" );
+    }
+
+    //  -------------------------------------------------------------------
+    //  Set Metadata on "ORACLE" domain
+    //  -------------------------------------------------------------------
+
+    char* pszDoc = CPLSerializeXMLTree( poGRW->phMetadata );
+
+    poGRD->SetMetadataItem( "TABLE_NAME", CPLSPrintf( "%s%s",
+        poGRW->sSchema.c_str(),
+        poGRW->sTable.c_str()), "ORACLE" );
+
+    poGRD->SetMetadataItem( "COLUMN_NAME",
+        poGRW->sColumn.c_str(), "ORACLE" );
+
+    poGRD->SetMetadataItem( "RDT_TABLE_NAME",
+        poGRW->sDataTable.c_str(), "ORACLE" );
+
+    poGRD->SetMetadataItem( "RASTER_ID", CPLSPrintf( "%d",
+        poGRW->nRasterId ), "ORACLE" );
+
+    poGRD->SetMetadataItem( "SRID", CPLSPrintf( "%d",
+        poGRW->nSRID ), "ORACLE" );
+
+    poGRD->SetMetadataItem( "WKT", poGRW->sWKText.c_str(), "ORACLE" );
+
+    poGRD->SetMetadataItem( "METADATA", pszDoc, "ORACLE" );
+
+    CPLFree( pszDoc );
+
+    //  -------------------------------------------------------------------
+    //  Return a GDALDataset
+    //  -------------------------------------------------------------------
+
+    return (GDALDataset*) poGRD;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     Create()
+//  ---------------------------------------------------------------------------
+
+GDALDataset *GeoRasterDataset::Create( const char *pszFilename,
+                                       int nXSize,
+                                       int nYSize,
+                                       int nBands, 
+                                       GDALDataType eType,
+                                       char **papszOptions )
+{
+    //  -------------------------------------------------------------------
+    //  Check for supported Data types
+    //  -------------------------------------------------------------------
+
+    const char* pszCellDepth = OWSetDataType( eType );
+
+    if( EQUAL( pszCellDepth, "Unknown" ) )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+            "Attempt to create GeoRaster with unsupported data type (%s)",
+            GDALGetDataTypeName( eType ) );
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Open the Dataset
+    //  -------------------------------------------------------------------
+
+    GeoRasterDataset* poGRD = NULL;
+
+    poGRD = (GeoRasterDataset*) GDALOpen( pszFilename, GA_Update );
+
+    if( ! poGRD )
+    {
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Get the GeoRaster
+    //  -------------------------------------------------------------------
+
+    GeoRasterWrapper* poGRW = poGRD->poGeoRaster;
+
+    if( ! poGRW )
+    {
+        delete poGRD;
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Set basic information and default values
+    //  -------------------------------------------------------------------
+
+    poGRW->nRasterColumns   = nXSize;
+    poGRW->nRasterRows      = nYSize;
+    poGRW->nRasterBands     = nBands;
+    poGRW->sCellDepth       = pszCellDepth;
+    poGRW->nRowBlockSize    = DEFAULT_BLOCK_ROWS;
+    poGRW->nColumnBlockSize = DEFAULT_BLOCK_COLUMNS;
+    poGRW->nBandBlockSize   = 1;
+
+    if( poGRW->bUniqueFound )
+    {
+        poGRW->PrepareToOverwrite();
+    }
+
+    //  -------------------------------------------------------------------
+    //  Check the create options to use in initialization
+    //  -------------------------------------------------------------------
+
+    const char* pszFetched  = "";
+    char* pszDescription    = NULL;
+    char* pszInsert         = NULL;
+    int   nQuality          = -1;
+
+    if( ! poGRW->sTable.empty() )
+    {
+        pszFetched = CSLFetchNameValue( papszOptions, "DESCRIPTION" );
+
+        if( pszFetched )
+        {
+            pszDescription  = CPLStrdup( pszFetched );
+        }
+    }
+
+    if( poGRW->sTable.empty() )
+    {
+        poGRW->sTable = "GDAL_IMPORT";
+        poGRW->sDataTable = "GDAL_RDT";
+    }
+
+    if( poGRW->sColumn.empty() )
+    {
+        poGRW->sColumn = "RASTER";
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "INSERT" );
+
+    if( pszFetched )
+    {
+        pszInsert = CPLStrdup( pszFetched );
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKXSIZE" );
+
+    if( pszFetched )
+    {
+        poGRW->nColumnBlockSize = atoi( pszFetched );
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKYSIZE" );
+
+    if( pszFetched )
+    {
+        poGRW->nRowBlockSize = atoi( pszFetched );
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "NBITS" );
+
+    if( pszFetched != NULL )
+    {
+        poGRW->sCellDepth = CPLSPrintf( "%dBIT", atoi( pszFetched ) );
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "COMPRESS" );
+
+    if( pszFetched != NULL &&
+        ( EQUALN( pszFetched, "JPEG", 4 ) ||
+          EQUAL( pszFetched, "DEFLATE" ) ) )
+    {
+        poGRW->sCompressionType = pszFetched;
+    }
+    else
+    {
+        poGRW->sCompressionType = "NONE";
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "QUALITY" );
+
+    if( pszFetched )
+    {
+        poGRW->nCompressQuality = atoi( pszFetched );
+        nQuality = poGRW->nCompressQuality;
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "INTERLEAVE" );
+
+    bool bInterleve_ind = false;
+
+    if( pszFetched )
+    {
+        bInterleve_ind = true;
+
+        if( EQUAL( pszFetched, "BAND" ) ||  EQUAL( pszFetched, "BSQ" ) )
+        {
+            poGRW->sInterleaving = "BSQ";
+        }
+        if( EQUAL( pszFetched, "LINE" ) ||  EQUAL( pszFetched, "BIL" ) )
+        {
+            poGRW->sInterleaving = "BIL";
+        }
+        if( EQUAL( pszFetched, "PIXEL" ) ||  EQUAL( pszFetched, "BIP" ) )
+        {
+            poGRW->sInterleaving = "BIP";
+        }
+    }
+    else
+    {
+        if( EQUAL( poGRW->sCompressionType.c_str(), "NONE" ) == false )
+        {
+            poGRW->sInterleaving = "BIP";
+        }
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKBSIZE" );
+
+    if( pszFetched )
+    {
+        poGRW->nBandBlockSize = atoi( pszFetched );
+    }
+    else
+    {
+        if( ! EQUAL( poGRW->sCompressionType.c_str(), "NONE" ) &&
+          ( nBands == 3 || nBands == 4 ) )
+        {
+            poGRW->nBandBlockSize = nBands;
+        }
+    }
+
+    if( bInterleve_ind == false && 
+      ( poGRW->nBandBlockSize == 3 || poGRW->nBandBlockSize == 4 ) ) 
+    {
+      poGRW->sInterleaving = "BIP";
+    }
+
+    if( EQUALN( poGRW->sCompressionType.c_str(), "JPEG", 4 ) )
+    {
+        if( ! EQUAL( poGRW->sInterleaving.c_str(), "BIP" ) )
+        {
+            CPLError( CE_Warning, CPLE_IllegalArg, 
+                "compress=JPEG assumes interleave=BIP" );
+            poGRW->sInterleaving = "BIP";
+        }
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "BLOCKING" );
+
+    if( pszFetched )
+    {
+        if( EQUAL( pszFetched, "NO" ) )
+        {
+            poGRW->bBlocking = false;
+        }
+
+        if( EQUAL( pszFetched, "OPTIMALPADDING" ) )
+        {
+            if( poGRW->poConnection->GetVersion() < 11 )
+            {
+                CPLError( CE_Warning, CPLE_IllegalArg, 
+                    "BLOCKING=OPTIMALPADDING not supported on Oracle older than 11g" );
+            }
+            else
+            {
+                poGRW->bAutoBlocking = true;
+                poGRW->bBlocking = true;
+            }
+        }
+    }
+
+    //  -------------------------------------------------------------------
+    //  Validate options
+    //  -------------------------------------------------------------------
+
+    if( pszDescription && poGRW->bUniqueFound )
+    {
+        CPLError( CE_Failure, CPLE_IllegalArg, 
+            "Option (DESCRIPTION) cannot be used on a existing GeoRaster." );
+        delete poGRD;
+        return NULL;
+    }
+
+    if( pszInsert && poGRW->bUniqueFound )
+    {
+        CPLError( CE_Failure, CPLE_IllegalArg, 
+            "Option (INSERT) cannot be used on a existing GeoRaster." );
+        delete poGRD;
+        return NULL;
+    }
+
+    /* Compression JPEG-B is deprecated. It should be able to read but to
+     * to create new GeoRaster on databases with that compression option.
+     *
+     * TODO: Remove that options on next release.
+     */
+    if( EQUAL( poGRW->sCompressionType.c_str(), "JPEG-B" ) )
+    {
+        CPLError( CE_Failure, CPLE_IllegalArg,
+            "Option (COMPRESS=%s) is deprecated and cannot be used.",
+            poGRW->sCompressionType.c_str() );
+        delete poGRD;
+        return NULL;
+    }
+
+    if( EQUAL( poGRW->sCompressionType.c_str(), "JPEG-F" ) )
+    {
+        /* JPEG-F can only compress byte data type
+         */
+        if( eType != GDT_Byte )
+        {
+            CPLError( CE_Failure, CPLE_IllegalArg, 
+                "Option (COMPRESS=%s) can only be used with Byte data type.",
+                poGRW->sCompressionType.c_str() );
+            delete poGRD;
+            return NULL;
+        }
+
+        /* JPEG-F can compress one band per block or 3 for RGB
+         * or 4 for RGBA.
+         */
+        if( ( poGRW->nBandBlockSize != 1 &&
+              poGRW->nBandBlockSize != 3 &&
+              poGRW->nBandBlockSize != 4 ) ||
+          ( ( poGRW->nBandBlockSize != 1 &&
+            ( poGRW->nBandBlockSize != poGRW->nRasterBands ) ) ) )
+        {
+            CPLError( CE_Failure, CPLE_IllegalArg,
+                "Option (COMPRESS=%s) requires BLOCKBSIZE to be 1 (for any "
+                "number of bands), 3 (for 3 bands RGB) and 4 (for 4 bands RGBA).",
+                poGRW->sCompressionType.c_str() );
+            delete poGRD;
+            return NULL;
+        }
+
+        /* There is a limite on how big a compressed block can be.
+         */
+        if( ( poGRW->nColumnBlockSize * 
+              poGRW->nRowBlockSize *
+              poGRW->nBandBlockSize *
+              ( GDALGetDataTypeSize( eType ) / 8 ) ) > ( 50 * 1024 * 1024 ) )
+        {
+            CPLError( CE_Failure, CPLE_IllegalArg, 
+                "Option (COMPRESS=%s) each data block must not exceed 50Mb. "
+                "Consider reducing BLOCK{X,Y,B}XSIZE.",
+                poGRW->sCompressionType.c_str() );
+            delete poGRD;
+            return NULL;
+        }
+    }
+
+    if( EQUAL( poGRW->sCompressionType.c_str(), "DEFLATE" ) )
+    {
+        if( ( poGRW->nColumnBlockSize * 
+              poGRW->nRowBlockSize *
+              poGRW->nBandBlockSize *
+              ( GDALGetDataTypeSize( eType ) / 8 ) ) > ( 1024 * 1024 * 1024 ) )
+        {
+            CPLError( CE_Failure, CPLE_IllegalArg, 
+                "For (COMPRESS=%s) each data block must not exceed 1Gb. "
+                "Consider reducing BLOCK{X,Y,B}XSIZE.",
+                poGRW->sCompressionType.c_str() );
+            delete poGRD;
+            return NULL;
+        }
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "OBJECTTABLE" );
+
+    if( pszFetched )
+    {
+        int nVersion = poGRW->poConnection->GetVersion();
+        if( nVersion <= 11 )
+        {
+            CPLError( CE_Failure, CPLE_IllegalArg, 
+                "Driver create-option OBJECTTABLE not "
+                "supported on Oracle %d", nVersion );
+            delete poGRD;
+            return NULL;
+        }
+    }
+
+    poGRD->poGeoRaster->bCreateObjectTable = (bool)
+        CSLFetchBoolean( papszOptions, "OBJECTTABLE", FALSE );
+
+    //  -------------------------------------------------------------------
+    //  Create a SDO_GEORASTER object on the server
+    //  -------------------------------------------------------------------
+
+    bool bSucced = poGRW->Create( pszDescription, pszInsert, poGRW->bUniqueFound );
+
+    CPLFree( pszInsert );
+    CPLFree( pszDescription );
+
+    if( ! bSucced )
+    {
+        delete poGRD;
+        return NULL;
+    }
+    
+    //  -------------------------------------------------------------------
+    //  Prepare an identification string
+    //  -------------------------------------------------------------------
+
+    char szStringId[OWTEXT];
+
+    strcpy( szStringId, CPLSPrintf( "georaster:%s,%s,%s,%s,%d",
+        poGRW->poConnection->GetUser(),
+        poGRW->poConnection->GetPassword(),
+        poGRW->poConnection->GetServer(),
+        poGRW->sDataTable.c_str(),
+        poGRW->nRasterId ) );
+
+    delete poGRD;
+
+    poGRD = (GeoRasterDataset*) GDALOpen( szStringId, GA_Update );
+
+    if( ! poGRD )
+    {
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Load aditional options
+    //  -------------------------------------------------------------------
+
+    pszFetched = CSLFetchNameValue( papszOptions, "VATNAME" );
+
+    if( pszFetched )
+    {
+        poGRW->sValueAttributeTab = pszFetched;
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "SRID" );
+
+    if( pszFetched )
+    {
+        poGRD->bForcedSRID = true;
+        poGRD->poGeoRaster->SetGeoReference( atoi( pszFetched ) );
+    }
+
+    poGRD->poGeoRaster->bGenSpatialIndex = (bool)
+        CSLFetchBoolean( papszOptions, "SPATIALEXTENT", TRUE );
+
+    pszFetched = CSLFetchNameValue( papszOptions, "EXTENTSRID" );
+
+    if( pszFetched )
+    {
+        poGRD->poGeoRaster->nExtentSRID = atoi( pszFetched );
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "COORDLOCATION" );
+
+    if( pszFetched )
+    {
+        if( EQUAL( pszFetched, "CENTER" ) )
+        {
+            poGRD->poGeoRaster->eModelCoordLocation = MCL_CENTER;
+        }
+        else if( EQUAL( pszFetched, "UPPERLEFT" ) )
+        {
+            poGRD->poGeoRaster->eModelCoordLocation = MCL_UPPERLEFT;
+        }
+        else 
+        {
+            CPLError( CE_Warning, CPLE_IllegalArg, 
+                "Incorrect COORDLOCATION (%s)", pszFetched );
+        }
+    }
+
+    if ( nQuality > 0 )
+    {
+        poGRD->poGeoRaster->nCompressQuality = nQuality;
+    }
+
+
+    pszFetched = CSLFetchNameValue( papszOptions, "GENPYRAMID" );
+
+    if( pszFetched != NULL )
+    {
+        if (!(EQUAL(pszFetched, "NN") ||
+              EQUAL(pszFetched, "BILINEAR") ||
+              EQUAL(pszFetched, "BIQUADRATIC") ||
+              EQUAL(pszFetched, "CUBIC") ||
+              EQUAL(pszFetched, "AVERAGE4") ||
+              EQUAL(pszFetched, "AVERAGE16")))
+        {
+            CPLError( CE_Warning, CPLE_IllegalArg, "Wrong resample method for pyramid (%s)", pszFetched);
+        }
+
+        poGRD->poGeoRaster->bGenPyramid = true;
+        poGRD->poGeoRaster->sPyramidResampling = pszFetched;
+    }
+
+    pszFetched = CSLFetchNameValue( papszOptions, "GENPYRLEVELS" );
+
+    if( pszFetched != NULL )
+    {
+        poGRD->poGeoRaster->bGenPyramid = true;
+        poGRD->poGeoRaster->nPyramidLevels = atoi(pszFetched);
+    }
+
+    //  -------------------------------------------------------------------
+    //  Return a new Dataset
+    //  -------------------------------------------------------------------
+
+    return (GDALDataset*) poGRD;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                 CreateCopy()
+//  ---------------------------------------------------------------------------
+
+GDALDataset *GeoRasterDataset::CreateCopy( const char* pszFilename,
+                                           GDALDataset* poSrcDS,
+                                           int bStrict,
+                                           char** papszOptions,
+                                           GDALProgressFunc pfnProgress,
+                                           void* pProgressData )
+{
+    (void) bStrict;
+
+    int nBands = poSrcDS->GetRasterCount();
+    if (nBands == 0)
+    {
+        CPLError( CE_Failure, CPLE_NotSupported, 
+        "GeoRaster driver does not support source dataset with zero band.\n");
+        return NULL;
+    }
+
+    GDALRasterBand* poBand = poSrcDS->GetRasterBand( 1 );
+    GDALDataType    eType  = poBand->GetRasterDataType();
+
+    //  -----------------------------------------------------------
+    //  Create a GeoRaster on the server or select one to overwrite
+    //  -----------------------------------------------------------
+
+    GeoRasterDataset *poDstDS;
+
+    poDstDS = (GeoRasterDataset *) GeoRasterDataset::Create( pszFilename,
+        poSrcDS->GetRasterXSize(),
+        poSrcDS->GetRasterYSize(),
+        poSrcDS->GetRasterCount(),
+        eType, papszOptions );
+
+    if( poDstDS == NULL )
+    {
+        return NULL;
+    }
+
+    //  -----------------------------------------------------------
+    //  Copy information to the dataset
+    //  -----------------------------------------------------------
+
+    double adfTransform[6];
+
+    if ( poSrcDS->GetGeoTransform( adfTransform ) == CE_None )
+    {
+        if ( ! ( adfTransform[0] == 0.0 && 
+                 adfTransform[1] == 1.0 &&
+                 adfTransform[2] == 0.0 &&
+                 adfTransform[3] == 0.0 &&
+                 adfTransform[4] == 0.0 &&
+                 adfTransform[5] == 1.0 ) ) 
+        {
+            poDstDS->SetGeoTransform( adfTransform );
+        }
+    }
+
+    if( ! poDstDS->bForcedSRID ) /* forced by create option SRID */
+    {
+        poDstDS->SetProjection( poSrcDS->GetProjectionRef() );
+    }
+
+    // --------------------------------------------------------------------
+    //      Copy RPC 
+    // --------------------------------------------------------------------
+
+    char **papszRPCMetadata = GDALGetMetadata( poSrcDS, "RPC" );
+
+    if ( papszRPCMetadata != NULL )
+    {
+        poDstDS->poGeoRaster->phRPC = (GDALRPCInfo*) VSIMalloc( sizeof(GDALRPCInfo) );
+        GDALExtractRPCInfo( papszRPCMetadata, poDstDS->poGeoRaster->phRPC );
+    }
+
+    // --------------------------------------------------------------------
+    //      Copy information to the raster bands
+    // --------------------------------------------------------------------
+
+    int    bHasNoDataValue = FALSE;
+    double dfNoDataValue = 0.0;
+    double dfMin = 0.0, dfMax = 0.0, dfStdDev = 0.0, dfMean = 0.0;
+    double dfMedian = 0.0, dfMode = 0.0;
+    int    iBand = 0;
+
+    for( iBand = 1; iBand <= poSrcDS->GetRasterCount(); iBand++ )
+    {
+        GDALRasterBand*      poSrcBand = poSrcDS->GetRasterBand( iBand );
+        GeoRasterRasterBand* poDstBand = (GeoRasterRasterBand*) 
+                                         poDstDS->GetRasterBand( iBand );
+
+        // ----------------------------------------------------------------
+        //  Copy Color Table
+        // ----------------------------------------------------------------
+
+        GDALColorTable* poColorTable = poSrcBand->GetColorTable(); 
+
+        if( poColorTable )
+        {
+            poDstBand->SetColorTable( poColorTable );
+        }
+
+        // ----------------------------------------------------------------
+        //  Copy statitics information, without median and mode
+        // ----------------------------------------------------------------
+
+        if( poSrcBand->GetStatistics( false, false, &dfMin, &dfMax,
+            &dfMean, &dfStdDev ) == CE_None )
+        {
+            poDstBand->SetStatistics( dfMin, dfMax, dfMean, dfStdDev );
+
+            /* That will not be recorded in the GeoRaster metadata since it
+             * doesn't have median and mode, so those values are only useful
+             * at runtime.
+             */
+        }
+
+        // ----------------------------------------------------------------
+        //  Copy statitics metadata information, including median and mode
+        // ----------------------------------------------------------------
+
+        const char *pszMin     = poSrcBand->GetMetadataItem( "STATISTICS_MINIMUM" );
+        const char *pszMax     = poSrcBand->GetMetadataItem( "STATISTICS_MAXIMUM" );
+        const char *pszMean    = poSrcBand->GetMetadataItem( "STATISTICS_MEAN" );
+        const char *pszMedian  = poSrcBand->GetMetadataItem( "STATISTICS_MEDIAN" );
+        const char *pszMode    = poSrcBand->GetMetadataItem( "STATISTICS_MODE" );
+        const char *pszStdDev  = poSrcBand->GetMetadataItem( "STATISTICS_STDDEV" );
+        const char *pszSkipFX  = poSrcBand->GetMetadataItem( "STATISTICS_SKIPFACTORX" );
+        const char *pszSkipFY  = poSrcBand->GetMetadataItem( "STATISTICS_SKIPFACTORY" );
+
+        if ( pszMin    != NULL && pszMax  != NULL && pszMean   != NULL &&
+             pszMedian != NULL && pszMode != NULL && pszStdDev != NULL )
+        {
+            dfMin        = CPLScanDouble( pszMin, MAX_DOUBLE_STR_REP );
+            dfMax        = CPLScanDouble( pszMax, MAX_DOUBLE_STR_REP );
+            dfMean       = CPLScanDouble( pszMean, MAX_DOUBLE_STR_REP );
+            dfMedian     = CPLScanDouble( pszMedian, MAX_DOUBLE_STR_REP );
+            dfMode       = CPLScanDouble( pszMode, MAX_DOUBLE_STR_REP );
+
+            if ( ! ( ( dfMin    > dfMax ) ||
+                     ( dfMean   > dfMax ) || ( dfMean   < dfMin ) ||
+                     ( dfMedian > dfMax ) || ( dfMedian < dfMin ) ||
+                     ( dfMode   > dfMax ) || ( dfMode   < dfMin ) ) )
+            {
+                if ( ! pszSkipFX )
+                {
+                    pszSkipFX = pszSkipFY != NULL ? pszSkipFY : "1";
+                }
+
+                poDstBand->poGeoRaster->SetStatistics( iBand,
+                                                       pszMin, pszMax, pszMean, 
+                                                       pszMedian, pszMode,
+                                                       pszStdDev, pszSkipFX );
+            }
+        }
+
+        // ----------------------------------------------------------------
+        //  Copy Raster Attribute Table (RAT)
+        // ----------------------------------------------------------------
+
+        GDALRasterAttributeTableH poRAT = GDALGetDefaultRAT( poSrcBand );
+
+        if( poRAT != NULL )
+        {
+            poDstBand->SetDefaultRAT( (GDALRasterAttributeTable*) poRAT );
+        }
+
+        // ----------------------------------------------------------------
+        //  Copy NoData Value
+        // ----------------------------------------------------------------
+
+        dfNoDataValue = poSrcBand->GetNoDataValue( &bHasNoDataValue );
+
+        if( bHasNoDataValue )
+        {
+            poDstBand->SetNoDataValue( dfNoDataValue );
+        }
+    }
+
+    // --------------------------------------------------------------------
+    //  Copy actual imagery.
+    // --------------------------------------------------------------------
+
+    int nXSize = poDstDS->GetRasterXSize();
+    int nYSize = poDstDS->GetRasterYSize();
+
+    int nBlockXSize = 0;
+    int nBlockYSize = 0;
+
+    poDstDS->GetRasterBand( 1 )->GetBlockSize( &nBlockXSize, &nBlockYSize );
+
+    void *pData = VSIMalloc( nBlockXSize * nBlockYSize *
+        GDALGetDataTypeSize( eType ) / 8 );
+
+    if( pData == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory,
+            "GeoRaster::CreateCopy : Out of memory " );
+        delete poDstDS;
+        return NULL;
+    }
+
+    int iYOffset = 0;
+    int iXOffset = 0;
+    int iXBlock  = 0;
+    int iYBlock  = 0;
+    int nBlockCols = 0;
+    int nBlockRows = 0;
+    CPLErr eErr = CE_None;
+
+    int nPixelSize = GDALGetDataTypeSize( 
+        poSrcDS->GetRasterBand(1)->GetRasterDataType() ) / 8;
+
+    if( poDstDS->poGeoRaster->nBandBlockSize == 1)
+    {
+        // ----------------------------------------------------------------
+        //  Band order
+        // ----------------------------------------------------------------
+
+        int nBandCount = poSrcDS->GetRasterCount();
+
+        for( iBand = 1; iBand <= nBandCount; iBand++ )
+        {
+            GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand );
+            GDALRasterBand *poDstBand = poDstDS->GetRasterBand( iBand );
+
+            for( iYOffset = 0, iYBlock = 0;
+                 iYOffset < nYSize;
+                 iYOffset += nBlockYSize, iYBlock++ )
+            {
+
+                for( iXOffset = 0, iXBlock = 0;
+                     iXOffset < nXSize;
+                     iXOffset += nBlockXSize, iXBlock++ )
+                {
+
+                    nBlockCols = MIN( nBlockXSize, nXSize - iXOffset );
+                    nBlockRows = MIN( nBlockYSize, nYSize - iYOffset );
+
+                    eErr = poSrcBand->RasterIO( GF_Read,
+                        iXOffset, iYOffset,
+                        nBlockCols, nBlockRows, pData,
+                        nBlockCols, nBlockRows, eType,
+                        nPixelSize,
+                        nPixelSize * nBlockXSize );
+
+                    if( eErr != CE_None )
+                    {
+                        return NULL;
+                    }
+
+                    eErr = poDstBand->WriteBlock( iXBlock, iYBlock, pData );
+
+                    if( eErr != CE_None )
+                    {
+                        return NULL;
+                    }
+                }
+
+                if( ( eErr == CE_None ) && ( ! pfnProgress(
+                      ( ( iBand - 1) / (float) nBandCount ) +
+                      ( iYOffset + nBlockRows ) / (float) (nYSize * nBandCount),
+                      NULL, pProgressData ) ) )
+                {
+                    eErr = CE_Failure;
+                    CPLError( CE_Failure, CPLE_UserInterrupt,
+                        "User terminated CreateCopy()" );
+                }
+            }
+        }
+    }
+    else
+    {
+        // ----------------------------------------------------------------
+        //  Block order
+        // ----------------------------------------------------------------
+
+        poDstDS->poGeoRaster->SetWriteOnly( true );
+
+        for( iYOffset = 0, iYBlock = 0;
+             iYOffset < nYSize;
+             iYOffset += nBlockYSize, iYBlock++ )
+        {
+            for( iXOffset = 0, iXBlock = 0;
+                 iXOffset < nXSize;
+                 iXOffset += nBlockXSize, iXBlock++ )
+            {
+                nBlockCols = MIN( nBlockXSize, nXSize - iXOffset );
+                nBlockRows = MIN( nBlockYSize, nYSize - iYOffset );
+
+                for( iBand = 1;
+                     iBand <= poSrcDS->GetRasterCount();
+                     iBand++ )
+                {
+                    GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand );
+                    GDALRasterBand *poDstBand = poDstDS->GetRasterBand( iBand );
+
+                    eErr = poSrcBand->RasterIO( GF_Read,
+                        iXOffset, iYOffset,
+                        nBlockCols, nBlockRows, pData,
+                        nBlockCols, nBlockRows, eType,
+                        nPixelSize,
+                        nPixelSize * nBlockXSize );
+
+                    if( eErr != CE_None )
+                    {
+                        return NULL;
+                    }
+
+                    eErr = poDstBand->WriteBlock( iXBlock, iYBlock, pData );
+
+                    if( eErr != CE_None )
+                    {
+                        return NULL;
+                    }
+                }
+
+            }
+
+            if( ( eErr == CE_None ) && ( ! pfnProgress(
+                ( iYOffset + nBlockRows ) / (double) nYSize, NULL,
+                    pProgressData ) ) )
+            {
+                eErr = CE_Failure;
+                CPLError( CE_Failure, CPLE_UserInterrupt,
+                    "User terminated CreateCopy()" );
+            }
+        }
+    }
+
+    CPLFree( pData );
+
+    // --------------------------------------------------------------------
+    //      Finalize
+    // --------------------------------------------------------------------
+
+    poDstDS->FlushCache();
+
+    if( pfnProgress )
+    {
+        printf( "Ouput dataset: (georaster:%s/%s@%s,%s,%d) on %s%s,%s\n",
+            poDstDS->poGeoRaster->poConnection->GetUser(),
+            poDstDS->poGeoRaster->poConnection->GetPassword(),
+            poDstDS->poGeoRaster->poConnection->GetServer(),
+            poDstDS->poGeoRaster->sDataTable.c_str(),
+            poDstDS->poGeoRaster->nRasterId,
+            poDstDS->poGeoRaster->sSchema.c_str(),
+            poDstDS->poGeoRaster->sTable.c_str(),
+            poDstDS->poGeoRaster->sColumn.c_str() );
+    }
+
+    return poDstDS;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                  IRasterIO()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::IRasterIO( GDALRWFlag eRWFlag,
+                                    int nXOff, int nYOff, int nXSize, int nYSize,
+                                    void *pData, int nBufXSize, int nBufYSize,
+                                    GDALDataType eBufType,
+                                    int nBandCount, int *panBandMap,
+                                    int nPixelSpace, int nLineSpace, int nBandSpace )
+
+{
+    if( poGeoRaster->nBandBlockSize > 1 )
+    {
+        return GDALDataset::BlockBasedRasterIO( eRWFlag,
+            nXOff, nYOff, nXSize, nYSize,
+            pData, nBufXSize, nBufYSize, eBufType,
+            nBandCount, panBandMap, nPixelSpace,
+            nLineSpace, nBandSpace );
+    }
+    else
+    {
+        return GDALDataset::IRasterIO( eRWFlag,
+            nXOff, nYOff, nXSize, nYSize,
+            pData, nBufXSize, nBufYSize, eBufType,
+            nBandCount, panBandMap,
+            nPixelSpace, nLineSpace, nBandSpace );
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                 FlushCache()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterDataset::FlushCache()
+{
+    GDALDataset::FlushCache();
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            GetGeoTransform()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::GetGeoTransform( double *padfTransform )
+{
+    if( poGeoRaster->phRPC )
+    {
+        return CE_Failure;
+    }
+
+    if( poGeoRaster->nSRID == 0 )
+    {
+        return CE_Failure;
+    }
+    
+    memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 );
+
+    bGeoTransform = true;
+
+    return CE_None;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                           GetProjectionRef()
+//  ---------------------------------------------------------------------------
+
+const char* GeoRasterDataset::GetProjectionRef( void )
+{
+    if( poGeoRaster->phRPC )
+    {
+        return "";
+    }
+
+    if( ! poGeoRaster->bIsReferenced )
+    {
+        return "";
+    }
+
+    if( poGeoRaster->nSRID == UNKNOWN_CRS || poGeoRaster->nSRID == 0 )
+    {
+        return "";
+    }
+
+    if( pszProjection )
+    {
+        return pszProjection;
+    }
+
+    OGRSpatialReference oSRS;
+
+    // --------------------------------------------------------------------
+    // Check if the SRID is a valid EPSG code
+    // --------------------------------------------------------------------
+
+    CPLPushErrorHandler( CPLQuietErrorHandler );
+
+    if( oSRS.importFromEPSG( poGeoRaster->nSRID ) == OGRERR_NONE )
+    {
+        /*
+         * Ignores the WKT from Oracle and use the one from GDAL's
+         * EPSG tables. That would ensure that other drivers/software
+         * will recognizize the parameters.
+         */
+
+        if( oSRS.exportToWkt( &pszProjection ) == OGRERR_NONE )
+        {
+            CPLPopErrorHandler();
+
+            return pszProjection;
+        }
+    }
+
+    CPLPopErrorHandler();
+
+    // --------------------------------------------------------------------
+    // Try to interpreter the WKT text
+    // --------------------------------------------------------------------
+
+    char* pszWKText = CPLStrdup( poGeoRaster->sWKText );
+
+    if( ! ( oSRS.importFromWkt( &pszWKText ) == OGRERR_NONE && oSRS.GetRoot() ) )
+    {
+        return "";
+    }
+
+    // ----------------------------------------------------------------
+    // Decorate with ORACLE Authority codes
+    // ----------------------------------------------------------------
+
+    oSRS.SetAuthority(oSRS.GetRoot()->GetValue(), "ORACLE", poGeoRaster->nSRID);
+
+    int nSpher = OWParseEPSG( oSRS.GetAttrValue("GEOGCS|DATUM|SPHEROID") );
+
+    if( nSpher > 0 )
+    {
+        oSRS.SetAuthority( "GEOGCS|DATUM|SPHEROID", "EPSG", nSpher );
+    }
+
+    int nDatum = OWParseEPSG( oSRS.GetAttrValue("GEOGCS|DATUM") );
+
+    if( nDatum > 0 )
+    {
+        oSRS.SetAuthority( "GEOGCS|DATUM", "EPSG", nDatum );
+    }
+
+    // ----------------------------------------------------------------
+    // Checks for Projection info
+    // ----------------------------------------------------------------
+
+    const char *pszProjName = oSRS.GetAttrValue( "PROJECTION" );
+
+    if( pszProjName )
+    {
+        int nProj = OWParseEPSG( pszProjName );
+
+        // ----------------------------------------------------------------
+        // Decorate with EPSG Authority
+        // ----------------------------------------------------------------
+
+        if( nProj > 0 )
+        {
+            oSRS.SetAuthority( "PROJECTION", "EPSG", nProj );
+        }
+
+        // ----------------------------------------------------------------
+        // Translate projection names to GDAL's standards
+        // ----------------------------------------------------------------
+
+        if ( EQUAL( pszProjName, "Transverse Mercator" ) )
+        {
+            oSRS.SetProjection( SRS_PT_TRANSVERSE_MERCATOR );
+        }
+        else if ( EQUAL( pszProjName, "Albers Conical Equal Area" ) )
+        {
+            oSRS.SetProjection( SRS_PT_ALBERS_CONIC_EQUAL_AREA );
+        }
+        else if ( EQUAL( pszProjName, "Azimuthal Equidistant" ) )
+        {
+            oSRS.SetProjection( SRS_PT_AZIMUTHAL_EQUIDISTANT );
+        }
+        else if ( EQUAL( pszProjName, "Miller Cylindrical" ) )
+        {
+            oSRS.SetProjection( SRS_PT_MILLER_CYLINDRICAL );
+        }
+        else if ( EQUAL( pszProjName, "Hotine Oblique Mercator" ) )
+        {
+            oSRS.SetProjection( SRS_PT_HOTINE_OBLIQUE_MERCATOR );
+        }
+        else if ( EQUAL( pszProjName, "Wagner IV" ) )
+        {
+            oSRS.SetProjection( SRS_PT_WAGNER_IV );
+        }
+        else if ( EQUAL( pszProjName, "Wagner VII" ) )
+        {
+            oSRS.SetProjection( SRS_PT_WAGNER_VII );
+        }
+        else if ( EQUAL( pszProjName, "Eckert IV" ) )
+        {
+            oSRS.SetProjection( SRS_PT_ECKERT_IV );
+        }
+        else if ( EQUAL( pszProjName, "Eckert VI" ) )
+        {
+            oSRS.SetProjection( SRS_PT_ECKERT_VI );
+        }
+        else if ( EQUAL( pszProjName, "New Zealand Map Grid" ) )
+        {
+            oSRS.SetProjection( SRS_PT_NEW_ZEALAND_MAP_GRID );
+        }
+        else if ( EQUAL( pszProjName, "Lambert Conformal Conic" ) )
+        {
+            oSRS.SetProjection( SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP );
+            //?? One ot two parameters?
+        }
+        else if ( EQUAL( pszProjName, "Lambert Azimuthal Equal Area" ) )
+        {
+            oSRS.SetProjection( SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA );
+        }
+        else if ( EQUAL( pszProjName, "Van der Grinten" ) )
+        {
+            oSRS.SetProjection( SRS_PT_VANDERGRINTEN );
+        }
+        else if ( EQUAL(
+            pszProjName, "Lambert Conformal Conic (Belgium 1972)" ) )
+        {
+            oSRS.SetProjection( SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP_BELGIUM );
+        }
+        else if ( EQUAL( pszProjName, "Cylindrical Equal Area" ) )
+        {
+            oSRS.SetProjection( SRS_PT_CYLINDRICAL_EQUAL_AREA );
+        }
+        else if ( EQUAL( pszProjName, "Interrupted Goode Homolosine" ) )
+        {
+            oSRS.SetProjection( SRS_PT_GOODE_HOMOLOSINE );
+        }
+    }
+
+    oSRS.exportToWkt( &pszProjection );
+
+    return pszProjection;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            SetGeoTransform()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::SetGeoTransform( double *padfTransform )
+{
+    memcpy( adfGeoTransform, padfTransform, sizeof( double ) * 6 );
+
+    poGeoRaster->dfXCoefficient[0] = adfGeoTransform[1];
+    poGeoRaster->dfXCoefficient[1] = adfGeoTransform[2];
+    poGeoRaster->dfXCoefficient[2] = adfGeoTransform[0];
+    poGeoRaster->dfYCoefficient[0] = adfGeoTransform[4];
+    poGeoRaster->dfYCoefficient[1] = adfGeoTransform[5];
+    poGeoRaster->dfYCoefficient[2] = adfGeoTransform[3];
+
+    bGeoTransform = true;
+
+    return CE_None;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              SetProjection()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::SetProjection( const char *pszProjString )
+{
+    OGRSpatialReference oSRS;
+
+    char* pszWKT = CPLStrdup( pszProjString );
+
+    OGRErr eOGRErr = oSRS.importFromWkt( &pszWKT );
+
+    if( eOGRErr != OGRERR_NONE )
+    {
+        poGeoRaster->SetGeoReference( DEFAULT_CRS );
+
+        return CE_Failure;
+    }
+
+    // --------------------------------------------------------------------
+    // Try to extract EPGS authority code
+    // --------------------------------------------------------------------
+
+    const char *pszAuthName = NULL, *pszAuthCode = NULL;
+
+    if( oSRS.IsGeographic() )
+    {
+        pszAuthName = oSRS.GetAuthorityName( "GEOGCS" );
+        pszAuthCode = oSRS.GetAuthorityCode( "GEOGCS" );
+    }
+    else if( oSRS.IsProjected() )
+    {
+        pszAuthName = oSRS.GetAuthorityName( "PROJCS" );
+        pszAuthCode = oSRS.GetAuthorityCode( "PROJCS" );
+    }
+
+    if( pszAuthName != NULL && pszAuthCode != NULL )
+    {
+        if( EQUAL( pszAuthName, "ORACLE" ) || 
+            EQUAL( pszAuthName, "EPSG" ) )
+        {
+            poGeoRaster->SetGeoReference( atoi( pszAuthCode ) );
+            return CE_None;
+        }
+    }
+
+    // ----------------------------------------------------------------
+    // Convert SRS into old style format (SF-SQL 1.0)
+    // ----------------------------------------------------------------
+
+    OGRSpatialReference *poSRS2 = oSRS.Clone();
+    
+    poSRS2->StripCTParms();
+
+    double dfAngularUnits = poSRS2->GetAngularUnits( NULL );
+    
+    if( fabs(dfAngularUnits - 0.0174532925199433) < 0.0000000000000010 )
+    {
+        /* match the precision used on Oracle for that particular value */
+
+        poSRS2->SetAngularUnits( "Decimal Degree", 0.0174532925199433 );
+    }
+
+    char* pszCloneWKT = NULL;
+
+    if( poSRS2->exportToWkt( &pszCloneWKT ) != OGRERR_NONE )
+    {
+        delete poSRS2;
+        return CE_Failure;
+    }
+    
+    // --------------------------------------------------------------------
+    // Search by simplified WKT or insert it as a user defined
+    // --------------------------------------------------------------------
+
+    OWConnection* poConnection  = poGeoRaster->poConnection;
+    OWStatement* poStmt = NULL;
+    int nMaxSRID = 0;
+
+    poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "DECLARE\n"
+        "  MAX_SRID NUMBER := 0;\n"
+        "BEGIN\n"
+        "  SELECT SRID INTO MAX_SRID FROM MDSYS.CS_SRS WHERE WKTEXT = '%s';\n"
+        "  EXCEPTION\n"
+        "    WHEN no_data_found THEN\n"
+        "      SELECT MAX(SRID) INTO MAX_SRID FROM MDSYS.CS_SRS;\n"
+        "      MAX_SRID := MAX_SRID + 1;\n"
+        "      INSERT INTO MDSYS.CS_SRS (SRID, WKTEXT, CS_NAME)\n"
+        "        VALUES (MAX_SRID, '%s', '%s');\n"
+        "END;",
+            pszCloneWKT,
+            pszCloneWKT,
+            oSRS.GetRoot()->GetChild(0)->GetValue() ) );
+
+    poStmt->Define( &nMaxSRID );
+
+    CPLErr eError = CE_None;
+
+    if( poStmt->Execute() )
+    {
+        poGeoRaster->SetGeoReference( nMaxSRID ); //TODO change that method
+        poGeoRaster->sWKText = pszCloneWKT;
+    }
+    else
+    {
+        poGeoRaster->SetGeoReference( UNKNOWN_CRS );
+        poGeoRaster->sWKText = "";
+
+        CPLError( CE_Warning, CPLE_UserInterrupt,
+            "Insufficient privileges to insert reference system to "
+            "MDSYS.CS_SRS table." );
+        eError = CE_Warning;
+    }
+
+    CPLFree( pszCloneWKT );
+    
+    return eError;
+}
+
+/************************************************************************/
+/*                      GetMetadataDomainList()                         */
+/************************************************************************/
+
+char **GeoRasterDataset::GetMetadataDomainList()
+{
+    return BuildMetadataDomainList(GDALDataset::GetMetadataDomainList(),
+                                   TRUE,
+                                   "SUBDATASETS", NULL);
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                GetMetadata()
+//  ---------------------------------------------------------------------------
+
+char **GeoRasterDataset::GetMetadata( const char *pszDomain )
+{
+    if( pszDomain != NULL && EQUALN( pszDomain, "SUBDATASETS", 11 ) )
+        return papszSubdatasets;
+    else
+        return GDALDataset::GetMetadata( pszDomain );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     Delete()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::Delete( const char* pszFilename )
+{
+    (void) pszFilename;
+/***
+    GeoRasterDataset* poGRD = NULL;
+
+    poGRD = (GeoRasterDataset*) GDALOpen( pszFilename, GA_Update );
+
+    if( ! poGRD )
+    {
+        return CE_Failure;
+    }
+
+    if( ! poGRD->poGeoRaster->Delete() )
+    {
+        return CE_Failure;
+    }
+***/
+    return CE_None;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                             SetSubdatasets()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterDataset::SetSubdatasets( GeoRasterWrapper* poGRW )
+{
+    OWConnection* poConnection  = poGRW->poConnection;
+    OWStatement* poStmt = NULL;
+
+    //  -----------------------------------------------------------
+    //  List all the GeoRaster Tables of that User/Database
+    //  -----------------------------------------------------------
+
+    if( poGRW->sTable.empty() &&
+        poGRW->sColumn.empty() )
+    {
+        poStmt = poConnection->CreateStatement( 
+            "SELECT   DISTINCT TABLE_NAME, OWNER FROM ALL_SDO_GEOR_SYSDATA\n"
+            "  ORDER  BY TABLE_NAME ASC" );
+        
+        char szTable[OWNAME];
+        char szOwner[OWNAME];
+
+        poStmt->Define( szTable );
+        poStmt->Define( szOwner );
+
+        if( poStmt->Execute() )
+        {
+            int nCount = 1;
+
+            do
+            {
+                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                    CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
+                    CPLSPrintf( "geor:%s/%s@%s,%s.%s",
+                        poConnection->GetUser(), poConnection->GetPassword(),
+                        poConnection->GetServer(), szOwner, szTable ) );
+
+                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                    CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
+                    CPLSPrintf( "%s.Table=%s", szOwner, szTable ) );
+
+                nCount++;
+            }
+            while( poStmt->Fetch() );
+        }
+
+        return;
+    }
+
+    //  -----------------------------------------------------------
+    //  List all the GeoRaster Columns of that Table
+    //  -----------------------------------------------------------
+
+    if( ! poGRW->sTable.empty() &&
+          poGRW->sColumn.empty() )
+    {
+        poStmt = poConnection->CreateStatement( CPLSPrintf(
+            "SELECT   DISTINCT COLUMN_NAME, OWNER FROM ALL_SDO_GEOR_SYSDATA\n"
+            "  WHERE  TABLE_NAME = UPPER('%s')\n"
+            "  ORDER  BY COLUMN_NAME ASC",
+                poGRW->sTable.c_str() ) );
+
+        char szColumn[OWNAME];
+        char szOwner[OWNAME];
+
+        poStmt->Define( szColumn );
+        poStmt->Define( szOwner );
+        
+        if( poStmt->Execute() )
+        {
+            int nCount = 1;
+
+            do
+            {
+                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                    CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
+                    CPLSPrintf( "geor:%s/%s@%s,%s.%s,%s",
+                        poConnection->GetUser(), poConnection->GetPassword(),
+                        poConnection->GetServer(), szOwner,
+                        poGRW->sTable.c_str(), szColumn ) );
+
+                papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                    CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
+                    CPLSPrintf( "Table=%s.%s Column=%s", szOwner,
+                        poGRW->sTable.c_str(), szColumn ) );
+
+                nCount++;
+            }
+            while( poStmt->Fetch() );
+        }
+        
+        return;
+    }
+
+    //  -----------------------------------------------------------
+    //  List all the rows that contains GeoRaster on Table/Column/Where
+    //  -----------------------------------------------------------
+
+    CPLString osAndWhere = "";
+
+    if( ! poGRW->sWhere.empty() )
+    {
+        osAndWhere = CPLSPrintf( "AND %s", poGRW->sWhere.c_str() );
+    }
+
+    poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "SELECT T.%s.RASTERDATATABLE, T.%s.RASTERID, \n"
+        "  extractValue(t.%s.metadata, "
+"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"ROW\"]/size','%s'),\n"
+        "  extractValue(t.%s.metadata, "
+"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"COLUMN\"]/size','%s'),\n"
+        "  extractValue(t.%s.metadata, "
+"'/georasterMetadata/rasterInfo/dimensionSize[@type=\"BAND\"]/size','%s'),\n"
+        "  extractValue(t.%s.metadata, "
+"'/georasterMetadata/rasterInfo/cellDepth','%s'),\n"
+        "  extractValue(t.%s.metadata, "
+"'/georasterMetadata/spatialReferenceInfo/SRID','%s')\n"
+        "  FROM   %s%s T\n"
+        "  WHERE  %s IS NOT NULL %s\n"
+        "  ORDER  BY T.%s.RASTERDATATABLE ASC,\n"
+        "            T.%s.RASTERID ASC",
+        poGRW->sColumn.c_str(), poGRW->sColumn.c_str(),
+        poGRW->sColumn.c_str(), OW_XMLNS,
+        poGRW->sColumn.c_str(), OW_XMLNS,
+        poGRW->sColumn.c_str(), OW_XMLNS,
+        poGRW->sColumn.c_str(), OW_XMLNS,
+        poGRW->sColumn.c_str(), OW_XMLNS,
+        poGRW->sSchema.c_str(), poGRW->sTable.c_str(),
+        poGRW->sColumn.c_str(), osAndWhere.c_str(),
+        poGRW->sColumn.c_str(), poGRW->sColumn.c_str() ) );
+
+    char szDataTable[OWNAME];
+    char szRasterId[OWNAME];
+    char szRows[OWNAME];
+    char szColumns[OWNAME];
+    char szBands[OWNAME];
+    char szCellDepth[OWNAME];
+    char szSRID[OWNAME];
+
+    poStmt->Define( szDataTable );
+    poStmt->Define( szRasterId );
+    poStmt->Define( szRows );
+    poStmt->Define( szColumns );
+    poStmt->Define( szBands );
+    poStmt->Define( szCellDepth );
+    poStmt->Define( szSRID );
+
+    if( poStmt->Execute() )
+    {
+        int nCount = 1;
+
+        do
+        {
+            papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                CPLSPrintf( "SUBDATASET_%d_NAME", nCount ),
+                CPLSPrintf( "geor:%s/%s@%s,%s,%s",
+                    poConnection->GetUser(), poConnection->GetPassword(),
+                    poConnection->GetServer(), szDataTable, szRasterId ) );
+
+            const char* pszXBands = "";
+
+            if( ! EQUAL( szBands, "" ) )
+            {
+                pszXBands = CPLSPrintf( "x%s", szBands );
+            }
+
+            papszSubdatasets = CSLSetNameValue( papszSubdatasets,
+                CPLSPrintf( "SUBDATASET_%d_DESC", nCount ),
+                CPLSPrintf( "[%sx%s%s] CellDepth=%s SRID=%s",
+                    szRows, szColumns, pszXBands,
+                    szCellDepth, szSRID ) );
+
+            nCount++;
+        }
+        while( poStmt->Fetch() );
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                    SetGCPs()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::SetGCPs( int, const GDAL_GCP *, const char * )
+{
+    return CE_None;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                           GetGCPProjection()
+//  ---------------------------------------------------------------------------
+
+const char* GeoRasterDataset::GetGCPProjection()
+
+{
+    if( nGCPCount > 0 )
+        return pszProjection;
+    else
+        return "";
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            IBuildOverviews()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::IBuildOverviews( const char* pszResampling,
+                                          int nOverviews,
+                                          int* panOverviewList,
+                                          int nListBands,
+                                          int* panBandList,
+                                          GDALProgressFunc pfnProgress,
+                                          void* pProgressData )
+{
+    (void) panBandList;
+    (void) nListBands;
+
+    //  ---------------------------------------------------------------
+    //  Can't update on read-only access mode
+    //  ---------------------------------------------------------------
+
+    if( GetAccess() != GA_Update )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+            "Can't build overviews/pyramids on read-only access." );
+        return CE_Failure;
+    }
+
+    //  ---------------------------------------------------------------
+    //  Uses internal sdo_generatePyramid at PL/SQL?
+    //  ---------------------------------------------------------------
+
+    bool bInternal = true;
+
+    const char *pszGEOR_INTERNAL_PYR = CPLGetConfigOption( "GEOR_INTERNAL_PYR",
+        "YES" );
+
+    if( EQUAL(pszGEOR_INTERNAL_PYR, "NO") )
+    {
+        bInternal = false;
+    }
+        
+    //  -----------------------------------------------------------
+    //  Pyramids applies to the whole dataset not to a specific band
+    //  -----------------------------------------------------------
+
+    if( nBands < GetRasterCount())
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+            "Invalid GeoRaster Pyramids band selection" );
+        return CE_Failure;
+    }
+
+    //  ---------------------------------------------------------------
+    //  Initialize progress reporting
+    //  ---------------------------------------------------------------
+
+    if( ! pfnProgress( 0.1, NULL, pProgressData ) )
+    {
+        CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
+        return CE_Failure;
+    }
+
+    //  ---------------------------------------------------------------
+    //  Clear existing overviews
+    //  ---------------------------------------------------------------
+
+    if( nOverviews == 0 )
+    {
+        poGeoRaster->DeletePyramid();
+        return CE_None;
+    }
+
+    //  -----------------------------------------------------------
+    //  Pyramids levels can not be treated individually
+    //  -----------------------------------------------------------
+
+    if( nOverviews > 0 )
+    {
+        int i;
+        for( i = 1; i < nOverviews; i++ )
+        {
+            //  -----------------------------------------------------------
+            //  Power of 2, starting on 2, e.g. 2, 4, 8, 16, 32, 64, 128
+            //  -----------------------------------------------------------
+
+            if( panOverviewList[0] != 2 ||
+              ( panOverviewList[i] != panOverviewList[i-1] * 2 ) )
+            {
+                CPLError( CE_Failure, CPLE_AppDefined,
+                    "Invalid GeoRaster Pyramids levels." );        
+                return CE_Failure;
+            }
+        }
+    }
+
+    //  -----------------------------------------------------------
+    //  Re-sampling method: 
+    //    NN, BILINEAR, AVERAGE4, AVERAGE16 and CUBIC
+    //  -----------------------------------------------------------
+
+    char szMethod[OWNAME];
+
+    if( EQUAL( pszResampling, "NEAREST" ) )
+    {
+        strcpy( szMethod, "NN" );
+    }
+    else if( EQUALN( pszResampling, "AVERAGE", 7 ) )
+    {
+        strcpy( szMethod, "AVERAGE4" );
+    }
+    else
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, "Invalid resampling method" );
+        return CE_Failure;
+    }
+
+    //  -----------------------------------------------------------
+    //  Generate pyramids on poGeoRaster
+    //  -----------------------------------------------------------
+
+    if( ! poGeoRaster->GeneratePyramid( nOverviews, szMethod, bInternal ) )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, "Error generating pyramid" );
+        return CE_Failure;
+    }
+
+    //  -----------------------------------------------------------
+    //  If Pyramid was done internally on the server exit here
+    //  -----------------------------------------------------------
+    
+    if( bInternal )
+    {
+        pfnProgress( 1 , NULL, pProgressData );
+        return CE_None;
+    }
+
+    //  -----------------------------------------------------------
+    //  Load the pyramids data using GDAL methods
+    //  -----------------------------------------------------------
+
+    CPLErr eErr = CE_None;
+
+    int i = 0;
+
+    for( i = 0; i < nBands; i++ )
+    {
+        GeoRasterRasterBand* poBand = (GeoRasterRasterBand*) papoBands[i];
+
+        //  -------------------------------------------------------
+        //  Clean up previous overviews
+        //  -------------------------------------------------------
+
+        int j = 0;
+
+        if( poBand->nOverviewCount && poBand->papoOverviews )
+        {
+            for( j = 0; j < poBand->nOverviewCount; j++ )
+            {
+                delete poBand->papoOverviews[j];
+            }
+            CPLFree( poBand->papoOverviews );
+        }
+
+        //  -------------------------------------------------------
+        //  Create new band's overviews list
+        //  -------------------------------------------------------
+
+        poBand->nOverviewCount = poGeoRaster->nPyramidMaxLevel;
+        poBand->papoOverviews  = (GeoRasterRasterBand**) VSIMalloc(
+                sizeof(GeoRasterRasterBand*) * poBand->nOverviewCount );
+
+        for( j = 0; j < poBand->nOverviewCount; j++ )
+        {
+          poBand->papoOverviews[j] = new GeoRasterRasterBand(
+                (GeoRasterDataset*) this, ( i + 1 ), ( j + 1 ) );
+        }
+    }
+
+    //  -----------------------------------------------------------
+    //  Load band's overviews
+    //  -----------------------------------------------------------
+
+    for( i = 0; i < nBands; i++ )
+    {
+        GeoRasterRasterBand* poBand = (GeoRasterRasterBand*) papoBands[i];
+
+        void *pScaledProgressData = GDALCreateScaledProgress( 
+            i / (double) nBands, ( i + 1) / (double) nBands, 
+            pfnProgress, pProgressData );
+
+        eErr = GDALRegenerateOverviews(
+            (GDALRasterBandH) poBand,
+            poBand->nOverviewCount,
+            (GDALRasterBandH*) poBand->papoOverviews,
+            pszResampling,
+            GDALScaledProgress,
+            pScaledProgressData );
+
+        GDALDestroyScaledProgress( pScaledProgressData );
+    }
+
+    return eErr;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                             CreateMaskBand()
+//  ---------------------------------------------------------------------------
+
+CPLErr GeoRasterDataset::CreateMaskBand( int nFlags )
+{
+    (void) nFlags;
+
+    if( ! poGeoRaster->InitializeMask( DEFAULT_BMP_MASK,
+            poGeoRaster->nRowBlockSize,
+            poGeoRaster->nColumnBlockSize,
+            poGeoRaster->nTotalRowBlocks,
+            poGeoRaster->nTotalColumnBlocks,
+            poGeoRaster->nTotalBandBlocks ) )
+    {
+        return CE_Failure;
+    }
+    
+    poGeoRaster->bHasBitmapMask = true;
+
+    return CE_None;
+}
+
+/*****************************************************************************/
+/*                          GDALRegister_GEOR                                */
+/*****************************************************************************/
+
+void CPL_DLL GDALRegister_GEOR()
+{
+    GDALDriver* poDriver;
+
+    if (! GDAL_CHECK_VERSION("GeoRaster driver"))
+        return;
+
+    if( GDALGetDriverByName( "GeoRaster" ) == NULL )
+    {
+        poDriver = new GDALDriver();
+
+        poDriver->SetDescription(  "GeoRaster" );
+        poDriver->SetMetadataItem( GDAL_DMD_LONGNAME,
+                                   "Oracle Spatial GeoRaster" );
+        poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_georaster.html" );
+        poDriver->SetMetadataItem( GDAL_DMD_SUBDATASETS, "YES" );
+        poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
+                                   "Byte UInt16 Int16 UInt32 Int32 Float32 "
+                                   "Float64 CFloat32 CFloat64" );
+        poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
+"<CreationOptionList>"
+"  <Option name='DESCRIPTION' type='string' description='Table Description'/>"
+"  <Option name='INSERT'      type='string' description='Column Values'/>"
+"  <Option name='BLOCKXSIZE'  type='int'    description='Column Block Size' "
+                                           "default='512'/>"
+"  <Option name='BLOCKYSIZE'  type='int'    description='Row Block Size' "
+                                           "default='512'/>"
+"  <Option name='BLOCKBSIZE'  type='int'    description='Band Block Size'/>"
+"  <Option name='BLOCKING'    type='string-select' default='YES'>"
+"       <Value>YES</Value>"
+"       <Value>NO</Value>"
+"       <Value>OPTIMALPADDING</Value>"
+"  </Option>"
+"  <Option name='SRID'        type='int'    description='Overwrite EPSG code'/>"
+"  <Option name='GENPYRAMID'  type='string-select' "
+" description='Generate Pyramid, inform resampling method'>"
+"       <Value>NN</Value>"
+"       <Value>BILINEAR</Value>"
+"       <Value>BIQUADRATIC</Value>"
+"       <Value>CUBIC</Value>"
+"       <Value>AVERAGE4</Value>"
+"       <Value>AVERAGE16</Value>"
+"  </Option>"
+"  <Option name='GENPYRLEVELS'  type='int'  description='Number of pyramid level to generate'/>"
+"  <Option name='OBJECTTABLE' type='boolean' "
+                                           "description='Create RDT as object table'/>"
+"  <Option name='SPATIALEXTENT' type='boolean' "
+                                           "description='Generate Spatial Extent' "
+                                           "default='TRUE'/>"
+"  <Option name='EXTENTSRID'  type='int'    description='Spatial ExtentSRID code'/>"
+"  <Option name='COORDLOCATION'    type='string-select' default='CENTER'>"
+"       <Value>CENTER</Value>"
+"       <Value>UPPERLEFT</Value>"
+"  </Option>"
+"  <Option name='VATNAME'     type='string' description='Value Attribute Table Name'/>"
+"  <Option name='NBITS'       type='int'    description='BITS for sub-byte "
+                                           "data types (1,2,4) bits'/>"
+"  <Option name='INTERLEAVE'  type='string-select'>"
+"       <Value>BSQ</Value>"
+"       <Value>BIP</Value>"
+"       <Value>BIL</Value>"
+"   </Option>"
+"  <Option name='COMPRESS'    type='string-select'>"
+"       <Value>NONE</Value>"
+"       <Value>JPEG-B</Value>"
+"       <Value>JPEG-F</Value>"
+"       <Value>DEFLATE</Value>"
+"  </Option>"
+"  <Option name='QUALITY'     type='int'    description='JPEG quality 0..100' "
+                                           "default='75'/>"
+"</CreationOptionList>" );
+
+        poDriver->pfnOpen       = GeoRasterDataset::Open;
+        poDriver->pfnCreate     = GeoRasterDataset::Create;
+        poDriver->pfnCreateCopy = GeoRasterDataset::CreateCopy;
+        poDriver->pfnIdentify   = GeoRasterDataset::Identify;
+        poDriver->pfnDelete     = GeoRasterDataset::Delete;
+
+        GetGDALDriverManager()->RegisterDriver( poDriver );
+    }
+}
diff --git a/frmts/georaster/georaster_priv.h b/frmts/georaster/georaster_priv.h
index 9ed33db..41dd5a6 100644
--- a/frmts/georaster/georaster_priv.h
+++ b/frmts/georaster/georaster_priv.h
@@ -1,471 +1,471 @@
-/******************************************************************************
- * $Id: $
- *
- * Name:     georaster_priv.h
- * Project:  Oracle Spatial GeoRaster Driver
- * Purpose:  Define C++/Private declarations
- * Author:   Ivan Lucena [ivan.lucena at oracle.com]
- *
- ******************************************************************************
- * Copyright (c) 2008, Ivan Lucena
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files ( the "Software" ),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *****************************************************************************/
-
-#ifndef _GEORASTER_PRIV_H_INCLUDED
-#define _GEORASTER_PRIV_H_INCLUDED
-
-#include "gdal.h"
-#include "gdal_priv.h"
-#include "gdal_alg.h"
-#include "gdal_rat.h"
-#include "ogr_spatialref.h"
-#include "cpl_minixml.h"
-#include "cpl_list.h"
-
-//  ---------------------------------------------------------------------------
-//  DEFLATE compression support
-//  ---------------------------------------------------------------------------
-
-#include <zlib.h>
-
-//  ---------------------------------------------------------------------------
-//  JPEG compression support
-//  ---------------------------------------------------------------------------
-
-CPL_C_START
-#include <jpeglib.h>
-CPL_C_END
-
-void jpeg_vsiio_src (j_decompress_ptr cinfo, VSILFILE * infile);
-void jpeg_vsiio_dest (j_compress_ptr cinfo, VSILFILE * outfile);
-
-//  ---------------------------------------------------------------------------
-//  System constants
-//  ---------------------------------------------------------------------------
-
-//  VAT maximum string len
-
-#define MAXLEN_VATSTR 128
-
-//  Geographic system without EPSG parameters
-
-#define UNKNOWN_CRS     999999
-#define NO_CRS          0
-#define DEFAULT_CRS     NO_CRS
-
-//  Bitmap Mask for the whole dataset start with -99999
-
-#define DEFAULT_BMP_MASK -99999
-
-//  Default block size
-
-#define DEFAULT_BLOCK_ROWS 256
-#define DEFAULT_BLOCK_COLUMNS 256
-
-//  Default Model Coordinate Location (internal pixel geo-reference)
-
-#define MCL_CENTER      0
-#define MCL_UPPERLEFT   1
-#define MCL_DEFAULT     MCL_CENTER
-
-// MAX double string representation
-
-#define MAX_DOUBLE_STR_REP 20
-
-struct hLevelDetails {
-    int             nColumnBlockSize;
-    int             nRowBlockSize;
-    int             nTotalColumnBlocks;
-    int             nTotalRowBlocks;
-    unsigned long   nBlockCount;
-    unsigned long   nBlockBytes;
-    unsigned long   nGDALBlockBytes;
-    unsigned long   nOffset;
-};
-
-//  ---------------------------------------------------------------------------
-//  Support for multi-values NoData support
-//  ---------------------------------------------------------------------------
-
-struct hNoDataItem {
-    int             nBand;
-    double          dfLower;
-    double          dfUpper;
-};
-
-//  ---------------------------------------------------------------------------
-//  GeoRaster wrapper classe definitions
-//  ---------------------------------------------------------------------------
-
-#include "oci_wrapper.h"
-
-class GeoRasterDataset;
-class GeoRasterRasterBand;
-class GeoRasterWrapper;
-
-//  ---------------------------------------------------------------------------
-//  GeoRasterDataset, extends GDALDataset to support GeoRaster Datasets
-//  ---------------------------------------------------------------------------
-
-class GeoRasterDataset : public GDALDataset
-{
-    friend class GeoRasterRasterBand;
-
-public:
-                        GeoRasterDataset();
-    virtual            ~GeoRasterDataset();
-
-private:
-
-    GeoRasterWrapper*   poGeoRaster;
-    bool                bGeoTransform;
-    bool                bForcedSRID;
-    char*               pszProjection;
-    char**              papszSubdatasets;
-    double              adfGeoTransform[6];
-    int                 nGCPCount;
-    GDAL_GCP*           pasGCPList;
-    GeoRasterRasterBand*
-                        poMaskBand;
-    bool                bApplyNoDataArray;
-
-public:
-
-    void                SetSubdatasets( GeoRasterWrapper* poGRW );
-
-    static int          Identify( GDALOpenInfo* poOpenInfo );
-    static GDALDataset* Open( GDALOpenInfo* poOpenInfo );
-    static CPLErr       Delete( const char *pszFilename );
-    static GDALDataset* Create( const char* pszFilename,
-                            int nXSize,
-                            int nYSize,
-                            int nBands,
-                            GDALDataType eType,
-                            char** papszOptions );
-    static GDALDataset* CreateCopy( const char* pszFilename, 
-                            GDALDataset* poSrcDS,
-                            int bStrict,
-                            char** papszOptions,
-                            GDALProgressFunc pfnProgress, 
-                            void* pProgressData );
-    virtual CPLErr      GetGeoTransform( double* padfTransform );
-    virtual CPLErr      SetGeoTransform( double* padfTransform );
-    virtual const char* GetProjectionRef( void );
-    virtual CPLErr      SetProjection( const char* pszProjString );
-    virtual char      **GetMetadataDomainList();
-    virtual char**      GetMetadata( const char* pszDomain );
-    virtual void        FlushCache( void );
-    virtual CPLErr      IRasterIO( GDALRWFlag eRWFlag, 
-                            int nXOff, int nYOff, int nXSize, int nYSize,
-                            void *pData, int nBufXSize, int nBufYSize, 
-                            GDALDataType eBufType,
-                            int nBandCount, int *panBandMap, 
-                            int nPixelSpace, int nLineSpace, int nBandSpace );
-    virtual int         GetGCPCount() { return nGCPCount; }
-    virtual const char* GetGCPProjection();
-    virtual const GDAL_GCP*
-                        GetGCPs() { return pasGCPList; }
-    virtual CPLErr      SetGCPs(
-                            int nGCPCount,
-                            const GDAL_GCP *pasGCPList,
-                            const char *pszGCPProjection );
-    virtual CPLErr      IBuildOverviews(
-                            const char* pszResampling,
-                            int nOverviews,
-                            int* panOverviewList,
-                            int nListBandsover,
-                            int* panBandList,
-                            GDALProgressFunc pfnProgress,
-                            void* pProgresoversData );
-    virtual CPLErr      CreateMaskBand( int nFlags );
-    void                AssignGeoRaster( GeoRasterWrapper* poGRW );
-};
-
-//  ---------------------------------------------------------------------------
-//  GeoRasterRasterBand, extends GDALRasterBand to support GeoRaster Band
-//  ---------------------------------------------------------------------------
-
-class GeoRasterRasterBand : public GDALRasterBand
-{
-    friend class GeoRasterDataset;
-
-public:
-                        GeoRasterRasterBand( GeoRasterDataset* poGDS, 
-                            int nBand,
-                            int nLevel );
-    virtual            ~GeoRasterRasterBand();
-
-private:
-
-    GeoRasterWrapper*   poGeoRaster;
-    GDALColorTable*     poColorTable;
-    GDALRasterAttributeTable*
-                        poDefaultRAT;
-    double              dfMin;
-    double              dfMax;
-    double              dfMean;
-    double              dfMedian;
-    double              dfMode;
-    double              dfStdDev;
-    bool                bValidStats;
-    double              dfNoData;
-    char*               pszVATName;
-    int                 nOverviewLevel;
-    GeoRasterRasterBand** papoOverviews;
-    int                 nOverviewCount;
-    hNoDataItem*        pahNoDataArray;
-    int                 nNoDataArraySz;
-    bool                bHasNoDataArray;
-    
-    void                ApplyNoDataArry( void* pBuffer );
-
-public:
-
-    virtual double      GetNoDataValue( int *pbSuccess = NULL );
-    virtual CPLErr      SetNoDataValue( double dfNoDataValue );
-    virtual double      GetMinimum( int* pbSuccess = NULL );
-    virtual double      GetMaximum( int* pbSuccess = NULL );
-    virtual GDALColorTable* 
-                        GetColorTable();
-    virtual CPLErr      SetColorTable( GDALColorTable *poInColorTable ); 
-    virtual GDALColorInterp   
-                        GetColorInterpretation();
-    virtual CPLErr      IReadBlock( int nBlockXOff, int nBlockYOff, 
-                            void *pImage );
-    virtual CPLErr      IWriteBlock( int nBlockXOff, int nBlockYOff, 
-                            void *pImage );
-    virtual CPLErr      SetStatistics( double dfMin, double dfMax, 
-                            double dfMean, double dfStdDev );
-    virtual CPLErr      GetStatistics( int bApproxOK, int bForce,
-                            double* pdfMin, double* pdfMax, 
-                            double* pdfMean, double* pdfStdDev );
-    virtual             GDALRasterAttributeTable *GetDefaultRAT();
-    virtual CPLErr      SetDefaultRAT( const GDALRasterAttributeTable *poRAT );
-    virtual int         GetOverviewCount();
-    virtual GDALRasterBand*
-                        GetOverview( int );
-    virtual CPLErr      CreateMaskBand( int nFlags );
-    virtual GDALRasterBand*
-                        GetMaskBand();
-    virtual int         GetMaskFlags();
-};
-
-//  ---------------------------------------------------------------------------
-//  GeoRasterWrapper, an interface for Oracle Spatial SDO_GEORASTER objects
-//  ---------------------------------------------------------------------------
-
-class GeoRasterWrapper
-{
-
-public:
-
-                        GeoRasterWrapper();
-    virtual            ~GeoRasterWrapper();
-
-private:
-
-    OCILobLocator**     pahLocator;
-    unsigned long       nBlockCount;
-    unsigned long       nBlockBytes;
-    unsigned long       nGDALBlockBytes;
-    GByte*              pabyBlockBuf;
-    GByte*              pabyCompressBuf;
-    OWStatement*        poBlockStmt;
-    OWStatement*        poStmtWrite;
-
-    int                 nCurrentLevel;
-    long                nLevelOffset;
-
-    long                nCacheBlockId;
-    bool                bFlushBlock;
-    unsigned long       nFlushBlockSize;
-
-    bool                bWriteOnly;
-
-    hLevelDetails*      pahLevels;
-
-    int                 nCellSizeBits;
-    int                 nGDALCellBytes;
-
-    bool                bUpdate;
-    bool                bInitializeIO;
-    bool                bFlushMetadata;
-
-    void                InitializeLayersNode( void );
-    bool                InitializeIO( void );
-    void                InitializeLevel( int nLevel );
-    bool                FlushMetadata( void );
-
-    void                LoadNoDataValues( void );
-
-    void                UnpackNBits( GByte* pabyData );
-    void                PackNBits( GByte* pabyData );
-    unsigned long       CompressJpeg( void );
-    unsigned long       CompressDeflate( void );
-    void                UncompressJpeg( unsigned long nBufferSize );
-    bool                UncompressDeflate( unsigned long nBufferSize );
-
-    struct jpeg_decompress_struct sDInfo;
-    struct jpeg_compress_struct sCInfo;
-    struct jpeg_error_mgr sJErr;
-
-public:
-
-    static char**       ParseIdentificator( const char* pszStringID );
-    static GeoRasterWrapper*
-                        Open( 
-                            const char* pszStringID,
-                            bool bUpdate );
-    bool                Create(
-                            char* pszDescription,
-                            char* pszInsert,
-                            bool bUpdate );
-    bool                Delete( void );
-    void                GetRasterInfo( void );
-    bool                GetStatistics( int nBand,
-                                       char* pszMin,
-                                       char* pszMax,
-                                       char* pszMean,
-                                       char* pszMedian,
-                                       char* pszMode,
-                                       char* pszStdDev,
-                                       char* pszSampling );
-    bool                SetStatistics( int nBand,
-                                       const char* pszMin,
-                                       const char* pszMax,
-                                       const char* pszMean,
-                                       const char* pszMedian,
-                                       const char* pszMode,
-                                       const char* pszStdDev,
-                                       const char* pszSampling );
-    bool                HasColorMap( int nBand );
-    void                GetColorMap( int nBand, GDALColorTable* poCT );
-    void                SetColorMap( int nBand, GDALColorTable* poCT );
-    void                SetGeoReference( int nSRIDIn );
-    bool                GetDataBlock(
-                            int nBand,
-                            int nLevel,
-                            int nXOffset,
-                            int nYOffset,
-                            void* pData );
-    bool                SetDataBlock(
-                            int nBand,
-                            int nLevel,
-                            int nXOffset,
-                            int nYOffset,
-                            void* pData );
-    long                GetBlockNumber( int nB, int nX, int nY )
-                        {
-                            return nLevelOffset +
-                                   (long) ( ( ceil( (double)
-                                   ( ( nB - 1 ) / nBandBlockSize ) ) *
-                                   nTotalColumnBlocks * nTotalRowBlocks ) +
-                                   ( nY * nTotalColumnBlocks ) + nX );
-                        }
-
-    bool                FlushBlock( long nCacheBlock );
-    bool                GetNoData( int nLayer, double* pdfNoDataValue );
-    bool                SetNoData( int nLayer, const char* pszValue );
-    CPLXMLNode*         GetMetadata() { return phMetadata; };
-    bool                SetVAT( int nBand, const char* pszName );
-    char*               GetVAT( int nBand );
-    bool                GeneratePyramid(
-                            int nLevels,
-                            const char* pszResampling,
-                            bool bInternal = false );
-    bool                DeletePyramid();
-    void                PrepareToOverwrite( void );
-    bool                InitializeMask( int nLevel,
-                                                int nBlockColumns,
-                                                int nBlockRows,
-                                                int nColumnBlocks,
-                                                int nRowBlocks,
-                                                int nBandBlocks );
-    void                SetWriteOnly( bool value ) { bWriteOnly = value; };
-    void                SetRPC();
-    void                GetRPC();
-
-public:
-
-    OWConnection*       poConnection;
-
-    CPLString           sTable;
-    CPLString           sSchema;
-    CPLString           sOwner;
-    CPLString           sColumn;
-    CPLString           sDataTable;
-    int                 nRasterId;
-    CPLString           sWhere;
-    CPLString           sValueAttributeTab;
-
-    int                 nSRID;
-    int                 nExtentSRID;
-    bool                bGenSpatialIndex;
-    bool                bCreateObjectTable;
-    CPLXMLNode*         phMetadata;
-    CPLString           sCellDepth;
-
-    bool                bGenPyramid;
-    CPLString           sPyramidResampling;
-    int                 nPyramidLevels;
-
-    CPLString           sCompressionType;
-    int                 nCompressQuality;
-    CPLString           sWKText;
-    CPLString           sAuthority;
-    CPLList*            psNoDataList;
-
-    int                 nRasterColumns;
-    int                 nRasterRows;
-    int                 nRasterBands;
-
-    CPLString           sInterleaving;
-    bool                bIsReferenced;
-
-    bool                bBlocking;
-    bool                bAutoBlocking;
-
-    double              dfXCoefficient[3];
-    double              dfYCoefficient[3];
-
-    int                 nColumnBlockSize;
-    int                 nRowBlockSize;
-    int                 nBandBlockSize;
-
-    int                 nTotalColumnBlocks;
-    int                 nTotalRowBlocks;
-    int                 nTotalBandBlocks;
-
-    int                 iDefaultRedBand;
-    int                 iDefaultGreenBand;
-    int                 iDefaultBlueBand;
-
-    int                 nPyramidMaxLevel;
-
-    bool                bHasBitmapMask;
-    bool                bUniqueFound;
-    
-    int                 eModelCoordLocation;
-    unsigned int        anULTCoordinate[3];
-
-    GDALRPCInfo*        phRPC;
-};
-
-#endif /* ifndef _GEORASTER_PRIV_H_INCLUDED */
+/******************************************************************************
+ * $Id: $
+ *
+ * Name:     georaster_priv.h
+ * Project:  Oracle Spatial GeoRaster Driver
+ * Purpose:  Define C++/Private declarations
+ * Author:   Ivan Lucena [ivan.lucena at oracle.com]
+ *
+ ******************************************************************************
+ * Copyright (c) 2008, Ivan Lucena
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files ( the "Software" ),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *****************************************************************************/
+
+#ifndef _GEORASTER_PRIV_H_INCLUDED
+#define _GEORASTER_PRIV_H_INCLUDED
+
+#include "gdal.h"
+#include "gdal_priv.h"
+#include "gdal_alg.h"
+#include "gdal_rat.h"
+#include "ogr_spatialref.h"
+#include "cpl_minixml.h"
+#include "cpl_list.h"
+
+//  ---------------------------------------------------------------------------
+//  DEFLATE compression support
+//  ---------------------------------------------------------------------------
+
+#include <zlib.h>
+
+//  ---------------------------------------------------------------------------
+//  JPEG compression support
+//  ---------------------------------------------------------------------------
+
+CPL_C_START
+#include <jpeglib.h>
+CPL_C_END
+
+void jpeg_vsiio_src (j_decompress_ptr cinfo, VSILFILE * infile);
+void jpeg_vsiio_dest (j_compress_ptr cinfo, VSILFILE * outfile);
+
+//  ---------------------------------------------------------------------------
+//  System constants
+//  ---------------------------------------------------------------------------
+
+//  VAT maximum string len
+
+#define MAXLEN_VATSTR 128
+
+//  Geographic system without EPSG parameters
+
+#define UNKNOWN_CRS     999999
+#define NO_CRS          0
+#define DEFAULT_CRS     NO_CRS
+
+//  Bitmap Mask for the whole dataset start with -99999
+
+#define DEFAULT_BMP_MASK -99999
+
+//  Default block size
+
+#define DEFAULT_BLOCK_ROWS 256
+#define DEFAULT_BLOCK_COLUMNS 256
+
+//  Default Model Coordinate Location (internal pixel geo-reference)
+
+#define MCL_CENTER      0
+#define MCL_UPPERLEFT   1
+#define MCL_DEFAULT     MCL_CENTER
+
+// MAX double string representation
+
+#define MAX_DOUBLE_STR_REP 20
+
+struct hLevelDetails {
+    int             nColumnBlockSize;
+    int             nRowBlockSize;
+    int             nTotalColumnBlocks;
+    int             nTotalRowBlocks;
+    unsigned long   nBlockCount;
+    unsigned long   nBlockBytes;
+    unsigned long   nGDALBlockBytes;
+    unsigned long   nOffset;
+};
+
+//  ---------------------------------------------------------------------------
+//  Support for multi-values NoData support
+//  ---------------------------------------------------------------------------
+
+struct hNoDataItem {
+    int             nBand;
+    double          dfLower;
+    double          dfUpper;
+};
+
+//  ---------------------------------------------------------------------------
+//  GeoRaster wrapper classe definitions
+//  ---------------------------------------------------------------------------
+
+#include "oci_wrapper.h"
+
+class GeoRasterDataset;
+class GeoRasterRasterBand;
+class GeoRasterWrapper;
+
+//  ---------------------------------------------------------------------------
+//  GeoRasterDataset, extends GDALDataset to support GeoRaster Datasets
+//  ---------------------------------------------------------------------------
+
+class GeoRasterDataset : public GDALDataset
+{
+    friend class GeoRasterRasterBand;
+
+public:
+                        GeoRasterDataset();
+    virtual            ~GeoRasterDataset();
+
+private:
+
+    GeoRasterWrapper*   poGeoRaster;
+    bool                bGeoTransform;
+    bool                bForcedSRID;
+    char*               pszProjection;
+    char**              papszSubdatasets;
+    double              adfGeoTransform[6];
+    int                 nGCPCount;
+    GDAL_GCP*           pasGCPList;
+    GeoRasterRasterBand*
+                        poMaskBand;
+    bool                bApplyNoDataArray;
+
+public:
+
+    void                SetSubdatasets( GeoRasterWrapper* poGRW );
+
+    static int          Identify( GDALOpenInfo* poOpenInfo );
+    static GDALDataset* Open( GDALOpenInfo* poOpenInfo );
+    static CPLErr       Delete( const char *pszFilename );
+    static GDALDataset* Create( const char* pszFilename,
+                            int nXSize,
+                            int nYSize,
+                            int nBands,
+                            GDALDataType eType,
+                            char** papszOptions );
+    static GDALDataset* CreateCopy( const char* pszFilename, 
+                            GDALDataset* poSrcDS,
+                            int bStrict,
+                            char** papszOptions,
+                            GDALProgressFunc pfnProgress, 
+                            void* pProgressData );
+    virtual CPLErr      GetGeoTransform( double* padfTransform );
+    virtual CPLErr      SetGeoTransform( double* padfTransform );
+    virtual const char* GetProjectionRef( void );
+    virtual CPLErr      SetProjection( const char* pszProjString );
+    virtual char      **GetMetadataDomainList();
+    virtual char**      GetMetadata( const char* pszDomain );
+    virtual void        FlushCache( void );
+    virtual CPLErr      IRasterIO( GDALRWFlag eRWFlag, 
+                            int nXOff, int nYOff, int nXSize, int nYSize,
+                            void *pData, int nBufXSize, int nBufYSize, 
+                            GDALDataType eBufType,
+                            int nBandCount, int *panBandMap, 
+                            int nPixelSpace, int nLineSpace, int nBandSpace );
+    virtual int         GetGCPCount() { return nGCPCount; }
+    virtual const char* GetGCPProjection();
+    virtual const GDAL_GCP*
+                        GetGCPs() { return pasGCPList; }
+    virtual CPLErr      SetGCPs(
+                            int nGCPCount,
+                            const GDAL_GCP *pasGCPList,
+                            const char *pszGCPProjection );
+    virtual CPLErr      IBuildOverviews(
+                            const char* pszResampling,
+                            int nOverviews,
+                            int* panOverviewList,
+                            int nListBandsover,
+                            int* panBandList,
+                            GDALProgressFunc pfnProgress,
+                            void* pProgresoversData );
+    virtual CPLErr      CreateMaskBand( int nFlags );
+    void                AssignGeoRaster( GeoRasterWrapper* poGRW );
+};
+
+//  ---------------------------------------------------------------------------
+//  GeoRasterRasterBand, extends GDALRasterBand to support GeoRaster Band
+//  ---------------------------------------------------------------------------
+
+class GeoRasterRasterBand : public GDALRasterBand
+{
+    friend class GeoRasterDataset;
+
+public:
+                        GeoRasterRasterBand( GeoRasterDataset* poGDS, 
+                            int nBand,
+                            int nLevel );
+    virtual            ~GeoRasterRasterBand();
+
+private:
+
+    GeoRasterWrapper*   poGeoRaster;
+    GDALColorTable*     poColorTable;
+    GDALRasterAttributeTable*
+                        poDefaultRAT;
+    double              dfMin;
+    double              dfMax;
+    double              dfMean;
+    double              dfMedian;
+    double              dfMode;
+    double              dfStdDev;
+    bool                bValidStats;
+    double              dfNoData;
+    char*               pszVATName;
+    int                 nOverviewLevel;
+    GeoRasterRasterBand** papoOverviews;
+    int                 nOverviewCount;
+    hNoDataItem*        pahNoDataArray;
+    int                 nNoDataArraySz;
+    bool                bHasNoDataArray;
+    
+    void                ApplyNoDataArry( void* pBuffer );
+
+public:
+
+    virtual double      GetNoDataValue( int *pbSuccess = NULL );
+    virtual CPLErr      SetNoDataValue( double dfNoDataValue );
+    virtual double      GetMinimum( int* pbSuccess = NULL );
+    virtual double      GetMaximum( int* pbSuccess = NULL );
+    virtual GDALColorTable* 
+                        GetColorTable();
+    virtual CPLErr      SetColorTable( GDALColorTable *poInColorTable ); 
+    virtual GDALColorInterp   
+                        GetColorInterpretation();
+    virtual CPLErr      IReadBlock( int nBlockXOff, int nBlockYOff, 
+                            void *pImage );
+    virtual CPLErr      IWriteBlock( int nBlockXOff, int nBlockYOff, 
+                            void *pImage );
+    virtual CPLErr      SetStatistics( double dfMin, double dfMax, 
+                            double dfMean, double dfStdDev );
+    virtual CPLErr      GetStatistics( int bApproxOK, int bForce,
+                            double* pdfMin, double* pdfMax, 
+                            double* pdfMean, double* pdfStdDev );
+    virtual             GDALRasterAttributeTable *GetDefaultRAT();
+    virtual CPLErr      SetDefaultRAT( const GDALRasterAttributeTable *poRAT );
+    virtual int         GetOverviewCount();
+    virtual GDALRasterBand*
+                        GetOverview( int );
+    virtual CPLErr      CreateMaskBand( int nFlags );
+    virtual GDALRasterBand*
+                        GetMaskBand();
+    virtual int         GetMaskFlags();
+};
+
+//  ---------------------------------------------------------------------------
+//  GeoRasterWrapper, an interface for Oracle Spatial SDO_GEORASTER objects
+//  ---------------------------------------------------------------------------
+
+class GeoRasterWrapper
+{
+
+public:
+
+                        GeoRasterWrapper();
+    virtual            ~GeoRasterWrapper();
+
+private:
+
+    OCILobLocator**     pahLocator;
+    unsigned long       nBlockCount;
+    unsigned long       nBlockBytes;
+    unsigned long       nGDALBlockBytes;
+    GByte*              pabyBlockBuf;
+    GByte*              pabyCompressBuf;
+    OWStatement*        poBlockStmt;
+    OWStatement*        poStmtWrite;
+
+    int                 nCurrentLevel;
+    long                nLevelOffset;
+
+    long                nCacheBlockId;
+    bool                bFlushBlock;
+    unsigned long       nFlushBlockSize;
+
+    bool                bWriteOnly;
+
+    hLevelDetails*      pahLevels;
+
+    int                 nCellSizeBits;
+    int                 nGDALCellBytes;
+
+    bool                bUpdate;
+    bool                bInitializeIO;
+    bool                bFlushMetadata;
+
+    void                InitializeLayersNode( void );
+    bool                InitializeIO( void );
+    void                InitializeLevel( int nLevel );
+    bool                FlushMetadata( void );
+
+    void                LoadNoDataValues( void );
+
+    void                UnpackNBits( GByte* pabyData );
+    void                PackNBits( GByte* pabyData );
+    unsigned long       CompressJpeg( void );
+    unsigned long       CompressDeflate( void );
+    void                UncompressJpeg( unsigned long nBufferSize );
+    bool                UncompressDeflate( unsigned long nBufferSize );
+
+    struct jpeg_decompress_struct sDInfo;
+    struct jpeg_compress_struct sCInfo;
+    struct jpeg_error_mgr sJErr;
+
+public:
+
+    static char**       ParseIdentificator( const char* pszStringID );
+    static GeoRasterWrapper*
+                        Open( 
+                            const char* pszStringID,
+                            bool bUpdate );
+    bool                Create(
+                            char* pszDescription,
+                            char* pszInsert,
+                            bool bUpdate );
+    bool                Delete( void );
+    void                GetRasterInfo( void );
+    bool                GetStatistics( int nBand,
+                                       char* pszMin,
+                                       char* pszMax,
+                                       char* pszMean,
+                                       char* pszMedian,
+                                       char* pszMode,
+                                       char* pszStdDev,
+                                       char* pszSampling );
+    bool                SetStatistics( int nBand,
+                                       const char* pszMin,
+                                       const char* pszMax,
+                                       const char* pszMean,
+                                       const char* pszMedian,
+                                       const char* pszMode,
+                                       const char* pszStdDev,
+                                       const char* pszSampling );
+    bool                HasColorMap( int nBand );
+    void                GetColorMap( int nBand, GDALColorTable* poCT );
+    void                SetColorMap( int nBand, GDALColorTable* poCT );
+    void                SetGeoReference( int nSRIDIn );
+    bool                GetDataBlock(
+                            int nBand,
+                            int nLevel,
+                            int nXOffset,
+                            int nYOffset,
+                            void* pData );
+    bool                SetDataBlock(
+                            int nBand,
+                            int nLevel,
+                            int nXOffset,
+                            int nYOffset,
+                            void* pData );
+    long                GetBlockNumber( int nB, int nX, int nY )
+                        {
+                            return nLevelOffset +
+                                   (long) ( ( ceil( (double)
+                                   ( ( nB - 1 ) / nBandBlockSize ) ) *
+                                   nTotalColumnBlocks * nTotalRowBlocks ) +
+                                   ( nY * nTotalColumnBlocks ) + nX );
+                        }
+
+    bool                FlushBlock( long nCacheBlock );
+    bool                GetNoData( int nLayer, double* pdfNoDataValue );
+    bool                SetNoData( int nLayer, const char* pszValue );
+    CPLXMLNode*         GetMetadata() { return phMetadata; };
+    bool                SetVAT( int nBand, const char* pszName );
+    char*               GetVAT( int nBand );
+    bool                GeneratePyramid(
+                            int nLevels,
+                            const char* pszResampling,
+                            bool bInternal = false );
+    bool                DeletePyramid();
+    void                PrepareToOverwrite( void );
+    bool                InitializeMask( int nLevel,
+                                                int nBlockColumns,
+                                                int nBlockRows,
+                                                int nColumnBlocks,
+                                                int nRowBlocks,
+                                                int nBandBlocks );
+    void                SetWriteOnly( bool value ) { bWriteOnly = value; };
+    void                SetRPC();
+    void                GetRPC();
+
+public:
+
+    OWConnection*       poConnection;
+
+    CPLString           sTable;
+    CPLString           sSchema;
+    CPLString           sOwner;
+    CPLString           sColumn;
+    CPLString           sDataTable;
+    int                 nRasterId;
+    CPLString           sWhere;
+    CPLString           sValueAttributeTab;
+
+    int                 nSRID;
+    int                 nExtentSRID;
+    bool                bGenSpatialIndex;
+    bool                bCreateObjectTable;
+    CPLXMLNode*         phMetadata;
+    CPLString           sCellDepth;
+
+    bool                bGenPyramid;
+    CPLString           sPyramidResampling;
+    int                 nPyramidLevels;
+
+    CPLString           sCompressionType;
+    int                 nCompressQuality;
+    CPLString           sWKText;
+    CPLString           sAuthority;
+    CPLList*            psNoDataList;
+
+    int                 nRasterColumns;
+    int                 nRasterRows;
+    int                 nRasterBands;
+
+    CPLString           sInterleaving;
+    bool                bIsReferenced;
+
+    bool                bBlocking;
+    bool                bAutoBlocking;
+
+    double              dfXCoefficient[3];
+    double              dfYCoefficient[3];
+
+    int                 nColumnBlockSize;
+    int                 nRowBlockSize;
+    int                 nBandBlockSize;
+
+    int                 nTotalColumnBlocks;
+    int                 nTotalRowBlocks;
+    int                 nTotalBandBlocks;
+
+    int                 iDefaultRedBand;
+    int                 iDefaultGreenBand;
+    int                 iDefaultBlueBand;
+
+    int                 nPyramidMaxLevel;
+
+    bool                bHasBitmapMask;
+    bool                bUniqueFound;
+    
+    int                 eModelCoordLocation;
+    unsigned int        anULTCoordinate[3];
+
+    GDALRPCInfo*        phRPC;
+};
+
+#endif /* ifndef _GEORASTER_PRIV_H_INCLUDED */
diff --git a/frmts/georaster/georaster_wrapper.cpp b/frmts/georaster/georaster_wrapper.cpp
index 47fa93d..8b8fece 100644
--- a/frmts/georaster/georaster_wrapper.cpp
+++ b/frmts/georaster/georaster_wrapper.cpp
@@ -1,3981 +1,3990 @@
-/******************************************************************************
- * $Id: $
- *
- * Name:     georaster_wrapper.cpp
- * Project:  Oracle Spatial GeoRaster Driver
- * Purpose:  Implement GeoRasterWrapper methods
- * Author:   Ivan Lucena [ivan.lucena at oracle.com]
- *
- ******************************************************************************
- * Copyright (c) 2008, Ivan Lucena
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files ( the "Software" ),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *****************************************************************************/
-
-#include <string.h>
-
-#include "georaster_priv.h"
-#include "cpl_error.h"
-#include "cpl_string.h"
-#include "cpl_minixml.h"
-
-//  ---------------------------------------------------------------------------
-//                                                           GeoRasterWrapper()
-//  ---------------------------------------------------------------------------
-
-GeoRasterWrapper::GeoRasterWrapper()
-{
-    nRasterId           = -1;
-    phMetadata          = NULL;
-    nRasterRows         = 0;
-    nRasterColumns      = 0;
-    nRasterBands        = 0;
-    nRowBlockSize       = 0;
-    nColumnBlockSize    = 0;
-    nBandBlockSize      = 0;
-    nTotalColumnBlocks  = 0;
-    nTotalRowBlocks     = 0;
-    nTotalBandBlocks    = 0;
-    nCellSizeBits       = 0;
-    nGDALCellBytes      = 0;
-    dfXCoefficient[0]   = 1.0;
-    dfXCoefficient[1]   = 0.0;
-    dfXCoefficient[2]   = 0.0;
-    dfYCoefficient[0]   = 0.0;
-    dfYCoefficient[1]   = 1.0;
-    dfYCoefficient[2]   = 0.0;
-    sCompressionType    = "NONE";
-    nCompressQuality    = 75;
-    bGenPyramid         = false;
-    nPyramidLevels      = 0;
-    sPyramidResampling  = "NN";
-    pahLocator          = NULL;
-    pabyBlockBuf        = NULL;
-    pabyCompressBuf     = NULL;
-    bIsReferenced       = false;
-    poBlockStmt         = NULL;
-    nCacheBlockId       = -1;
-    nCurrentLevel       = -1;
-    pahLevels           = NULL;
-    nLevelOffset        = 0L;
-    sInterleaving       = "BSQ";
-    bUpdate             = false;
-    bInitializeIO       = false;
-    bFlushMetadata      = false;
-    nSRID               = 0;
-    nExtentSRID         = 0;
-    bGenSpatialIndex    = false;
-    bCreateObjectTable  = false;
-    nPyramidMaxLevel    = 0;
-    nBlockCount         = 0L;
-    nGDALBlockBytes     = 0L;
-    sDInfo.global_state = 0;
-    sCInfo.global_state = 0;
-    bHasBitmapMask      = false;
-    nBlockBytes         = 0L;
-    bFlushBlock         = false;
-    nFlushBlockSize     = 0L;
-    bUniqueFound        = false;
-    sValueAttributeTab  = "";
-    psNoDataList        = NULL;
-    bWriteOnly          = false;
-    bBlocking           = true;
-    bAutoBlocking       = false;
-    eModelCoordLocation = MCL_DEFAULT;
-    phRPC               = NULL;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                           GeoRasterDataset()
-//  ---------------------------------------------------------------------------
-
-GeoRasterWrapper::~GeoRasterWrapper()
-{
-    FlushMetadata();
-
-    if( pahLocator && nBlockCount )
-    {
-        OWStatement::Free( pahLocator, nBlockCount );
-    }
-
-    CPLFree( pahLocator );
-    CPLFree( pabyBlockBuf );
-    CPLFree( pabyCompressBuf );
-    CPLFree( pahLevels );
-    
-    if( CPLListCount( psNoDataList ) )
-    {
-        CPLList* psList = NULL;
-        
-        for( psList = psNoDataList; psList ; psList = psList->psNext )
-        {
-            CPLFree( psList->pData );
-        }
-        
-        CPLListDestroy( psNoDataList );
-    }
-
-    if( poBlockStmt )
-    {
-        delete poBlockStmt;
-    }
-
-    CPLDestroyXMLNode( phMetadata );
-    
-    if( sDInfo.global_state )
-    {
-        jpeg_destroy_decompress( &sDInfo );
-    }
-
-    if( sCInfo.global_state )
-    {
-        jpeg_destroy_compress( &sCInfo );
-    }
-
-    if( poConnection )
-    {
-        delete poConnection;
-    }
-
-    if( phRPC )
-    {
-        CPLFree( phRPC );
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                         ParseIdentificator()
-//  ---------------------------------------------------------------------------
-//
-//  StringID:
-//      {georaster,geor}:<name>{/,,}<password>{/,@}<db>,<tab>,<col>,<where>
-//      {georaster,geor}:<name>{/,,}<password>{/,@}<db>,<rdt>,<rid>
-//
-//  ---------------------------------------------------------------------------
-
-char** GeoRasterWrapper::ParseIdentificator( const char* pszStringID )
-{
-
-    char* pszStartPos = (char*) strstr( pszStringID, ":" ) + 1;
-
-    char** papszParam = CSLTokenizeString2( pszStartPos, ",@",
-                            CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS |
-                            CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES );
-
-    //  -------------------------------------------------------------------
-    //  The "/" should not be catch on the previous parser
-    //  -------------------------------------------------------------------
-
-    if( CSLCount( papszParam ) > 0 )
-    {
-        char** papszFirst2 = CSLTokenizeString2( papszParam[0], "/",
-                             CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
-        if( CSLCount( papszFirst2 ) == 2 )
-        {
-            papszParam = CSLInsertStrings( papszParam, 0, papszFirst2 );
-            papszParam = CSLRemoveStrings( papszParam, 2, 1, NULL );
-        }
-        CSLDestroy( papszFirst2 );
-    }
-
-    return papszParam;
-
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                       Open()
-//  ---------------------------------------------------------------------------
-
-GeoRasterWrapper* GeoRasterWrapper::Open( const char* pszStringId, bool bUpdate )
-{
-    char** papszParam = ParseIdentificator( pszStringId );
-
-    //  ---------------------------------------------------------------
-    //  Validate identificator
-    //  ---------------------------------------------------------------
-
-    int nArgc = CSLCount( papszParam );
-
-    for( ; nArgc < 3; nArgc++ )
-    {
-        papszParam = CSLAddString( papszParam, "" );
-    }
-
-    //  ---------------------------------------------------------------
-    //  Create a GeoRasterWrapper object
-    //  ---------------------------------------------------------------
-
-    GeoRasterWrapper* poGRW = new GeoRasterWrapper();
-
-    if( ! poGRW )
-    {
-        return NULL;
-    }
-
-    poGRW->bUpdate = bUpdate;
-    
-    //  ---------------------------------------------------------------
-    //  Get a connection with Oracle server
-    //  ---------------------------------------------------------------
-
-    poGRW->poConnection = new OWConnection( papszParam[0],
-                                            papszParam[1],
-                                            papszParam[2] );
-
-    if( ! poGRW->poConnection->Succeeded() )
-    {
-        CSLDestroy( papszParam );
-        delete poGRW;
-        return NULL;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Extract schema name
-    //  -------------------------------------------------------------------
-
-    if( nArgc > 3 )
-    {
-        char** papszSchema = CSLTokenizeString2( papszParam[3], ".",
-                                CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
-
-        if( CSLCount( papszSchema ) == 2 )
-        {
-            poGRW->sOwner  = papszSchema[0];
-            poGRW->sSchema = CPLSPrintf( "%s.", poGRW->sOwner.c_str() );
-
-            papszParam = CSLRemoveStrings( papszParam, 3, 1, NULL );
-
-            if( ! EQUAL( papszSchema[1], "" ) )
-            {
-                papszParam = CSLInsertString( papszParam, 3, papszSchema[1] );
-            }
-
-            nArgc = CSLCount( papszParam );
-        }
-        else
-        {
-            poGRW->sSchema = "";
-            poGRW->sOwner  = poGRW->poConnection->GetUser();
-        }
-        
-        CSLDestroy( papszSchema );
-    }
-    else
-    {
-        poGRW->sSchema = "";
-        poGRW->sOwner  = poGRW->poConnection->GetUser();
-    }
-
-    //  -------------------------------------------------------------------
-    //  Assign parameters from Identification string
-    //  -------------------------------------------------------------------
-
-    switch( nArgc )
-    {
-    case 6 :
-        poGRW->sTable   = papszParam[3];
-        poGRW->sColumn  = papszParam[4];
-        poGRW->sWhere   = papszParam[5];
-        break;
-    case 5 :
-        if( OWIsNumeric( papszParam[4] ) )
-        {
-            poGRW->sDataTable   = papszParam[3];
-            poGRW->nRasterId    = atoi( papszParam[4]);
-            break;
-        }
-        else
-        {
-            poGRW->sTable   = papszParam[3];
-            poGRW->sColumn  = papszParam[4];
-            return poGRW;
-        }
-    case 4 :
-        poGRW->sTable   = papszParam[3];
-        return poGRW;
-    default :
-        return poGRW;
-    }
-
-    CSLDestroy( papszParam );
-
-    //  -------------------------------------------------------------------
-    //  Query all the basic information at once to reduce round trips
-    //  -------------------------------------------------------------------
-
-    char szOwner[OWCODE];
-    char szTable[OWCODE];
-    char szColumn[OWTEXT];
-    char szDataTable[OWCODE];
-    char szWhere[OWTEXT];
-    int nRasterId = -1;
-    int nSizeX = 0;
-    int nSizeY = 0;
-    int nSRID  = 0;
-    OCILobLocator* phLocator = NULL;
-    double dfULx = 0.0;
-    double dfURx = 0.0;
-    double dfLRx = 0.0;
-    double dfULy = 0.0;
-    double dfLLy = 0.0;
-    double dfLRy = 0.0;
-    char szWKText[2 * OWTEXT];
-    char szAuthority[OWTEXT];
-    char szMLC[OWTEXT];
-
-    if( ! poGRW->sOwner.empty() )
-      strcpy( szOwner, poGRW->sOwner.c_str() );
-    else
-      szOwner[0] = '\0';
-
-    if( ! poGRW->sTable.empty() )
-      strcpy( szTable, poGRW->sTable.c_str() );
-    else
-      szTable[0] = '\0';
-
-    if( ! poGRW->sColumn.empty() )
-      strcpy( szColumn, poGRW->sColumn.c_str() );
-    else
-      szColumn[0] = '\0';
-
-    if( ! poGRW->sDataTable.empty() )
-      strcpy( szDataTable, poGRW->sDataTable.c_str() );
-    else
-      szDataTable[0] = '\0';
-
-    nRasterId = poGRW->nRasterId;
-
-    if( ! poGRW->sWhere.empty() )
-      strcpy( szWhere, poGRW->sWhere.c_str() );
-    else
-      szWhere[0] = '\0';
-
-    OWStatement* poStmt = poGRW->poConnection->CreateStatement(
-      "DECLARE\n"
-      "  SCM VARCHAR2(64) := 'xmlns=\"http://xmlns.oracle.com/spatial/georaster\"';\n"
-      "  GUL SDO_GEOMETRY := null;\n"
-      "  GUR SDO_GEOMETRY := null;\n"
-      "  GLL SDO_GEOMETRY := null;\n"
-      "  GLR SDO_GEOMETRY := null;\n"
-      "BEGIN\n"
-      "\n"
-      "    IF :datatable IS NOT NULL AND :rasterid  > 0 THEN\n"
-      "\n"
-      "      EXECUTE IMMEDIATE\n"
-      "        'SELECT OWNER, TABLE_NAME, COLUMN_NAME\n"
-      "         FROM   ALL_SDO_GEOR_SYSDATA\n"
-      "         WHERE  RDT_TABLE_NAME = UPPER(:1)\n"
-      "           AND  RASTER_ID = :2'\n"
-      "        INTO  :owner, :table, :column\n"
-      "        USING :datatable, :rasterid;\n"
-      "\n"
-      "      EXECUTE IMMEDIATE\n"
-      "        'SELECT T.'||:column||'.METADATA.getClobVal()\n"
-      "         FROM   '||:owner||'.'||:table||' T\n"
-      "         WHERE  T.'||:column||'.RASTERDATATABLE = UPPER(:1)\n"
-      "           AND  T.'||:column||'.RASTERID = :2'\n"
-      "        INTO  :metadata\n"
-      "        USING :datatable, :rasterid;\n"
-      "      :counter := 1;\n"
-      "\n"
-      "    ELSE\n"
-      "\n"
-      "      EXECUTE IMMEDIATE\n"
-      "        'SELECT T.'||:column||'.RASTERDATATABLE,\n"
-      "                T.'||:column||'.RASTERID,\n"
-      "                T.'||:column||'.METADATA.getClobVal()\n"
-      "         FROM  '||:owner||'.'||:table||' T\n"
-      "         WHERE '||:where\n"
-      "        INTO  :datatable, :rasterid, :metadata;\n"
-      "      :counter := 1;\n"
-      "\n"
-      "    END IF;\n"
-      "\n"
-      "  SELECT\n"
-      "    extractValue(XMLType(:metadata),"
-      "'/georasterMetadata/rasterInfo/dimensionSize[@type=\"ROW\"]/size', "
-      "SCM),\n"
-      "    extractValue(XMLType(:metadata),"
-      "'/georasterMetadata/rasterInfo/dimensionSize[@type=\"COLUMN\"]/size', "
-      "SCM),\n"
-      "    extractValue(XMLType(:metadata),"
-      "'/georasterMetadata/spatialReferenceInfo/SRID', "
-      "SCM),\n"
-      "    extractValue(XMLType(:metadata),"
-      "'/georasterMetadata/spatialReferenceInfo/modelCoordinateLocation', "
-      "SCM)\n"
-      "    INTO :sizey, :sizex, :srid, :mcl FROM DUAL;\n"
-      "\n"
-      "  EXECUTE IMMEDIATE\n"
-      "    'SELECT\n"
-      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
-      "SDO_NUMBER_ARRAY(0, 0)),\n"
-      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
-      "SDO_NUMBER_ARRAY(0, '||:sizex||')),\n"
-      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
-      "SDO_NUMBER_ARRAY('||:sizey||', 0)),\n"
-      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
-      "SDO_NUMBER_ARRAY('||:sizey||', '||:sizex||'))\n"
-      "     FROM  '||:owner||'.'||:table||' T\n"
-      "     WHERE T.'||:column||'.RASTERDATATABLE = UPPER(:1)\n"
-      "       AND T.'||:column||'.RASTERID = :2'\n"
-      "    INTO  GUL, GLL, GUR, GLR\n"
-      "    USING :datatable, :rasterid;\n"
-      "\n"
-      "  :ULx := GUL.sdo_point.x;\n"
-      "  :URx := GUR.sdo_point.x;\n"
-      "  :LRx := GLR.sdo_point.x;\n"
-      "  :ULy := GUL.sdo_point.y;\n"
-      "  :LLy := GLL.sdo_point.y;\n"
-      "  :LRy := GLR.sdo_point.y;\n"
-      "\n"
-      "  BEGIN\n"
-      "    EXECUTE IMMEDIATE\n"
-      "      'SELECT WKTEXT, AUTH_NAME\n"
-      "       FROM   MDSYS.CS_SRS\n"
-      "       WHERE  SRID = :1 AND WKTEXT IS NOT NULL'\n"
-      "      INTO   :wktext, :authority\n"
-      "      USING  :srid;\n"
-      "  EXCEPTION\n"
-      "    WHEN no_data_found THEN\n"
-      "      :wktext := '';\n"
-      "      :authority := '';\n"
-      "  END;\n"
-      "\n"
-      "  EXCEPTION\n"
-      "    WHEN no_data_found THEN :counter := 0;\n"
-      "    WHEN too_many_rows THEN :counter := 2;\n"
-      "END;" );
-
-    int nCounter = 0;
-
-    poStmt->BindName( ":datatable", szDataTable );
-    poStmt->BindName( ":rasterid", &nRasterId );
-    poStmt->BindName( ":owner", szOwner );
-    poStmt->BindName( ":table", szTable );
-    poStmt->BindName( ":column", szColumn );
-    poStmt->BindName( ":where", szWhere );
-    poStmt->BindName( ":counter", &nCounter );
-    poStmt->BindName( ":metadata", &phLocator );
-    poStmt->BindName( ":sizex", &nSizeX );
-    poStmt->BindName( ":sizey", &nSizeY );
-    poStmt->BindName( ":srid", &nSRID );
-    poStmt->BindName( ":mcl", szMLC );
-    poStmt->BindName( ":ULx", &dfULx );
-    poStmt->BindName( ":URx", &dfURx );
-    poStmt->BindName( ":LRx", &dfLRx );
-    poStmt->BindName( ":ULy", &dfULy );
-    poStmt->BindName( ":LLy", &dfLLy );
-    poStmt->BindName( ":LRy", &dfLRy );
-    poStmt->BindName( ":wktext", szWKText, sizeof(szWKText) );
-    poStmt->BindName( ":authority", szAuthority );
-
-    CPLErrorReset();
-
-    if( ! poStmt->Execute() )
-    {
-        delete poStmt;
-        delete poGRW;
-        return NULL;
-    }
-
-    if( nCounter < 1 )
-    {
-        delete poStmt;
-        delete poGRW;
-        return NULL;
-    }
-
-    poGRW->sSchema  = CPLSPrintf( "%s.", szOwner );
-    poGRW->sOwner   = szOwner;
-    poGRW->sTable   = szTable;
-    poGRW->sColumn  = szColumn;
-
-    if( nCounter == 1 )
-    {
-        poGRW->bUniqueFound = true;
-    }
-    else
-    {
-        poGRW->bUniqueFound = false;
-        
-        delete poStmt;
-        return poGRW;
-    }
-
-    poGRW->sWKText      = szWKText;
-    poGRW->sAuthority   = szAuthority;
-    poGRW->sDataTable   = szDataTable;
-    poGRW->nRasterId    = nRasterId;
-    poGRW->sWhere       = CPLSPrintf(
-        "T.%s.RASTERDATATABLE = UPPER('%s') AND T.%s.RASTERID = %d",
-        poGRW->sColumn.c_str(),
-        poGRW->sDataTable.c_str(),
-        poGRW->sColumn.c_str(),
-        poGRW->nRasterId );
-    
-    //  -------------------------------------------------------------------
-    //  Read Metadata XML in text
-    //  -------------------------------------------------------------------
-
-    char* pszXML = poStmt->ReadCLob( phLocator );
-
-    if( pszXML )
-    {
-        //  -----------------------------------------------------------
-        //  Get basic information from xml metadata
-        //  -----------------------------------------------------------
-
-        poGRW->phMetadata = CPLParseXMLString( pszXML );
-        poGRW->GetRasterInfo();
-    }
-    else
-    {
-        poGRW->sDataTable = "";
-        poGRW->nRasterId  = 0;
-    }
-
-    // --------------------------------------------------------------------
-    // Load Coefficients matrix
-    // --------------------------------------------------------------------
-
-    if ( EQUAL( szMLC, "UPPERLEFT" ) )
-    {
-      poGRW->eModelCoordLocation = MCL_UPPERLEFT;
-    }
-    else
-    {
-      poGRW->eModelCoordLocation = MCL_DEFAULT;
-    }
-
-    double dfRotation = 0.0;
-
-    if( ! CPLIsEqual( dfULy, dfLLy ) )
-    {
-        dfRotation = ( dfURx - dfULx ) / ( dfLLy - dfULy );
-    }
-
-    poGRW->dfXCoefficient[0] = ( dfLRx - dfULx ) / nSizeX;
-    poGRW->dfXCoefficient[1] = dfRotation;
-    poGRW->dfXCoefficient[2] = dfULx;
-    poGRW->dfYCoefficient[0] = -dfRotation;
-    poGRW->dfYCoefficient[1] = ( dfLRy - dfULy ) / nSizeY;
-    poGRW->dfYCoefficient[2] = dfULy;
-
-    if ( poGRW->eModelCoordLocation == MCL_CENTER )
-    {
-      poGRW->dfXCoefficient[2] -= poGRW->dfXCoefficient[0] / 2;
-      poGRW->dfYCoefficient[2] -= poGRW->dfYCoefficient[1] / 2;
-
-      CPLDebug("GEOR","eModelCoordLocation = MCL_CENTER");
-    }
-    else
-    {
-      CPLDebug("GEOR","eModelCoordLocation = MCL_UPPERLEFT");
-    }
-
-    //  -------------------------------------------------------------------
-    //  Apply ULTCoordinate
-    //  -------------------------------------------------------------------
-
-    poGRW->dfXCoefficient[2] += 
-                ( poGRW->anULTCoordinate[0] * poGRW->dfXCoefficient[0] );
-
-    poGRW->dfYCoefficient[2] += 
-                ( poGRW->anULTCoordinate[1] * poGRW->dfYCoefficient[1] );
-
-    //  -------------------------------------------------------------------
-    //  Clean up
-    //  -------------------------------------------------------------------
-
-    OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
-    CPLFree( pszXML );
-    delete poStmt;
-    
-    //  -------------------------------------------------------------------
-    //  Return a GeoRasterWrapper object
-    //  -------------------------------------------------------------------
-
-    return poGRW;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     Create()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::Create( char* pszDescription,
-                               char* pszInsert,
-                               bool bUpdate )
-{
-    CPLString sValues;
-    CPLString sFormat;
-
-    if( sTable.empty() ||
-        sColumn.empty() )
-    {
-        return false;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Parse RDT/RID from the current szValues
-    //  -------------------------------------------------------------------
-
-    char szRDT[OWNAME];
-    char szRID[OWCODE];
-
-    if( ! sDataTable.empty() )
-    {
-        strcpy( szRDT, CPLSPrintf( "'%s'", sDataTable.c_str() ) );
-    }
-    else
-    {
-        strcpy( szRDT, OWParseSDO_GEOR_INIT( sValues.c_str(), 1 ) );
-    }
-
-    if ( nRasterId > 0 )
-    {
-        strcpy( szRID, CPLSPrintf( "%d", nRasterId ) );
-    }
-    else
-    {
-        strcpy( szRID, OWParseSDO_GEOR_INIT( sValues.c_str(), 2 ) );
-
-        if ( EQUAL( szRID, "" ) )
-        {
-            strcpy( szRID, "NULL" );
-        }
-    }
-
-    //  -------------------------------------------------------------------
-    //  Description parameters
-    //  -------------------------------------------------------------------
-
-    char szDescription[OWTEXT];
-
-    if( bUpdate == false )
-    {
-
-        if ( pszDescription  )
-        {
-            strcpy( szDescription, pszDescription );
-        }
-        else
-        {
-            strcpy( szDescription, CPLSPrintf(
-                "(%s MDSYS.SDO_GEORASTER)", sColumn.c_str() ) );
-        }
-
-        //  ---------------------------------------------------------------
-        //  Insert parameters
-        //  ---------------------------------------------------------------
-
-        if( pszInsert )
-        {
-            sValues = pszInsert;
-
-            if( pszInsert[0] == '(' && sValues.ifind( "VALUES" ) == std::string::npos )
-            {
-                sValues = CPLSPrintf( "VALUES %s", pszInsert );
-            }
-        }
-        else
-        {
-            sValues = CPLSPrintf( "VALUES (SDO_GEOR.INIT(%s,%s))", szRDT, szRID );
-        }
-    }
-
-    //  -----------------------------------------------------------
-    //  Storage parameters
-    //  -----------------------------------------------------------
-
-    nColumnBlockSize = nColumnBlockSize == 0 ? DEFAULT_BLOCK_COLUMNS : nColumnBlockSize;
-    nRowBlockSize    = nRowBlockSize    == 0 ? DEFAULT_BLOCK_ROWS    : nRowBlockSize;
-    nBandBlockSize   = nBandBlockSize   == 0 ? 1 : nBandBlockSize;
-
-    //  -----------------------------------------------------------
-    //  Blocking storage paramters
-    //  -----------------------------------------------------------
-
-    CPLString sBlocking;
-
-    if( bBlocking == true )
-    {
-        if( bAutoBlocking == true )
-        {
-            int nBlockXSize = nColumnBlockSize;
-            int nBlockYSize = nRowBlockSize;
-            int nBlockBSize = nBandBlockSize;
-
-            OWStatement* poStmt;
-
-            poStmt = poConnection->CreateStatement(
-                "DECLARE\n"
-                "  dimensionSize    sdo_number_array;\n"
-                "  blockSize        sdo_number_array;\n"
-                "BEGIN\n"
-                "  dimensionSize := sdo_number_array(:1, :2, :3);\n"
-                "  blockSize     := sdo_number_array(:4, :5, :6);\n"
-                "  sdo_geor_utl.calcOptimizedBlockSize(dimensionSize,blockSize);\n"
-                "  :4 := blockSize(1);\n"
-                "  :5 := blockSize(2);\n"
-                "  :6 := blockSize(3);\n"
-                "END;" );
-
-            poStmt->Bind( &nRasterColumns );
-            poStmt->Bind( &nRasterRows );
-            poStmt->Bind( &nRasterBands );
-            poStmt->Bind( &nBlockXSize );
-            poStmt->Bind( &nBlockYSize );
-            poStmt->Bind( &nBlockBSize );
-
-            if( poStmt->Execute() )
-            {
-                nColumnBlockSize = nBlockXSize;
-                nRowBlockSize = nBlockYSize;
-                nBandBlockSize = nBlockBSize;
-            }
-
-            delete poStmt;
-        }
-
-        if( nRasterBands == 1 )
-        {
-            sBlocking = CPLSPrintf( 
-                "blockSize=(%d, %d)", 
-                nRowBlockSize, 
-                nColumnBlockSize );
-        }
-        else
-        {
-            sBlocking = CPLSPrintf( 
-                "blockSize=(%d, %d, %d)", 
-                nRowBlockSize, 
-                nColumnBlockSize, 
-                nBandBlockSize );
-        }
-    }
-    else
-    {
-        sBlocking = "blocking=FALSE";
-
-        nColumnBlockSize = nRasterColumns;
-        nRowBlockSize = nRasterRows;
-        nBandBlockSize = nRasterBands;
-    }
-
-    //  -----------------------------------------------------------
-    //  Complete format paramters
-    //  -----------------------------------------------------------
-
-    if( poConnection->GetVersion() > 10 )
-    {
-        if( nRasterBands == 1 )
-        {
-            sFormat = CPLSPrintf( 
-                "20001, '"
-                "dimSize=(%d,%d) ", 
-                nRasterRows, nRasterColumns );
-        }
-        else
-        {
-            sFormat = CPLSPrintf( 
-                "21001, '"
-                "dimSize=(%d,%d,%d) ", 
-                nRasterRows, nRasterColumns, nRasterBands );
-        }
-
-        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-        {
-            sFormat.append( CPLSPrintf( 
-                    "%s "
-                    "cellDepth=%s "
-                    "interleaving=%s "
-                    "compression=%s "
-                    "quality=%d'",
-                    sBlocking.c_str(),
-                    sCellDepth.c_str(),
-                    sInterleaving.c_str(),
-                    sCompressionType.c_str(),
-                    nCompressQuality) );
-        }
-        else
-        {
-            sFormat.append( CPLSPrintf( 
-                    "%s "
-                    "cellDepth=%s "
-                    "interleaving=%s "
-                    "compression=%s'",
-                    sBlocking.c_str(),
-                    sCellDepth.c_str(),
-                    sInterleaving.c_str(),
-                    sCompressionType.c_str() ) );
-        }
-    }
-    else
-    {
-        //  -------------------------------------------------------
-        //  For versions 10g or older
-        //  -------------------------------------------------------
-
-        sFormat = CPLSPrintf(
-            "%s "
-            "cellDepth=%s "
-            "interleaving=%s "
-            "pyramid=FALSE "
-            "compression=NONE",
-            sBlocking.c_str(),
-            sCellDepth.c_str(),
-            sInterleaving.c_str() );
-    }
-
-    nTotalColumnBlocks = (int)
-        ( ( nRasterColumns + nColumnBlockSize - 1 ) / nColumnBlockSize );
-
-    nTotalRowBlocks = (int)
-        ( ( nRasterRows + nRowBlockSize - 1 ) / nRowBlockSize );
-
-    nTotalBandBlocks = (int)
-        ( ( nRasterBands + nBandBlockSize - 1) / nBandBlockSize );
-
-    //  -------------------------------------------------------------------
-    //  Create Georaster Table if needed
-    //  -------------------------------------------------------------------
-
-    OWStatement* poStmt;
-
-    if( ! bUpdate )
-    {
-        poStmt = poConnection->CreateStatement( CPLSPrintf(
-            "DECLARE\n"
-            "  TAB VARCHAR2(68)  := UPPER('%s');\n"
-            "  COL VARCHAR2(68)  := UPPER('%s');\n"
-            "  OWN VARCHAR2(68)  := UPPER('%s');\n"
-            "  CNT NUMBER        := 0;\n"
-            "BEGIN\n"
-            "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_TABLES\n"
-            "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
-            "      INTO CNT USING TAB, OWN;\n"
-            "\n"
-            "  IF CNT = 0 THEN\n"
-            "    EXECUTE IMMEDIATE 'CREATE TABLE %s%s %s';\n"
-            "    SDO_GEOR_UTL.createDMLTrigger( TAB,  COL );\n"
-            "  END IF;\n"
-            "END;",
-                sTable.c_str(),
-                sColumn.c_str(),
-                sOwner.c_str(),
-                sSchema.c_str(),
-                sTable.c_str(),
-                szDescription ) );
-
-        if( ! poStmt->Execute() )
-        {
-            delete ( poStmt );
-            return false;
-        }
-
-        delete poStmt;
-    }
-
-    //  -----------------------------------------------------------
-    //  Prepare UPDATE or INSERT comand
-    //  -----------------------------------------------------------
-
-    CPLString sCommand;
-
-    if( bUpdate )
-    {
-        sCommand = CPLSPrintf(
-            "SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;",
-            sColumn.c_str(),
-            sSchema.c_str(),
-            sTable.c_str(),
-            sWhere.c_str() );
-    }
-    else
-    {
-        sCommand = CPLSPrintf(
-            "INSERT INTO %s%s %s RETURNING %s INTO GR1;",
-            sSchema.c_str(),
-            sTable.c_str(),
-            sValues.c_str(),
-            sColumn.c_str() );
-    }
-
-    //  -----------------------------------------------------------
-    //  Create RTD if needed and insert/update GeoRaster
-    //  -----------------------------------------------------------
-
-    char szBindRDT[OWNAME];
-    int  nBindRID = 0;
-    szBindRDT[0] = '\0';
-
-    CPLString sObjectTable;
-    CPLString sSecureFile;
-
-    // For version > 11 create RDT as relational table by default,
-    // if it is not specified by create-option OBJECTTABLE=TRUE
-
-    if( poConnection->GetVersion() <= 11 || bCreateObjectTable )
-    {
-        sObjectTable = "OF MDSYS.SDO_RASTER\n      (";
-    }
-    else
-    {
-        sObjectTable = CPLSPrintf("(\n"
-                       "      RASTERID           NUMBER,\n"
-                       "      PYRAMIDLEVEL       NUMBER,\n"
-                       "      BANDBLOCKNUMBER    NUMBER,\n"
-                       "      ROWBLOCKNUMBER     NUMBER,\n"
-                       "      COLUMNBLOCKNUMBER  NUMBER,\n"
-                       "      BLOCKMBR           SDO_GEOMETRY,\n"
-                       "      RASTERBLOCK        BLOB,\n"
-                       "      CONSTRAINT '||:rdt||'_RDT_PK ");
-    }
-
-    // For version >= 11 create RDT rasterBlock as securefile
-
-    if( poConnection->GetVersion() >= 11 )
-    {
-        sSecureFile = "SECUREFILE(CACHE)";
-    }
-    else
-    {
-        sSecureFile = "(NOCACHE NOLOGGING)";
-    }
-
-    if( poConnection->GetVersion() > 10 )
-    {
-        poStmt = poConnection->CreateStatement( CPLSPrintf(
-            "DECLARE\n"
-            "  TAB  VARCHAR2(68)    := UPPER('%s');\n"
-            "  COL  VARCHAR2(68)    := UPPER('%s');\n"
-            "  OWN  VARCHAR2(68)    := UPPER('%s');\n"
-            "  CNT  NUMBER          := 0;\n"
-            "  GR1  SDO_GEORASTER   := NULL;\n"
-            "BEGIN\n"
-            "\n"
-            "  %s\n"
-            "\n"
-            "  GR1.spatialExtent := NULL;\n"
-            "\n"
-            "  SELECT GR1.RASTERDATATABLE INTO :rdt FROM DUAL;\n"
-            "  SELECT GR1.RASTERID        INTO :rid FROM DUAL;\n"
-            "\n"
-            "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_OBJECT_TABLES\n"
-            "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
-            "      INTO CNT USING :rdt, OWN;\n"
-            "\n"
-            "  IF CNT = 0 THEN\n"
-            "    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_TABLES\n"
-            "      WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
-            "        INTO CNT USING :rdt, OWN;\n"
-            "  END IF;\n"
-            "\n"
-            "  IF CNT = 0 THEN\n"
-            "    EXECUTE IMMEDIATE 'CREATE TABLE %s'||:rdt||' %s"
-            "PRIMARY KEY (RASTERID, PYRAMIDLEVEL,\n"
-            "      BANDBLOCKNUMBER, ROWBLOCKNUMBER, COLUMNBLOCKNUMBER))\n"
-            "      LOB(RASTERBLOCK) STORE AS %s';\n"
-            "  END IF;\n"
-            "\n"
-            "  SDO_GEOR.createTemplate(GR1, %s, null, 'TRUE');\n"
-            "\n"
-            "  UPDATE %s%s T SET %s = GR1 WHERE\n"
-            "    T.%s.RasterDataTable = :rdt AND\n"
-            "    T.%s.RasterId = :rid;\n"
-            "\n"
-            "  EXECUTE IMMEDIATE\n"
-            "    'SELECT T.%s.METADATA.getClobVal()\n"
-            "     FROM   %s%s T\n"
-            "     WHERE  T.%s.RASTERDATATABLE = UPPER(:1)\n"
-            "       AND  T.%s.RASTERID = :2'\n"
-            "      INTO  :metadata\n"
-            "     USING  :rdt, :rid;\n"
-            "\n"
-            "  COMMIT;\n"
-            "\n"
-            "END;\n",
-                sTable.c_str(),
-                sColumn.c_str(),
-                sOwner.c_str(),
-                sCommand.c_str(),
-                sSchema.c_str(),
-                sObjectTable.c_str(),
-                sSecureFile.c_str(),
-                sFormat.c_str(),
-                sSchema.c_str(),
-                sTable.c_str(),
-                sColumn.c_str(),
-                sColumn.c_str(),
-                sColumn.c_str(),
-                sColumn.c_str(),
-                sSchema.c_str(),
-                sTable.c_str(),
-                sColumn.c_str(),
-                sColumn.c_str() ) );
-
-        OCILobLocator* phLocator = NULL;
-
-        poStmt->BindName( ":metadata", &phLocator );
-        poStmt->BindName( ":rdt", szBindRDT );
-        poStmt->BindName( ":rid", &nBindRID );
-
-        CPLErrorReset();
-
-        if( ! poStmt->Execute() )
-        {
-            delete poStmt;
-            return false;
-        }
-
-        sDataTable = szBindRDT;
-        nRasterId  = nBindRID;
-
-        OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
-
-        
-        delete poStmt;
-
-        return true;
-    }
-
-    //  -----------------------------------------------------------
-    //  Procedure for Server version older than 11
-    //  -----------------------------------------------------------
-
-    char szCreateBlank[OWTEXT];
-
-    if( nRasterBands == 1 )
-    {
-        strcpy( szCreateBlank, CPLSPrintf( "SDO_GEOR.createBlank(20001, "
-            "SDO_NUMBER_ARRAY(0, 0), "
-            "SDO_NUMBER_ARRAY(%d, %d), 0, :rdt, :rid)",
-            nRasterRows, nRasterColumns ) );
-    }
-    else
-    {
-        strcpy( szCreateBlank, CPLSPrintf( "SDO_GEOR.createBlank(21001, "
-            "SDO_NUMBER_ARRAY(0, 0, 0), "
-            "SDO_NUMBER_ARRAY(%d, %d, %d), 0, :rdt, :rid)",
-            nRasterRows, nRasterColumns, nRasterBands ) );
-    }
-
-    poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "DECLARE\n"
-        "  W    NUMBER          := :1;\n"
-        "  H    NUMBER          := :2;\n"
-        "  BB   NUMBER          := :3;\n"
-        "  RB   NUMBER          := :4;\n"
-        "  CB   NUMBER          := :5;\n"
-        "  OWN  VARCHAR2(68)    := UPPER('%s');\n"
-        "  X    NUMBER          := 0;\n"
-        "  Y    NUMBER          := 0;\n"
-        "  CNT  NUMBER          := 0;\n"
-        "  GR1  SDO_GEORASTER   := NULL;\n"
-        "  GR2  SDO_GEORASTER   := NULL;\n"
-        "  STM  VARCHAR2(1024)  := '';\n"
-        "BEGIN\n"
-        "\n"
-        "  %s\n"
-        "\n"
-        "  SELECT GR1.RASTERDATATABLE INTO :rdt FROM DUAL;\n"
-        "  SELECT GR1.RASTERID        INTO :rid FROM DUAL;\n"
-        "\n"
-        "  SELECT %s INTO GR2 FROM %s%s T WHERE"
-        " T.%s.RasterDataTable = :rdt AND"
-        " T.%s.RasterId = :rid FOR UPDATE;\n"
-        "\n"
-        "  GR1 := %s;\n"
-        "\n"
-        "  SDO_GEOR.changeFormatCopy(GR1, '%s', GR2);\n"
-        "\n"
-        "  UPDATE %s%s T SET %s = GR2 WHERE"
-        " T.%s.RasterDataTable = :rdt AND"
-        " T.%s.RasterId = :rid;\n"
-        "\n"
-        "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_OBJECT_TABLES\n"
-        "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
-        "      INTO CNT USING :rdt, OWN;\n"
-        "\n"
-        "  IF CNT = 0 THEN\n"
-        "    EXECUTE IMMEDIATE 'CREATE TABLE %s'||:rdt||' OF MDSYS.SDO_RASTER\n"
-        "      (PRIMARY KEY (RASTERID, PYRAMIDLEVEL, BANDBLOCKNUMBER,\n"
-        "      ROWBLOCKNUMBER, COLUMNBLOCKNUMBER))\n"
-        "      LOB(RASTERBLOCK) STORE AS (NOCACHE NOLOGGING)';\n"
-        "  ELSE\n"
-        "    EXECUTE IMMEDIATE 'DELETE FROM %s'||:rdt||' WHERE RASTERID ='||:rid||' ';\n"
-        "  END IF;\n"
-        "\n"
-        "  STM := 'INSERT INTO %s'||:rdt||' VALUES (:1,0,:2-1,:3-1,:4-1,\n"
-        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
-        "    SDO_ORDINATE_ARRAY(:5,:6,:7-1,:8-1)), EMPTY_BLOB() )';\n\n"
-        "  FOR b IN 1..BB LOOP\n"
-        "    Y := 0;\n"
-        "    FOR r IN 1..RB LOOP\n"
-        "      X := 0;\n"
-        "      FOR c IN 1..CB LOOP\n"
-        "        EXECUTE IMMEDIATE STM USING :rid, b, r, c, Y, X, (Y+H), (X+W);\n"
-        "        X := X + W;\n"
-        "      END LOOP;\n"
-        "      Y := Y + H;\n"
-        "    END LOOP;\n"
-        "  END LOOP;\n"
-        "\n"
-        "  SDO_GEOR.georeference(GR1, %d, %d,"
-        " SDO_NUMBER_ARRAY(1.0, 0.0, 0.0),"
-        " SDO_NUMBER_ARRAY(0.0, 1.0, 0.0));\n"
-        "\n"
-        "  UPDATE %s%s T SET %s = GR1 WHERE"
-        " T.%s.RasterDataTable = :rdt AND"
-        " T.%s.RasterId = :rid;\n"
-        "\n"
-        "  COMMIT;\n"
-        "\n"
-        "END;",
-            sOwner.c_str(),
-            sCommand.c_str(),
-            sColumn.c_str(), sSchema.c_str(), sTable.c_str(),
-            sColumn.c_str(), sColumn.c_str(),
-            szCreateBlank,
-            sFormat.c_str(), 
-            sSchema.c_str(), sTable.c_str(),
-            sColumn.c_str(), sColumn.c_str(), sColumn.c_str(),
-            sSchema.c_str(), sSchema.c_str(), sSchema.c_str(),
-            DEFAULT_CRS, MCL_DEFAULT,
-            sSchema.c_str(), sTable.c_str(),
-            sColumn.c_str(), sColumn.c_str(), sColumn.c_str() ) );
-
-    poStmt->Bind( &nColumnBlockSize );
-    poStmt->Bind( &nRowBlockSize );
-    poStmt->Bind( &nTotalBandBlocks );
-    poStmt->Bind( &nTotalRowBlocks );
-    poStmt->Bind( &nTotalColumnBlocks );
-    
-    poStmt->BindName( ":rdt", szBindRDT );
-    poStmt->BindName( ":rid", &nBindRID );
-
-    if( ! poStmt->Execute() )
-    {
-        delete poStmt;
-        return false;
-    }
-
-    sDataTable = szBindRDT;
-    nRasterId  = nBindRID;
-
-    delete poStmt;
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                         PrepareToOverwrite()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::PrepareToOverwrite( void )
-{
-    nTotalColumnBlocks  = 0;
-    nTotalRowBlocks     = 0;
-    nTotalBandBlocks    = 0;
-    if( sscanf( sCellDepth.c_str(), "%dBIT", &nCellSizeBits ) )
-    {
-        nGDALCellBytes   = GDALGetDataTypeSize(
-                          OWGetDataType( sCellDepth.c_str() ) ) / 8;
-    }
-    else
-    {
-        nGDALCellBytes   = 1;
-    }
-    dfXCoefficient[0]   = 1.0;
-    dfXCoefficient[1]   = 0.0;
-    dfXCoefficient[2]   = 0.0;
-    dfYCoefficient[0]   = 0.0;
-    dfYCoefficient[1]   = 1.0;
-    dfYCoefficient[2]   = 0.0;
-    sCompressionType    = "NONE";
-    nCompressQuality    = 75;
-    bGenPyramid         = false;
-    nPyramidLevels      = 0;
-    sPyramidResampling  = "NN";
-    bIsReferenced       = false;
-    nCacheBlockId       = -1;
-    nCurrentLevel       = -1;
-    pahLevels           = NULL;
-    nLevelOffset        = 0L;
-    sInterleaving       = "BSQ";
-    bUpdate             = false;
-    bInitializeIO       = false;
-    bFlushMetadata      = false;
-    nSRID               = 0;
-    nExtentSRID         = 0;
-    bGenSpatialIndex    = false;
-    bCreateObjectTable  = false;
-    nPyramidMaxLevel    = 0;
-    nBlockCount         = 0L;
-    sDInfo.global_state = 0;
-    sCInfo.global_state = 0;
-    bHasBitmapMask      = false;
-    bWriteOnly          = false;
-    bBlocking           = true;
-    bAutoBlocking       = false;
-    eModelCoordLocation = MCL_DEFAULT;
-    bFlushBlock         = false;
-    nFlushBlockSize     = 0L;
-    phRPC               = NULL;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     Delete()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::Delete( void )
-{
-    if( ! bUniqueFound )
-    {
-        return false;
-    }
-    
-    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
-      "UPDATE %s%s T SET %s = NULL WHERE %s\n",
-            sSchema.c_str(),
-            sTable.c_str(),
-            sColumn.c_str(),
-            sWhere.c_str() ) );
-
-    bool bReturn = poStmt->Execute();
-
-    delete poStmt;
-
-    return bReturn;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            SetGeoReference()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::SetGeoReference( int nSRIDIn )
-{
-    nSRID = nSRIDIn;
-
-    bIsReferenced = true;
-
-    bFlushMetadata = true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              GetRasterInfo()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::GetRasterInfo( void )
-{
-    //  -------------------------------------------------------------------
-    //  Get dimensions
-    //  -------------------------------------------------------------------
-
-    int nCount  = 0;
-
-    CPLXMLNode* phDimSize   = NULL;
-    const char* pszType     = NULL;
-
-    nCount      = atoi( CPLGetXMLValue( phMetadata,
-                  "rasterInfo.totalDimensions", "0" ) );
-    phDimSize   = CPLGetXMLNode( phMetadata, "rasterInfo.dimensionSize" );
-
-    int i = 0;
-
-    for( i = 0; i < nCount; i++ )
-    {
-        pszType = CPLGetXMLValue( phDimSize, "type", "0" );
-
-        if( EQUAL( pszType, "ROW" ) )
-        {
-            nRasterRows = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
-        }
-
-        if( EQUAL( pszType, "COLUMN" ) )
-        {
-            nRasterColumns = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
-        }
-
-        if( EQUAL( pszType, "BAND" ) )
-        {
-            nRasterBands = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
-        }
-
-        phDimSize = phDimSize->psNext;
-    }
-
-    if( nRasterBands == 0 )
-    {
-        nRasterBands = 1;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Load NoData Values 
-    //  -------------------------------------------------------------------
-
-    LoadNoDataValues();
-
-    //  -------------------------------------------------------------------
-    //  Get ULTCoordinate values
-    //  -------------------------------------------------------------------
-
-    anULTCoordinate[0] = atoi(CPLGetXMLValue( 
-            phMetadata, "rasterInfo.ULTCoordinate.column", "0"));
-
-    anULTCoordinate[1] = atoi(CPLGetXMLValue( 
-            phMetadata, "rasterInfo.ULTCoordinate.row", "0"));
-
-    anULTCoordinate[2] = atoi(CPLGetXMLValue( 
-            phMetadata, "rasterInfo.ULTCoordinate.band", "0"));
-
-    //  -------------------------------------------------------------------
-    //  Get Interleaving mode
-    //  -------------------------------------------------------------------
-
-    sInterleaving = CPLGetXMLValue( phMetadata,
-        "rasterInfo.interleaving", "BSQ" );
-
-    //  -------------------------------------------------------------------
-    //  Get blocking
-    //  -------------------------------------------------------------------
-
-    nRowBlockSize       = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.rowBlockSize",
-                            CPLSPrintf( "%d", nRasterRows ) ) );
-
-    nColumnBlockSize    = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.columnBlockSize",
-                            CPLSPrintf( "%d", nRasterColumns ) ) );
-
-    nBandBlockSize      = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.bandBlockSize",
-                            CPLSPrintf( "%d", nRasterBands ) ) );
-
-    nTotalColumnBlocks  = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.totalColumnBlocks","1") );
-
-    nTotalRowBlocks     = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.totalRowBlocks", "1" ) );
-
-    nTotalBandBlocks    = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.blocking.totalBandBlocks", "1" ) );
-
-    if( nBandBlockSize == -1 )
-    {
-       nBandBlockSize = nRasterBands;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Get data type
-    //  -------------------------------------------------------------------
-
-    sCellDepth = CPLGetXMLValue( phMetadata, "rasterInfo.cellDepth", "8BIT_U" );
-
-    if( sscanf( sCellDepth.c_str(), "%dBIT", &nCellSizeBits ) )
-    {
-        nGDALCellBytes   = GDALGetDataTypeSize(
-            OWGetDataType( sCellDepth.c_str() ) ) / 8;
-    }
-    else
-    {
-        nGDALCellBytes   = 1;
-    }
-
-    sCompressionType  = CPLGetXMLValue( phMetadata,
-        "rasterInfo.compression.type", "NONE" );
-
-    if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-    {
-        nCompressQuality = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.compression.quality", "75" ) );
-    }
-
-    if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-    {
-        sInterleaving = "BIP";
-    }
-
-    //  -------------------------------------------------------------------
-    //  Get default RGB Bands
-    //  -------------------------------------------------------------------
-
-    iDefaultRedBand     = atoi( CPLGetXMLValue( phMetadata,
-                            "objectInfo.defaultRed", "-1" ) );
-
-    iDefaultGreenBand   = atoi( CPLGetXMLValue( phMetadata,
-                            "objectInfo.defaultGreen", "-1" ) );
-
-    iDefaultBlueBand    = atoi( CPLGetXMLValue( phMetadata,
-                            "objectInfo.defaultBlue", "-1" ) );
-
-    //  -------------------------------------------------------------------
-    //  Get Pyramid details
-    //  -------------------------------------------------------------------
-
-    char szPyramidType[OWCODE];
-
-    strcpy( szPyramidType, CPLGetXMLValue( phMetadata,
-                            "rasterInfo.pyramid.type", "None" ) );
-
-    if( EQUAL( szPyramidType, "DECREASE" ) )
-    {
-        nPyramidMaxLevel = atoi( CPLGetXMLValue( phMetadata,
-                            "rasterInfo.pyramid.maxLevel", "0" ) );
-    }
-
-    //  -------------------------------------------------------------------
-    //  Check for RPCs
-    //  -------------------------------------------------------------------
-
-    const char* pszModelType = CPLGetXMLValue( phMetadata,
-                               "spatialReferenceInfo.modelType", "None" );
-
-    if( EQUAL( pszModelType, "FunctionalFitting" ) )
-    {
-        GetRPC();
-    }
-
-    //  -------------------------------------------------------------------
-    //  Prepare to get Extents
-    //  -------------------------------------------------------------------
-
-    bIsReferenced       = EQUAL( "TRUE", CPLGetXMLValue( phMetadata,
-                            "spatialReferenceInfo.isReferenced", "FALSE" ) );
-
-    nSRID               = atoi( CPLGetXMLValue( phMetadata,
-                            "spatialReferenceInfo.SRID", "0" ) );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              GetStatistics()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::GetStatistics( int nBand,
-                                      char* pszMin,
-                                      char* pszMax,
-                                      char* pszMean,
-                                      char* pszMedian,
-                                      char* pszMode,
-                                      char* pszStdDev,
-                                      char* pszSampling )
-{
-    int n = 1;
-
-    CPLXMLNode *phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
-    {
-        if( n == nBand && CPLGetXMLNode( phSubLayer, "statisticDataset" ) )
-        {
-            strncpy( pszSampling, CPLGetXMLValue( phSubLayer, 
-                "statisticDataset.samplingFactor",  "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszMin, CPLGetXMLValue( phSubLayer, 
-                "statisticDataset.MIN",  "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszMax, CPLGetXMLValue( phSubLayer,
-                "statisticDataset.MAX",  "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszMean, CPLGetXMLValue( phSubLayer,
-                "statisticDataset.MEAN", "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszMedian, CPLGetXMLValue( phSubLayer,
-                "statisticDataset.MEDIAN", "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszMode, CPLGetXMLValue( phSubLayer,
-                "statisticDataset.MODEVALUE", "0.0" ), MAX_DOUBLE_STR_REP );
-            strncpy( pszStdDev, CPLGetXMLValue( phSubLayer,
-                "statisticDataset.STD",  "0.0" ), MAX_DOUBLE_STR_REP );
-            return true;
-        }
-    }
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              SetStatistics()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::SetStatistics( int nBand,
-                                      const char* pszMin,
-                                      const char* pszMax,
-                                      const char* pszMean,
-                                      const char* pszMedian,
-                                      const char* pszMode,
-                                      const char* pszStdDev,
-                                      const char* pszSampling )
-{
-    InitializeLayersNode();
-
-    bFlushMetadata = true;
-
-    int n = 1;
-
-    CPLXMLNode* phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
-    {
-        if( n != nBand )
-        {
-            continue;
-        }
-
-        CPLXMLNode* psSDaset = CPLGetXMLNode( phSubLayer, "statisticDataset" );
-
-        if( psSDaset != NULL )
-        {
-            CPLRemoveXMLChild( phSubLayer, psSDaset );
-            CPLDestroyXMLNode( psSDaset );
-        }
-
-        psSDaset = CPLCreateXMLNode(phSubLayer,CXT_Element,"statisticDataset");
-
-        CPLCreateXMLElementAndValue(psSDaset,"samplingFactor", pszSampling );
-        CPLCreateXMLElementAndValue(psSDaset,"MIN", pszMin );
-        CPLCreateXMLElementAndValue(psSDaset,"MAX", pszMax );
-        CPLCreateXMLElementAndValue(psSDaset,"MEAN", pszMean );
-        CPLCreateXMLElementAndValue(psSDaset,"MEDIAN", pszMedian );
-        CPLCreateXMLElementAndValue(psSDaset,"MODEVALUE", pszMode );
-        CPLCreateXMLElementAndValue(psSDaset,"STD", pszStdDev );
-
-        return true;
-    }
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              HasColorTable()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::HasColorMap( int nBand )
-{
-    CPLXMLNode *psLayers;
-
-    int n = 1;
-
-    psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( ; psLayers; psLayers = psLayers->psNext, n++ )
-    {
-        if( n == nBand )
-        {
-            if( CPLGetXMLNode( psLayers, "colorMap.colors" ) )
-            {
-                return true;
-            }
-        }
-    }
-
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                        InitializeLayersNode()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::InitializeLayersNode()
-{
-    CPLXMLNode *pslInfo  = CPLGetXMLNode( phMetadata, "layerInfo" );
-
-    int n = 1;
-
-    for( n = 0 ; n < nRasterBands; n++ )
-    {
-        CPLXMLNode *psSLayer = CPLGetXMLNode( pslInfo,    "subLayer" );
-
-        if( psSLayer == NULL )
-        {
-            psSLayer = CPLCreateXMLNode( pslInfo, CXT_Element, "subLayer" );
-
-            CPLCreateXMLElementAndValue( psSLayer, "layerNumber",
-                CPLSPrintf( "%d", n + 1 ) );
-
-            CPLCreateXMLElementAndValue( psSLayer, "layerDimensionOrdinate",
-                CPLSPrintf( "%d", n ) );
-
-            CPLCreateXMLElementAndValue( psSLayer, "layerID", "" );
-        }
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              GetColorTable()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::GetColorMap( int nBand, GDALColorTable* poCT )
-{
-    GDALColorEntry oEntry;
-
-    CPLXMLNode* psLayers;
-
-    int n = 1;
-
-    psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( ; psLayers; psLayers = psLayers->psNext, n++ )
-    {
-        if( n != nBand )
-        {
-            continue;
-        }
-
-        CPLXMLNode* psColors = CPLGetXMLNode( psLayers, "colorMap.colors.cell" );
-
-        int iColor = 0;
-
-        for(  ; psColors; psColors = psColors->psNext )
-        {
-            iColor    = (short) atoi( CPLGetXMLValue( psColors, "value","0"));
-            oEntry.c1 = (short) atoi( CPLGetXMLValue( psColors, "red",  "0"));
-            oEntry.c2 = (short) atoi( CPLGetXMLValue( psColors, "green","0"));
-            oEntry.c3 = (short) atoi( CPLGetXMLValue( psColors, "blue", "0"));
-            oEntry.c4 = (short) atoi( CPLGetXMLValue( psColors, "alpha","0"));
-            poCT->SetColorEntry( iColor, &oEntry );
-        }
-        break;
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              SetColorTable()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::SetColorMap( int nBand, GDALColorTable* poCT )
-{
-    InitializeLayersNode();
-
-    bFlushMetadata = true;
-
-    GDALColorEntry oEntry;
-
-    int n = 1;
-
-    CPLXMLNode* phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
-    {
-        if( n != nBand )
-        {
-            continue;
-        }
-
-        CPLXMLNode* psCMap = CPLGetXMLNode( phSubLayer, "colorMap" );
-
-        if( psCMap != NULL )
-        {
-            CPLRemoveXMLChild( phSubLayer, psCMap );
-            CPLDestroyXMLNode( psCMap );
-        }
-
-        psCMap = CPLCreateXMLNode( phSubLayer, CXT_Element, "colorMap" );
-
-        CPLXMLNode* psColor = CPLCreateXMLNode( psCMap, CXT_Element, "colors" );
-
-        // ------------------------------------------------
-        // Clean existing colors entry (RGB color table)
-        // ------------------------------------------------
-
-        if( psColor != NULL )
-        {
-            CPLRemoveXMLChild( psCMap, psColor );
-            CPLDestroyXMLNode( psColor );
-        }
-
-        psColor = CPLCreateXMLNode( psCMap, CXT_Element, "colors" );
-
-        int iColor = 0;
-
-        int nCount = 0;
-
-        switch( nCellSizeBits )
-        {
-            case 1 :
-                nCount = 2;
-                break;
-            case 2 :
-                nCount = 4;
-                break;
-            case 4:
-                nCount = 16;
-                break;
-            default:
-                nCount = poCT->GetColorEntryCount();
-        }
-
-
-        for( iColor = 0; iColor < nCount; iColor++ )
-        {
-            poCT->GetColorEntryAsRGB( iColor, &oEntry );
-
-            CPLXMLNode* psCell = CPLCreateXMLNode( psColor, CXT_Element, "cell" );
-
-            CPLSetXMLValue( psCell, "#value", CPLSPrintf("%d", iColor) );
-            CPLSetXMLValue( psCell, "#blue",  CPLSPrintf("%d", oEntry.c3) );
-            CPLSetXMLValue( psCell, "#red",   CPLSPrintf("%d", oEntry.c1) );
-            CPLSetXMLValue( psCell, "#green", CPLSPrintf("%d", oEntry.c2) );
-            CPLSetXMLValue( psCell, "#alpha", CPLSPrintf("%d", oEntry.c4) );
-        }
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                               InitializeIO()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::InitializeIO( void )
-{
-    bInitializeIO = true;
-    
-    // --------------------------------------------------------------------
-    // Initialize Pyramid level details
-    // --------------------------------------------------------------------
-
-    pahLevels = (hLevelDetails*) CPLCalloc( sizeof(hLevelDetails),
-                                            nPyramidMaxLevel + 1 );
-
-    // --------------------------------------------------------------------
-    // Calculate number and size of the blocks in level zero
-    // --------------------------------------------------------------------
-
-    nBlockCount = (unsigned long) ( nTotalColumnBlocks * nTotalRowBlocks * nTotalBandBlocks );
-    nBlockBytes = (unsigned long) ( nColumnBlockSize * nRowBlockSize * nBandBlockSize *
-                                    nCellSizeBits / 8L );
-    nGDALBlockBytes = (unsigned long) ( nColumnBlockSize * nRowBlockSize * nGDALCellBytes );
-
-    pahLevels[0].nColumnBlockSize   = nColumnBlockSize;
-    pahLevels[0].nRowBlockSize      = nRowBlockSize;
-    pahLevels[0].nTotalColumnBlocks = nTotalColumnBlocks;
-    pahLevels[0].nTotalRowBlocks    = nTotalRowBlocks;
-    pahLevels[0].nBlockCount        = nBlockCount;
-    pahLevels[0].nBlockBytes        = nBlockBytes;
-    pahLevels[0].nGDALBlockBytes    = nGDALBlockBytes;
-    pahLevels[0].nOffset            = 0L;
-
-    // --------------------------------------------------------------------
-    // Calculate number and size of the blocks in Pyramid levels
-    // --------------------------------------------------------------------
-
-    int iLevel = 1;
-    
-    for( iLevel = 1; iLevel <= nPyramidMaxLevel; iLevel++ )
-    {
-        int nRBS = nRowBlockSize;
-        int nCBS = nColumnBlockSize;
-        int nTCB = nTotalColumnBlocks;
-        int nTRB = nTotalRowBlocks;
-
-        // --------------------------------------------------------------------
-        // Calculate the actual size of a lower resolution block
-        // --------------------------------------------------------------------
-
-        double dfScale = pow( (double) 2.0, (double) iLevel );
-
-        int nXSize  = (int) floor( (double) nRasterColumns / dfScale );
-        int nYSize  = (int) floor( (double) nRasterRows / dfScale );
-        int nXBlock = (int) floor( (double) nCBS / 2.0 );
-        int nYBlock = (int) floor( (double) nRBS / 2.0 );
-
-        if( nXSize <= nXBlock && nYSize <= nYBlock )
-        {
-            // ------------------------------------------------------------
-            // Calculate the size of the singe small blocks
-            // ------------------------------------------------------------
-
-            nCBS = nXSize;
-            nRBS = nYSize;
-            nTCB = 1;
-            nTRB = 1;
-        }
-        else
-        {
-            // ------------------------------------------------------------
-            // Recalculate blocks quantity
-            // ------------------------------------------------------------
-
-            nTCB = (int) ceil( (double) nXSize / nCBS );
-            nTRB = (int) ceil( (double) nYSize / nRBS );
-        }
-
-        // --------------------------------------------------------------------
-        // Save level datails
-        // --------------------------------------------------------------------
-
-        pahLevels[iLevel].nColumnBlockSize   = nCBS;
-        pahLevels[iLevel].nRowBlockSize      = nRBS;
-        pahLevels[iLevel].nTotalColumnBlocks = nTCB;
-        pahLevels[iLevel].nTotalRowBlocks    = nTRB;
-        pahLevels[iLevel].nBlockCount        = (unsigned long ) ( nTCB * nTRB * nTotalBandBlocks );
-        pahLevels[iLevel].nBlockBytes        = (unsigned long ) ( nCBS * nRBS * nBandBlockSize *
-                                                                  nCellSizeBits / 8L );
-        pahLevels[iLevel].nGDALBlockBytes    = (unsigned long ) ( nCBS * nRBS * nGDALCellBytes );
-        pahLevels[iLevel].nOffset            = 0L;
-    }
-    
-    // --------------------------------------------------------------------
-    // Calculate total row count and level's offsets
-    // --------------------------------------------------------------------
-
-    nBlockCount = 0L;
-    
-    for( iLevel = 0; iLevel <= nPyramidMaxLevel; iLevel++ )
-    {
-        pahLevels[iLevel].nOffset = nBlockCount;
-        nBlockCount += pahLevels[iLevel].nBlockCount;
-    }
-
-    // --------------------------------------------------------------------
-    // Allocate buffer for one raster block
-    // --------------------------------------------------------------------
-
-    long nMaxBufferSize = MAX( nBlockBytes, nGDALBlockBytes );
-
-    pabyBlockBuf = (GByte*) VSIMalloc( sizeof(GByte) * nMaxBufferSize );
-
-    if ( pabyBlockBuf == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory, 
-            "InitializeIO - Block Buffer error\n"
-            "Cannot allocate memory buffer of (%ld) bytes "
-            "Consider the use of *smaller* block size",
-            nMaxBufferSize );
-        return false;
-    }
-
-    // --------------------------------------------------------------------
-    // Allocate buffer for one compressed raster block
-    // --------------------------------------------------------------------
-
-    if( bUpdate && ! EQUAL( sCompressionType.c_str(), "NONE") )
-    {
-        pabyCompressBuf = (GByte*) VSIMalloc( sizeof(GByte) * nMaxBufferSize );
-
-        if ( pabyCompressBuf == NULL )
-        {
-            CPLError( CE_Failure, CPLE_OutOfMemory,
-                "InitializeIO - Compression Buffer error\n"
-                "Cannot allocate memory buffer of (%ld) bytes "
-                "Consider the use of *smaller* block size",
-                nMaxBufferSize );
-            return false;
-        }
-    }
-
-    // --------------------------------------------------------------------
-    // Allocate array of LOB Locators
-    // --------------------------------------------------------------------
-
-    pahLocator = (OCILobLocator**) VSIMalloc( sizeof(void*) * nBlockCount );
-
-    if ( pahLocator == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory,
-                "InitializeIO - LobLocator Array error\n"
-                "Cannot allocate memory buffer of (%ld) bytes "
-                "Consider the use of *bigger* block size",
-                (sizeof(void*) * nBlockCount) );
-        return false;
-    }
-
-    //  --------------------------------------------------------------------
-    //  Issue a statement to load the locators
-    //  --------------------------------------------------------------------
-
-    const char* pszUpdate = "";
-
-    if( bUpdate )
-    {
-        pszUpdate = CPLStrdup( "\nFOR UPDATE" );
-    }
-
-    poBlockStmt = poConnection->CreateStatement( CPLSPrintf(
-        "SELECT RASTERBLOCK\n"
-        "FROM   %s%s\n"
-        "WHERE  RASTERID = :1\n"
-        "ORDER BY\n"
-        "       PYRAMIDLEVEL ASC,\n"
-        "       BANDBLOCKNUMBER ASC,\n"
-        "       ROWBLOCKNUMBER ASC,\n"
-        "       COLUMNBLOCKNUMBER ASC%s",
-        sSchema.c_str(),
-        sDataTable.c_str(),
-        pszUpdate ) );
-
-    poBlockStmt->Bind( &nRasterId );
-    poBlockStmt->Define( pahLocator, nBlockCount );
-
-    if( ! poBlockStmt->Execute( nBlockCount ) )
-    {
-        return false;
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            InitializeLevel()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::InitializeLevel( int nLevel )
-{
-    nCurrentLevel       = nLevel;
-    nColumnBlockSize    = pahLevels[nLevel].nColumnBlockSize;
-    nRowBlockSize       = pahLevels[nLevel].nRowBlockSize;
-    nTotalColumnBlocks  = pahLevels[nLevel].nTotalColumnBlocks;
-    nTotalRowBlocks     = pahLevels[nLevel].nTotalRowBlocks;
-    nBlockBytes         = pahLevels[nLevel].nBlockBytes;
-    nGDALBlockBytes     = pahLevels[nLevel].nGDALBlockBytes;
-    nLevelOffset        = pahLevels[nLevel].nOffset;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                               GetDataBlock()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::GetDataBlock( int nBand,
-                                     int nLevel,
-                                     int nXOffset,
-                                     int nYOffset,
-                                     void* pData )
-{
-    if( ! bInitializeIO )
-    {
-        if( InitializeIO() == false )
-        {
-            return false;
-        }
-    }
-
-    if( nCurrentLevel != nLevel )
-    {
-        InitializeLevel( nLevel );
-    }
-    
-    long nBlock = GetBlockNumber( nBand, nXOffset, nYOffset );
-
-    CPLDebug( "Read  ", 
-              "Block = %4ld Size = %7ld Band = %d Level = %d X = %d Y = %d", 
-              nBlock, nBlockBytes, nBand, nLevel, nXOffset, nYOffset );
-
-    if( nCacheBlockId != nBlock )
-    {
-        if ( bFlushBlock )       
-        {
-            if( ! FlushBlock( nCacheBlockId ) )
-            {
-                return false;
-            }
-        }
-
-        nCacheBlockId = nBlock;
-
-        unsigned long nBytesRead = 0;
-
-        nBytesRead = poBlockStmt->ReadBlob( pahLocator[nBlock],
-                                            pabyBlockBuf,
-                                            nBlockBytes );
-
-        CPLDebug( "Load  ", "Block = %4ld Size = %7ld", nBlock, nBlockBytes );
-
-        if( nBytesRead == 0 )
-        {
-            memset( pData, 0, nGDALBlockBytes );
-            return true;
-        }
-
-        if( nBytesRead < nBlockBytes && 
-            EQUAL( sCompressionType.c_str(), "NONE") )
-        {
-            CPLError( CE_Warning, CPLE_AppDefined, 
-                "BLOB size (%ld) is smaller than expected (%ld) !", 
-                nBytesRead,  nBlockBytes );
-            memset( pData, 0, nGDALBlockBytes );
-            return true;
-        }
-
-        if( nBytesRead > nBlockBytes )
-        {
-            CPLError( CE_Warning, CPLE_AppDefined, 
-                "BLOB size (%ld) is bigger than expected (%ld) !",
-                nBytesRead,  nBlockBytes );
-            memset( pData, 0, nGDALBlockBytes );
-            return true;
-        }
-
-#ifndef CPL_MSB
-        if( nCellSizeBits > 8 )
-        {
-            int nWordSize  = nCellSizeBits / 8;
-            int nWordCount = nColumnBlockSize * nRowBlockSize * nBandBlockSize;
-            GDALSwapWords( pabyBlockBuf, nWordSize, nWordCount, nWordSize );
-        }
-#endif
-
-        //  ----------------------------------------------------------------
-        //  Uncompress
-        //  ----------------------------------------------------------------
-
-        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-        {
-            UncompressJpeg( nBytesRead );
-        }
-        else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
-        {
-            UncompressDeflate( nBytesRead );
-        }
-
-        //  ----------------------------------------------------------------
-        //  Unpack NBits
-        //  ----------------------------------------------------------------
-
-        if( nCellSizeBits < 8 || nLevel == DEFAULT_BMP_MASK )
-        {
-            UnpackNBits( pabyBlockBuf );
-        }
-    }
-
-    //  --------------------------------------------------------------------
-    //  Uninterleaving, extract band from block buffer
-    //  --------------------------------------------------------------------
-
-    int nStart = ( nBand - 1 ) % nBandBlockSize;
-
-    if( EQUAL( sInterleaving.c_str(), "BSQ" ) || nBandBlockSize == 1 )
-    {
-        nStart *= nGDALBlockBytes;
-
-        memcpy( pData, &pabyBlockBuf[nStart], nGDALBlockBytes );
-    }
-    else
-    {
-        int nIncr   = nBandBlockSize * nGDALCellBytes;
-        int nSize   = nGDALCellBytes;
-
-        if( EQUAL( sInterleaving.c_str(), "BIL" ) )
-        {
-            nStart  *= nColumnBlockSize;
-            nIncr   *= nColumnBlockSize;
-            nSize   *= nColumnBlockSize;
-        }
-
-        GByte* pabyData = (GByte*) pData;
-
-        unsigned long ii = 0;
-        unsigned long jj = nStart * nGDALCellBytes;
-
-        for( ii = 0; ii < nGDALBlockBytes; ii += nSize, jj += nIncr )
-        {
-            memcpy( &pabyData[ii], &pabyBlockBuf[jj], nSize );
-        }
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                               SetDataBlock()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::SetDataBlock( int nBand,
-                                     int nLevel,
-                                     int nXOffset,
-                                     int nYOffset,
-                                     void* pData )
-{
-#ifndef CPL_MSB
-    if( nCellSizeBits > 8 )
-    {
-        int nWordSize  = nCellSizeBits / 8;
-        int nWordCount = nColumnBlockSize * nRowBlockSize;
-        GDALSwapWords( pData, nWordSize, nWordCount, nWordSize );
-    }
-#endif
-
-    if( ! bInitializeIO )
-    {
-        if( InitializeIO() == false )
-        {
-            return false;
-        }
-    }
-
-    if( nCurrentLevel != nLevel )
-    {
-        InitializeLevel( nLevel );
-    }
-
-    long nBlock = GetBlockNumber( nBand, nXOffset, nYOffset );
-
-    CPLDebug( "Write ", 
-              "Block = %4ld Size = %7ld Band = %d Level = %d X = %d Y = %d", 
-              nBlock, nBlockBytes, nBand, nLevel, nXOffset, nYOffset );
-
-    //  --------------------------------------------------------------------
-    //  Flush previous block
-    //  --------------------------------------------------------------------
-
-    if( nCacheBlockId != nBlock && bFlushBlock )
-    {
-        if( ! FlushBlock( nCacheBlockId ) )
-        {
-            return false;
-        }
-    }
-
-    //  --------------------------------------------------------------------
-    //  Re-load interleaved block
-    //  --------------------------------------------------------------------
-
-    if( nBandBlockSize > 1 && bWriteOnly == false && nCacheBlockId != nBlock )
-    {
-        nCacheBlockId = nBlock;
-
-        unsigned long nBytesRead = 0;
-
-        nBytesRead = poBlockStmt->ReadBlob( pahLocator[nBlock],
-                                            pabyBlockBuf,
-                                            nBlockBytes );
-
-        CPLDebug( "Reload", "Block = %4ld Size = %7ld", nBlock, nBlockBytes );
-
-        if( nBytesRead == 0 )
-        {
-            memset( pabyBlockBuf, 0, nBlockBytes );
-        }
-        else
-        {
-            //  ------------------------------------------------------------
-            //  Uncompress
-            //  ------------------------------------------------------------
-
-            if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-            {
-                UncompressJpeg( nBytesRead );
-            }
-            else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
-            {
-                UncompressDeflate( nBytesRead );
-            }
-            
-            //  ------------------------------------------------------------
-            //  Unpack NBits
-            //  ------------------------------------------------------------
-
-            if( nCellSizeBits < 8 || nLevel == DEFAULT_BMP_MASK )
-            {
-                UnpackNBits( pabyBlockBuf );
-            }
-        }
-    }
-
-    GByte *pabyInBuf = (GByte *) pData;
-
-    //  --------------------------------------------------------------------
-    //  Interleave
-    //  --------------------------------------------------------------------
-
-    int nStart = ( nBand - 1 ) % nBandBlockSize;
-
-    if( EQUAL( sInterleaving.c_str(), "BSQ" ) || nBandBlockSize == 1 )
-    {
-        nStart *= nGDALBlockBytes;
-
-        memcpy( &pabyBlockBuf[nStart], pabyInBuf, nGDALBlockBytes );
-    }
-    else
-    {
-        int nIncr   = nBandBlockSize * nGDALCellBytes;
-        int nSize   = nGDALCellBytes;
-
-        if( EQUAL( sInterleaving.c_str(), "BIL" ) )
-        {
-            nStart  *= nColumnBlockSize;
-            nIncr   *= nColumnBlockSize;
-            nSize   *= nColumnBlockSize;
-        }
-
-        unsigned long ii = 0;
-        unsigned long jj = nStart * nGDALCellBytes;
-
-        for( ii = 0; ii < nGDALBlockBytes; ii += nSize, jj += nIncr )
-        {
-            memcpy( &pabyBlockBuf[jj], &pabyInBuf[ii], nSize );
-        }
-    }
-
-    //  --------------------------------------------------------------------
-    //  Flag the flush block
-    //  --------------------------------------------------------------------
-
-    nCacheBlockId   = nBlock;
-    bFlushBlock     = true;
-    nFlushBlockSize = nBlockBytes;
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                 FlushBlock()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::FlushBlock( long nCacheBlock )
-{
-    GByte* pabyFlushBuffer = (GByte *) pabyBlockBuf;
-
-    //  --------------------------------------------------------------------
-    //  Pack bits ( inside pabyOutBuf )
-    //  --------------------------------------------------------------------
-
-    if( nCellSizeBits < 8 || nCurrentLevel == DEFAULT_BMP_MASK )
-    {
-        PackNBits( pabyFlushBuffer );
-    }
-
-    //  --------------------------------------------------------------------
-    //  Compress ( from pabyBlockBuf to pabyBlockBuf2 )
-    //  --------------------------------------------------------------------
-
-    if( ! EQUAL( sCompressionType.c_str(), "NONE" ) )
-    {
-        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-        {
-            nFlushBlockSize = CompressJpeg();
-        }
-        else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
-        {
-            nFlushBlockSize = CompressDeflate();
-        }
-
-        pabyFlushBuffer = pabyCompressBuf;
-    }
-
-    //  --------------------------------------------------------------------
-    //  Write BLOB
-    //  --------------------------------------------------------------------
-
-    CPLDebug( "Flush ", "Block = %4ld Size = %7ld", nCacheBlock, 
-              nFlushBlockSize );
-
-    if( ! poBlockStmt->WriteBlob( pahLocator[nCacheBlock],
-                                  pabyFlushBuffer,
-                                  nFlushBlockSize ) )
-    {
-        return false;
-    }
-
-    bFlushBlock     = false;
-    bFlushMetadata  = true;
-    nFlushBlockSize = nBlockBytes;
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                           LoadNoDataValues()
-//  ---------------------------------------------------------------------------
-
-CPLList* AddToNoDataList( CPLXMLNode* phNode, int nNumber, CPLList* poList )
-{
-    CPLXMLNode* psChild = phNode->psChild;
-
-    const char* pszMin = NULL;
-    const char* pszMax = NULL;
-
-    for( ; psChild ; psChild = psChild->psNext )
-    {
-        if( EQUAL( psChild->pszValue, "value" ) )
-        {
-            pszMin = CPLGetXMLValue( psChild, NULL, "NONE" );
-            pszMax = pszMin;
-        }
-        else if ( EQUAL( psChild->pszValue, "range" ) )
-        {
-            pszMin = CPLGetXMLValue( psChild, "min", "NONE" );
-            pszMax = CPLGetXMLValue( psChild, "max", "NONE" );
-        }
-        else
-        {
-            continue;
-        }
-
-        hNoDataItem* poItem = (hNoDataItem*) CPLMalloc( sizeof( hNoDataItem ) );
-
-        poItem->nBand = nNumber;
-        poItem->dfLower = CPLAtof( pszMin );
-        poItem->dfUpper = CPLAtof( pszMax );
-
-        poList = CPLListAppend( poList, poItem );
-    }
-
-    return poList;
-}
-
-void GeoRasterWrapper::LoadNoDataValues( void )
-{
-    CPLListDestroy( psNoDataList );
-
-    CPLXMLNode* phLayerInfo = CPLGetXMLNode( phMetadata, "layerInfo" );
-
-    if( phLayerInfo == NULL )
-    {
-        return;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Load NoDatas from list of values and list of value ranges
-    //  -------------------------------------------------------------------
-
-    CPLXMLNode* phObjNoData = CPLGetXMLNode( phLayerInfo, "objectLayer.NODATA" );
-
-    for( ; phObjNoData ; phObjNoData = phObjNoData->psNext )
-    {
-        psNoDataList = AddToNoDataList( phObjNoData, 0, psNoDataList );
-    }
-
-    CPLXMLNode* phSubLayer = CPLGetXMLNode( phLayerInfo, "subLayer" );
-
-    for( ; phSubLayer ; phSubLayer = phSubLayer->psNext )
-    {
-        int nNumber = atoi( CPLGetXMLValue( phSubLayer, "layerNumber", "-1") );
-
-        CPLXMLNode* phSubNoData = CPLGetXMLNode( phSubLayer, "NODATA" );
-
-        if( phSubNoData )
-        {
-            psNoDataList = AddToNoDataList( phSubNoData, nNumber, psNoDataList );
-        }
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     GetRPC()
-//  ---------------------------------------------------------------------------
-
-/* This is the order for storing 20 coeffients in GeoRaster Metadata */
-
-static const int anOrder[] = { 
-    1, 2, 8, 12, 3, 5, 15, 9, 13, 16, 4, 6, 18, 7, 11, 19, 10, 14, 17, 20
-};
-
-void GeoRasterWrapper::GetRPC()
-{
-    int i;
-
-    CPLXMLNode* phSRSInfo = CPLGetXMLNode( phMetadata, 
-                                           "spatialReferenceInfo" );
-
-    if( phSRSInfo == NULL )
-    {
-        return;
-    }
-
-    const char* pszModelType = CPLGetXMLValue( phMetadata,
-                               "spatialReferenceInfo.modelType", "None" );
-
-    if( EQUAL( pszModelType, "FunctionalFitting" ) == false )
-    {
-        return;
-    }
-
-    CPLXMLNode* phPolyModel = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
-
-    if ( phPolyModel == NULL )
-    {
-        return;
-    }
-
-    // pPolynomial refers to LINE_NUM
-
-    CPLXMLNode* phPolynomial = CPLGetXMLNode( phPolyModel, "pPolynomial" );
-
-    if ( phPolynomial == NULL )
-    {
-        return;
-    }
-
-    int nNumCoeff = atoi( CPLGetXMLValue( phPolynomial, "nCoefficients", "0" ) );
-
-    if ( nNumCoeff != 20 )
-    {
-        return;
-    }
-
-    const char* pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
-
-    if ( EQUAL( pszPolyCoeff, "None" ) )
-    {
-        return;
-    }
-
-    char** papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
-
-    if( CSLCount( papszCeoff ) != 20 )
-    {
-        return;
-    }
-
-    phRPC = (GDALRPCInfo*) VSIMalloc( sizeof(GDALRPCInfo) );
-    
-    phRPC->dfLINE_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "rowOff", "0" ) );
-    phRPC->dfSAMP_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "columnOff", "0" ) );
-    phRPC->dfLONG_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "xOff", "0" ) );
-    phRPC->dfLAT_OFF      = CPLAtof( CPLGetXMLValue( phPolyModel, "yOff", "0" ) );
-    phRPC->dfHEIGHT_OFF   = CPLAtof( CPLGetXMLValue( phPolyModel, "zOff", "0" ) );
-
-    phRPC->dfLINE_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "rowScale", "0" ) );
-    phRPC->dfSAMP_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "columnScale", "0" ) );
-    phRPC->dfLONG_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "xScale", "0" ) );
-    phRPC->dfLAT_SCALE    = CPLAtof( CPLGetXMLValue( phPolyModel, "yScale", "0" ) );
-    phRPC->dfHEIGHT_SCALE = CPLAtof( CPLGetXMLValue( phPolyModel, "zScale", "0" ) );
-
-    for( i = 0; i < 20; i++ )
-    {
-        phRPC->adfLINE_NUM_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
-    }
-
-    // qPolynomial refers to LINE_DEN
-
-    phPolynomial = CPLGetXMLNode( phPolyModel, "qPolynomial" );
-
-    if ( phPolynomial == NULL )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
-
-    if ( EQUAL( pszPolyCoeff, "None" ) )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
-
-    if( CSLCount( papszCeoff ) != 20 )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    for( i = 0; i < 20; i++ )
-    {
-        phRPC->adfLINE_DEN_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
-    }
-
-    // rPolynomial refers to SAMP_NUM
-
-    phPolynomial = CPLGetXMLNode( phPolyModel, "rPolynomial" );
-
-    if ( phPolynomial == NULL )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
-
-    if ( EQUAL( pszPolyCoeff, "None" ) )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
-
-    if( CSLCount( papszCeoff ) != 20 )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    for( i = 0; i < 20; i++ )
-    {
-        phRPC->adfSAMP_NUM_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
-    }
-
-    // sPolynomial refers to SAMP_DEN
-
-    phPolynomial = CPLGetXMLNode( phPolyModel, "sPolynomial" );
-
-    if ( phPolynomial == NULL )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
-
-    if ( EQUAL( pszPolyCoeff, "None" ) )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
-
-    if( CSLCount( papszCeoff ) != 20 )
-    {
-        CPLFree( phRPC );
-        phRPC = NULL;
-        return;
-    }
-
-    for( i = 0; i < 20; i++ )
-    {
-        phRPC->adfSAMP_DEN_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     SetRPC()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::SetRPC()
-{
-    //  -------------------------------------------------------------------
-    //  Remove "layerInfo" tree
-    //  -------------------------------------------------------------------
-
-    CPLXMLNode* phLayerInfo = CPLGetXMLNode( phMetadata, "layerInfo" );
-    CPLXMLNode* phClone = NULL;
-
-    if( phLayerInfo )
-    {
-        phClone = CPLCloneXMLTree( phLayerInfo );
-        CPLRemoveXMLChild( phMetadata, phLayerInfo );
-    }
-
-    //  -------------------------------------------------------------------
-    //  Start loading the RPC to "spatialReferenceInfo" tree
-    //  -------------------------------------------------------------------
-
-    int i = 0;
-    CPLString osField, osMultiField;
-    CPLXMLNode* phPolynomial = NULL;
-
-    CPLXMLNode* phSRSInfo = CPLGetXMLNode( phMetadata, 
-                                           "spatialReferenceInfo" );
-
-    if( ! phSRSInfo )
-    {
-        phSRSInfo = CPLCreateXMLNode( phMetadata, CXT_Element, 
-                                      "spatialReferenceInfo" );
-    }
-    else
-    {
-        CPLXMLNode* phNode = NULL;
-
-        phNode = CPLGetXMLNode( phSRSInfo, "isReferenced" );
-        if( phNode )
-        {
-            CPLRemoveXMLChild( phSRSInfo, phNode );
-        }
-
-        phNode = CPLGetXMLNode( phSRSInfo, "SRID" );
-        if( phNode )
-        {
-            CPLRemoveXMLChild( phSRSInfo, phNode );
-        }
-
-        phNode = CPLGetXMLNode( phSRSInfo, "modelCoordinateLocation" );
-        if( phNode )
-        {
-            CPLRemoveXMLChild( phSRSInfo, phNode );
-        }
-
-        phNode = CPLGetXMLNode( phSRSInfo, "modelType" );
-        if( phNode )
-        {
-            CPLRemoveXMLChild( phSRSInfo, phNode );
-        }
-
-        phNode = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
-        if( phNode )
-        {
-            CPLRemoveXMLChild( phSRSInfo, phNode );
-        }
-    }
-
-    CPLCreateXMLElementAndValue( phSRSInfo, "isReferenced", "true" );
-    CPLCreateXMLElementAndValue( phSRSInfo, "SRID", "4327" );
-    CPLCreateXMLElementAndValue( phSRSInfo, "modelCoordinateLocation", 
-                                            "CENTER" );
-    CPLCreateXMLElementAndValue( phSRSInfo, "modelType", "FunctionalFitting" );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#rowOff",      
-                                    CPLSPrintf( "%.15g", phRPC->dfLINE_OFF ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#columnOff",   
-                                    CPLSPrintf( "%.15g", phRPC->dfSAMP_OFF ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#xOff",        
-                                    CPLSPrintf( "%.15g", phRPC->dfLONG_OFF ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#yOff",        
-                                    CPLSPrintf( "%.15g", phRPC->dfLAT_OFF ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#zOff",        
-                                    CPLSPrintf( "%.15g", phRPC->dfHEIGHT_OFF ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#rowScale",    
-                                    CPLSPrintf( "%.15g", phRPC->dfLINE_SCALE ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#columnScale", 
-                                    CPLSPrintf( "%.15g", phRPC->dfSAMP_SCALE ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#xScale",      
-                                    CPLSPrintf( "%.15g", phRPC->dfLONG_SCALE ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#yScale",      
-                                    CPLSPrintf( "%.15g", phRPC->dfLAT_SCALE ) );
-    CPLSetXMLValue( phSRSInfo, "polynomialModel.#zScale",      
-                                    CPLSPrintf( "%.15g", phRPC->dfHEIGHT_SCALE ) );
-    CPLXMLNode*     phPloyModel = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
-
-    // pPolynomial refers to LINE_NUM
-
-    CPLSetXMLValue( phPloyModel, "pPolynomial.#pType",         "1" );
-    CPLSetXMLValue( phPloyModel, "pPolynomial.#nVars",         "3" );
-    CPLSetXMLValue( phPloyModel, "pPolynomial.#order",         "3" );
-    CPLSetXMLValue( phPloyModel, "pPolynomial.#nCoefficients", "20" );
-    for( i = 0; i < 20; i++ )
-    {
-        osField.Printf( "%.15g", phRPC->adfLINE_NUM_COEFF[anOrder[i] - 1] );
-        if( i > 0 )
-            osMultiField += " ";
-        else
-            osMultiField = "";
-        osMultiField += osField;
-    }
-    phPolynomial = CPLGetXMLNode( phPloyModel, "pPolynomial" );
-    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
-                                 osMultiField );
-
-    // qPolynomial refers to LINE_DEN
-
-    CPLSetXMLValue( phPloyModel, "qPolynomial.#pType",         "1" );
-    CPLSetXMLValue( phPloyModel, "qPolynomial.#nVars",         "3" );
-    CPLSetXMLValue( phPloyModel, "qPolynomial.#order",         "3" );
-    CPLSetXMLValue( phPloyModel, "qPolynomial.#nCoefficients", "20" );
-    for( i = 0; i < 20; i++ )
-    {
-        osField.Printf( "%.15g", phRPC->adfLINE_DEN_COEFF[anOrder[i] - 1] );
-        if( i > 0 )
-            osMultiField += " ";
-        else
-            osMultiField = "";
-        osMultiField += osField;
-    }
-    phPolynomial = CPLGetXMLNode( phPloyModel, "qPolynomial" );
-    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
-                                 osMultiField );
-
-    // rPolynomial refers to SAMP_NUM
-
-    CPLSetXMLValue( phPloyModel, "rPolynomial.#pType",         "1" );
-    CPLSetXMLValue( phPloyModel, "rPolynomial.#nVars",         "3" );
-    CPLSetXMLValue( phPloyModel, "rPolynomial.#order",         "3" );
-    CPLSetXMLValue( phPloyModel, "rPolynomial.#nCoefficients", "20" );
-    for( i = 0; i < 20; i++ )
-    {
-        osField.Printf( "%.15g", phRPC->adfSAMP_NUM_COEFF[anOrder[i] - 1] );
-        if( i > 0 )
-            osMultiField += " ";
-        else
-            osMultiField = "";
-        osMultiField += osField;
-    }
-    phPolynomial = CPLGetXMLNode( phPloyModel, "rPolynomial" );
-    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
-                                 osMultiField );
-
-    // sPolynomial refers to SAMP_DEN
-
-    CPLSetXMLValue( phPloyModel, "sPolynomial.#pType",         "1" );
-    CPLSetXMLValue( phPloyModel, "sPolynomial.#nVars",         "3" );
-    CPLSetXMLValue( phPloyModel, "sPolynomial.#order",         "3" );
-    CPLSetXMLValue( phPloyModel, "sPolynomial.#nCoefficients", "20" );
-    for( i = 0; i < 20; i++ )
-    {
-        osField.Printf( "%.15g", phRPC->adfSAMP_DEN_COEFF[anOrder[i] - 1] );
-        if( i > 0 )
-            osMultiField += " ";
-        else
-            osMultiField = "";
-        osMultiField += osField;
-    }
-    phPolynomial = CPLGetXMLNode( phPloyModel, "sPolynomial" );
-    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
-                                 osMultiField );
-
-    //  -------------------------------------------------------------------
-    //  Add "layerInfo" tree back
-    //  -------------------------------------------------------------------
-
-    CPLAddXMLChild( phMetadata, phClone );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                  GetNoData()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::GetNoData( int nLayer, double* pdfNoDataValue )
-{
-    if( psNoDataList == NULL || CPLListCount( psNoDataList ) == 0 )
-    {
-        return false;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Get only single value NoData, no list of values or value ranges
-    //  -------------------------------------------------------------------
-
-    int nCount = 0;
-    double dfValue = 0.0;
-
-    CPLList* psList = NULL;
-
-    //  -------------------------------------------------------------------
-    //  Process Object Layer values
-    //  -------------------------------------------------------------------
-
-    for( psList = psNoDataList; psList ; psList = psList->psNext )
-    {
-        hNoDataItem* phItem = (hNoDataItem*) psList->pData;
-
-        if( phItem->nBand == 0 )
-        {
-            if( phItem->dfLower == phItem->dfUpper )
-            {
-                dfValue = phItem->dfLower;
-                nCount++;
-            }
-            else
-            {
-                return false; // value range
-            }
-        }
-    }
-
-    //  -------------------------------------------------------------------
-    //  Values from the Object Layer override values from the layers 
-    //  -------------------------------------------------------------------
-
-    if( nCount == 1 )
-    {
-        *pdfNoDataValue = dfValue;
-        return true;
-    }
-
-    //  -------------------------------------------------------------------
-    //  Process SubLayer values
-    //  -------------------------------------------------------------------
-
-    for( psList = psNoDataList; psList ; psList = psList->psNext )
-    {
-        hNoDataItem* phItem = (hNoDataItem*) psList->pData;
-
-        if( phItem->nBand == nLayer )
-        {
-            if( phItem->dfLower == phItem->dfUpper )
-            {
-                dfValue = phItem->dfLower;
-                nCount++;
-            }
-            else
-            {
-                return false; // value range
-            }
-        }
-    }
-
-    if( nCount == 1 )
-    {
-        *pdfNoDataValue = dfValue;
-        return true;
-    }
-
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                             SetNoDataValue()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::SetNoData( int nLayer, const char* pszValue )
-{
-    // ------------------------------------------------------------
-    //  Set one NoData per dataset on "rasterInfo" section (10g)
-    // ------------------------------------------------------------
-
-    if( poConnection->GetVersion() < 11 )
-    {
-        CPLXMLNode* psRInfo = CPLGetXMLNode( phMetadata, "rasterInfo" );
-        CPLXMLNode* psNData = CPLSearchXMLNode( psRInfo, "NODATA" );
-
-        if( psNData == NULL )
-        {
-            psNData = CPLCreateXMLNode( NULL, CXT_Element, "NODATA" );
-
-            CPLXMLNode* psCDepth = CPLGetXMLNode( psRInfo, "cellDepth" );
-
-            CPLXMLNode* psPointer = psCDepth->psNext;
-            psCDepth->psNext = psNData;
-            psNData->psNext = psPointer;
-        }
-
-        CPLSetXMLValue( psRInfo, "NODATA", pszValue );
-        bFlushMetadata = true;
-        return true;
-    }
-
-    // ------------------------------------------------------------
-    //  Add NoData for all bands (layer=0) or for a specific band
-    // ------------------------------------------------------------
-
-    char szRDT[OWCODE];
-    char szNoData[OWTEXT];
-    
-    strcpy( szRDT, sDataTable.c_str() );
-    strcpy( szNoData, pszValue );
-
-    int nRID = nRasterId;
-
-    // ------------------------------------------------------------
-    //  Write the in memory XML metada to avoid lossing other changes
-    // ------------------------------------------------------------
-
-    char* pszMetadata = CPLSerializeXMLTree( phMetadata );
-
-    if( pszMetadata == NULL )
-    {
-        return false;
-    }
-
-    OCILobLocator* phLocatorR = NULL;
-    OCILobLocator* phLocatorW = NULL;
-    
-    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "DECLARE\n"
-        "  GR1 sdo_georaster;\n"
-        "BEGIN\n"
-        "  SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;\n"
-        "\n"
-        "  GR1.metadata := sys.xmltype.createxml(:1);\n"
-        "\n"
-        "  SDO_GEOR.addNODATA( GR1, :2, :3 );\n"
-        "\n"
-        "  UPDATE %s%s T SET %s = GR1 WHERE %s;\n"
-        "\n"
-        "  EXECUTE IMMEDIATE\n"
-        "    'SELECT T.%s.METADATA.getClobVal() FROM %s%s T \n"
-        "     WHERE  T.%s.RASTERDATATABLE = UPPER(:1)\n"
-        "       AND  T.%s.RASTERID = :2'\n"
-        "    INTO :metadata USING :rdt, :rid;\n"
-        "\n"
-        "  COMMIT;\n"
-        "END;",
-            sColumn.c_str(), sSchema.c_str(), sTable.c_str(), sWhere.c_str(),
-            sSchema.c_str(), sTable.c_str(), sColumn.c_str(), sWhere.c_str(),
-            sColumn.c_str(), sSchema.c_str(), sTable.c_str(),
-            sColumn.c_str(),
-            sColumn.c_str() ) );
-
-    poStmt->WriteCLob( &phLocatorW, pszMetadata );
-
-    poStmt->Bind( &phLocatorW );
-    poStmt->Bind( &nLayer );
-    poStmt->Bind( szNoData );
-    poStmt->BindName( ":metadata", &phLocatorR );
-    poStmt->BindName( ":rdt", szRDT );
-    poStmt->BindName( ":rid", &nRID );
-
-    CPLFree( pszMetadata );    
-
-    if( ! poStmt->Execute() )
-    {
-        OCIDescriptorFree( phLocatorR, OCI_DTYPE_LOB );
-        OCIDescriptorFree( phLocatorW, OCI_DTYPE_LOB );
-        delete poStmt;
-        return false;
-    }
-
-    OCIDescriptorFree( phLocatorW, OCI_DTYPE_LOB );
-
-    // ------------------------------------------------------------
-    //  Read the XML metadata from db to memory with nodata updates
-    // ------------------------------------------------------------
-
-    char* pszXML = poStmt->ReadCLob( phLocatorR );
-
-    if( pszXML )
-    {
-        CPLDestroyXMLNode( phMetadata );
-        phMetadata = CPLParseXMLString( pszXML );
-        CPLFree( pszXML );
-    }
-
-    OCIDescriptorFree( phLocatorR, OCI_DTYPE_LOB );
-
-    bFlushMetadata = true;
-    delete poStmt;
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     SetVAT()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::SetVAT( int nBand, const char* pszName )
-{
-    InitializeLayersNode();
-
-    bFlushMetadata = true;
-
-    int n = 1;
-
-    CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    for( ; psLayers; psLayers = psLayers->psNext, n++ )
-    {
-        if( n != nBand )
-        {
-            continue;
-        }
-
-        CPLXMLNode* psVAT = CPLGetXMLNode( psLayers, "vatTableName" );
-
-        if( psVAT != NULL )
-        {
-            CPLRemoveXMLChild( psLayers, psVAT );
-            CPLDestroyXMLNode( psVAT );
-        }
-
-        CPLCreateXMLElementAndValue(psLayers, "vatTableName", pszName );
-
-        // ------------------------------------------------------------
-        // To be updated at Flush Metadata in SDO_GEOR.setVAT()
-        // ------------------------------------------------------------
-
-        sValueAttributeTab = pszName;
-
-        return true;
-    }
-
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                     GetVAT()
-//  ---------------------------------------------------------------------------
-
-char* GeoRasterWrapper::GetVAT( int nBand )
-{
-    CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
-
-    if( psLayers == NULL )
-    {
-        return NULL;
-    }
-
-    char* pszTablename = NULL;
-
-    int n = 1;
-
-    for( ; psLayers; psLayers = psLayers->psNext, n++ )
-    {
-        if( n != nBand )
-        {
-            continue;
-        }
-
-        CPLXMLNode* psVAT = CPLGetXMLNode( psLayers, "vatTableName" );
-
-        if( psVAT != NULL )
-        {
-            pszTablename = CPLStrdup(
-                CPLGetXMLValue( psLayers, "vatTableName", "" ) );
-        }
-
-        break;
-    }
-
-    return pszTablename;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                              FlushMetadata()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::FlushMetadata()
-{
-    if( bFlushBlock )
-    {
-        FlushBlock( nCacheBlockId );
-    }
-
-    if( ! bFlushMetadata )
-    {
-        return true;
-    }
-
-    bFlushMetadata = false;
-
-    //  --------------------------------------------------------------------
-    //  Change the isBlank setting left by SDO_GEOR.createBlank() to 'false'
-    //  --------------------------------------------------------------------
-
-    CPLXMLNode* psOInfo = CPLGetXMLNode( phMetadata, "objectInfo" );
-    CPLXMLNode* psNode  = NULL;
-
-    CPLSetXMLValue( psOInfo,  "isBlank", "false" );
-
-    psNode  = CPLGetXMLNode( psOInfo, "blankCellValue" );
-
-    if( psNode != NULL )
-    {
-        CPLRemoveXMLChild( psOInfo, psNode );
-        CPLDestroyXMLNode( psNode );
-    }
-
-    const char* pszRed   = "1";
-    const char* pszGreen = "1";
-    const char* pszBlue  = "1";
-
-    if( ( nRasterBands > 2 ) &&
-        ( ! HasColorMap( 1 ) ) &&
-        ( ! HasColorMap( 2 ) ) &&
-        ( ! HasColorMap( 3 ) ) )
-    {
-        pszRed   = "1";
-        pszGreen = "2";
-        pszBlue  = "3";
-    }
-
-    psNode = CPLGetXMLNode( psOInfo, "defaultRed" );
-    if( psNode )
-    {
-        CPLRemoveXMLChild( psOInfo, psNode );
-        CPLDestroyXMLNode( psNode );
-    }
-    CPLCreateXMLElementAndValue( psOInfo, "defaultRed",   pszRed );
-
-    psNode = CPLGetXMLNode( psOInfo, "defaultGreen" );
-    if( psNode )
-    {
-        CPLRemoveXMLChild( psOInfo, psNode );
-        CPLDestroyXMLNode( psNode );
-    }
-    CPLCreateXMLElementAndValue( psOInfo, "defaultGreen",   pszGreen );
-
-    psNode = CPLGetXMLNode( psOInfo, "defaultBlue" );
-    if( psNode )
-    {
-        CPLRemoveXMLChild( psOInfo, psNode );
-        CPLDestroyXMLNode( psNode );
-    }
-    CPLCreateXMLElementAndValue( psOInfo, "defaultBlue",   pszBlue );
-
-    //  --------------------------------------------------------------------
-    //  Set compression
-    //  --------------------------------------------------------------------
-
-    psNode = CPLGetXMLNode( phMetadata, "rasterInfo.compression" );
-
-    if( psNode )
-    {
-        CPLSetXMLValue( psNode, "type", sCompressionType.c_str() );
-
-        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
-        {
-            CPLSetXMLValue( psNode, "quality",
-                CPLSPrintf( "%d", nCompressQuality ) );
-        }
-    }
-
-    //  --------------------------------------------------------------------
-    //  Update BitmapMask info
-    //  --------------------------------------------------------------------
-
-    if( bHasBitmapMask )
-    {
-        CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo" );
-
-        if( psLayers )
-        {
-            CPLCreateXMLElementAndValue( psLayers, "bitmapMask", "true" );
-        }
-    }
-
-    //  --------------------------------------------------------------------
-    //  Update the Metadata directly from the XML text
-    //  --------------------------------------------------------------------
-
-    double dfXCoef[3];
-    double dfYCoef[3];
-    int nMLC;
-
-    dfXCoef[0] = dfXCoefficient[0];
-    dfXCoef[1] = dfXCoefficient[1];
-    dfXCoef[2] = dfXCoefficient[2];
-
-    dfYCoef[0] = dfYCoefficient[0];
-    dfYCoef[1] = dfYCoefficient[1];
-    dfYCoef[2] = dfYCoefficient[2];
-
-    if ( eModelCoordLocation == MCL_CENTER )
-    {
-      dfXCoef[2] += dfXCoefficient[0] / 2;
-      dfYCoef[2] += dfYCoefficient[1] / 2;
-      nMLC = MCL_CENTER;
-    }
-    else
-    {
-      nMLC = MCL_UPPERLEFT;
-    }
-
-    if( phRPC )
-    {
-        SetRPC();
-        nSRID = 0;
-    }
-
-    //  --------------------------------------------------------------------
-    //  Serialize XML metadata to plain text
-    //  --------------------------------------------------------------------
-
-    char* pszMetadata = CPLSerializeXMLTree( phMetadata );
-
-    if( pszMetadata == NULL )
-    {
-        return false;
-    }
-
-    if( bGenSpatialIndex )
-    {
-        nExtentSRID = nExtentSRID == 0 ? nSRID : nExtentSRID;
-    }
-    else
-    {
-        nExtentSRID = 0; /* Set spatialExtent to null */
-    }
-
-    //  --------------------------------------------------------------------
-    //  Update GeoRaster Metadata
-    //  --------------------------------------------------------------------
-
-    int nException = 0;
-
-    OCILobLocator* phLocator = NULL;
-
-    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "DECLARE\n"
-        "  GR1      sdo_georaster;\n"
-        "  GM1      sdo_geometry;\n"
-        "  SRID     number  := :1;\n"
-        "  EXT_SRID number  := :2;\n"
-        "  VAT      varchar2(128);\n"
-        "BEGIN\n"
-        "\n"
-        "  SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;\n"
-        "\n"
-        "  GR1.metadata := sys.xmltype.createxml(:3);\n"
-        "\n"
-        "  IF SRID != 0 THEN\n"
-        "    SDO_GEOR.georeference( GR1, SRID, :4,"
-        "      SDO_NUMBER_ARRAY(:5, :6, :7), SDO_NUMBER_ARRAY(:8, :9, :10));\n"
-        "  END IF;\n"
-        "\n"
-        "  IF EXT_SRID = 0 THEN\n"
-        "    GM1 := NULL;\n"
-        "  ELSE\n"
-        "    GM1 := SDO_GEOR.generateSpatialExtent( GR1 );\n"
-        "    IF EXT_SRID != SRID THEN\n"
-        "      GM1 := SDO_CS.transform( GM1, EXT_SRID );\n"
-        "    END IF;\n"
-        "  END IF;\n"
-        "\n"
-        "  GR1.spatialExtent := GM1;\n"
-        "\n"
-        "  VAT := '%s';\n"
-        "  IF VAT != '' THEN\n"
-        "    SDO_GEOR.setVAT(GR1, 1, VAT);\n"
-        "  END IF;\n"
-        "\n"
-        "  BEGIN\n"
-        "    UPDATE %s%s T SET %s = GR1\n"
-        "    WHERE %s;\n"
-        "  EXCEPTION\n"
-        "    WHEN OTHERS THEN\n"
-        "      :except := SQLCODE;\n"
-        "      IF (SQLCODE != -29877) THEN\n"
-        "        RAISE;\n"
-        "      END IF;\n"
-        "  END\n"
-        "\n"
-        "  COMMIT;\n"
-        "END;",
-            sColumn.c_str(),
-            sSchema.c_str(),
-            sTable.c_str(),
-            sWhere.c_str(),
-            sValueAttributeTab.c_str(),
-            sSchema.c_str(),
-            sTable.c_str(),
-            sColumn.c_str(),
-            sWhere.c_str() ) );
-
-    poStmt->WriteCLob( &phLocator, pszMetadata );
-    
-    poStmt->Bind( &nSRID );
-    poStmt->Bind( &nExtentSRID );
-    poStmt->Bind( &phLocator );
-    poStmt->Bind( &nMLC );
-    poStmt->Bind( &dfXCoef[0] );
-    poStmt->Bind( &dfXCoef[1] );
-    poStmt->Bind( &dfXCoef[2] );
-    poStmt->Bind( &dfYCoef[0] );
-    poStmt->Bind( &dfYCoef[1] );
-    poStmt->Bind( &dfYCoef[2] );
-    poStmt->BindName( ":except", &nException );
-
-    CPLFree( pszMetadata );
-
-    if( ! poStmt->Execute() )
-    {
-        OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
-        delete poStmt;
-        return false;
-    }
-
-    OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
-
-    delete poStmt;
-
-    if( nException )
-    {
-        CPLError( CE_Warning, CPLE_AppDefined, 
-            "Cannot generate spatialExtent! (ORA-%d) ", nException );
-    }
-
-    if (bGenPyramid) 
-    {
-        if (GeneratePyramid( nPyramidLevels, sPyramidResampling.c_str(), true ))
-        {
-            CPLDebug("GEOR", "Generated pyramid successfully.");
-        }
-        else
-        {
-            CPLError( CE_Warning, CPLE_AppDefined, "Error generating pyramid!");
-        }
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            GeneratePyramid()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::GeneratePyramid( int nLevels,
-                                        const char* pszResampling,
-                                        bool bInternal )
-{
-    nPyramidMaxLevel = nLevels;
-
-    if( bInternal )
-    {
-        CPLString sLevels = "";
-
-        if (nLevels > 0)
-        {
-            sLevels = CPLSPrintf("rlevel=%d", nLevels);
-        }
-
-        OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
-            "DECLARE\n"
-            "  gr sdo_georaster;\n"
-            "BEGIN\n"
-            "  SELECT %s INTO gr FROM %s t WHERE %s FOR UPDATE;\n"
-            "  sdo_geor.generatePyramid(gr, '%s resampling=%s');\n"
-            "  UPDATE %s t SET %s = gr WHERE %s;\n"
-            "  COMMIT;\n"
-            "END;\n",
-                sColumn.c_str(),
-                sTable.c_str(),
-                sWhere.c_str(),
-                sLevels.c_str(),
-                pszResampling,
-                sTable.c_str(),
-                sColumn.c_str(),
-                sWhere.c_str() ) );
-
-        if( poStmt->Execute() )
-        {
-            delete poStmt;
-            return true;
-        }
-
-        delete poStmt;
-        return false;
-    }
-
-    //  -----------------------------------------------------------
-    //  Create rows for pyramid levels
-    //  -----------------------------------------------------------
-
-    OWStatement* poStmt = NULL;
-
-    poStmt = poConnection->CreateStatement(
-        "DECLARE\n"
-        "  SCL  NUMBER         := 0;\n"
-        "  RC   NUMBER         := 0;\n"
-        "  RR   NUMBER         := 0;\n"
-        "  CBS2 NUMBER         := 0;\n"
-        "  RBS2 NUMBER         := 0;\n"
-        "  TBB  NUMBER         := 0;\n"
-        "  TRB  NUMBER         := 0;\n"
-        "  TCB  NUMBER         := 0;\n"
-        "  X    NUMBER         := 0;\n"
-        "  Y    NUMBER         := 0;\n"
-        "  W    NUMBER         := 0;\n"
-        "  H    NUMBER         := 0;\n"
-        "  STM  VARCHAR2(1024) := '';\n"
-        "BEGIN\n"
-        "  EXECUTE IMMEDIATE 'DELETE FROM '||:rdt||' \n"
-        "    WHERE RASTERID = '||:rid||' AND PYRAMIDLEVEL > 0';\n"
-        "  STM := 'INSERT INTO '||:rdt||' VALUES (:1, :2, :3-1, :4-1, :5-1 ,\n"
-        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
-        "    SDO_ORDINATE_ARRAY(:6, :7, :8-1, :9-1)), EMPTY_BLOB() )';\n"
-        "  TBB  := :TotalBandBlocks;\n"
-        "  RBS2 := floor(:RowBlockSize / 2);\n"
-        "  CBS2 := floor(:ColumnBlockSize / 2);\n"
-        "  FOR l IN 1..:level LOOP\n"
-        "    SCL := 2 ** l;\n"
-        "    RR  := floor(:RasterRows / SCL);\n"
-        "    RC  := floor(:RasterColumns / SCL);\n"
-        "    IF (RC <= CBS2) OR (RR <= RBS2) THEN\n"
-        "      H   := RR;\n"
-        "      W   := RC;\n"
-        "    ELSE\n"
-        "      H   := :RowBlockSize;\n"
-        "      W   := :ColumnBlockSize;\n"
-        "    END IF;\n"
-        "    TRB := greatest(1, ceil( ceil(:RasterColumns / :ColumnBlockSize) / SCL));\n"
-        "    TCB := greatest(1, ceil( ceil(:RasterRows / :RowBlockSize) / SCL));\n"
-        "    FOR b IN 1..TBB LOOP\n"
-        "      Y := 0;\n"
-        "      FOR r IN 1..TCB LOOP\n"
-        "        X := 0;\n"
-        "        FOR c IN 1..TRB LOOP\n"
-        "          EXECUTE IMMEDIATE STM USING :rid, l, b, r, c, Y, X, (Y+H), (X+W);\n"
-        "          X := X + W;\n"
-        "        END LOOP;\n"
-        "        Y := Y + H;\n"
-        "      END LOOP;\n"
-        "    END LOOP;\n"
-        "  END LOOP;\n"
-        "  COMMIT;\n"
-        "END;" );
-
-    const char* pszDataTable = sDataTable.c_str();
-
-    poStmt->BindName( ":rdt",             (char*) pszDataTable );
-    poStmt->BindName( ":rid",             &nRasterId );
-    poStmt->BindName( ":level",           &nLevels );
-    poStmt->BindName( ":TotalBandBlocks", &nTotalBandBlocks );
-    poStmt->BindName( ":RowBlockSize",    &nRowBlockSize );
-    poStmt->BindName( ":ColumnBlockSize", &nColumnBlockSize );
-    poStmt->BindName( ":RasterRows",      &nRasterRows );
-    poStmt->BindName( ":RasterColumns",   &nRasterColumns );
-
-    if( ! poStmt->Execute() )
-    {
-        delete poStmt;
-        return false;
-    }
-
-    CPLXMLNode* psNode = CPLGetXMLNode( phMetadata, "rasterInfo.pyramid" );
-
-    if( psNode )
-    {
-        CPLSetXMLValue( psNode, "type", "DECREASE" );
-        CPLSetXMLValue( psNode, "resampling", pszResampling );
-        CPLSetXMLValue( psNode, "maxLevel", CPLSPrintf( "%d", nLevels ) );
-    }
-
-    bFlushMetadata = true;
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            GeneratePyramid()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::DeletePyramid()
-{
-    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
-        "DECLARE\n"
-        "  gr sdo_georaster;\n"
-        "BEGIN\n"
-        "  SELECT %s INTO gr FROM %s t WHERE %s FOR UPDATE;\n"
-        "  sdo_geor.deletePyramid(gr);\n"
-        "  UPDATE %s t SET %s = gr WHERE %s;\n"
-        "  COMMIT;\n"
-        "END;\n",
-            sColumn.c_str(),
-            sTable.c_str(),
-            sWhere.c_str(),
-            sTable.c_str(),
-            sColumn.c_str(),
-            sWhere.c_str() ) );
-    
-    poStmt->Execute();
-
-    delete poStmt;
-    return false;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                           CreateBitmapMask()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::InitializeMask( int nLevel,
-                                       int nBlockColumns,
-                                       int nBlockRows,
-                                       int nColumnBlocks,
-                                       int nRowBlocks,
-                                       int nBandBlocks )
-{
-    //  -----------------------------------------------------------
-    //  Create rows for the bitmap mask
-    //  -----------------------------------------------------------
-
-    OWStatement* poStmt = NULL;
-
-    poStmt = poConnection->CreateStatement(
-        "DECLARE\n"
-        "  W    NUMBER          := :1;\n"
-        "  H    NUMBER          := :2;\n"
-        "  BB   NUMBER          := :3;\n"
-        "  RB   NUMBER          := :4;\n"
-        "  CB   NUMBER          := :5;\n"
-        "  X    NUMBER          := 0;\n"
-        "  Y    NUMBER          := 0;\n"
-        "  STM  VARCHAR2(1024)  := '';\n"
-        "BEGIN\n"
-        "\n"
-        "  EXECUTE IMMEDIATE 'DELETE FROM '||:rdt||' \n"
-        "    WHERE RASTERID = '||:rid||' AND PYRAMIDLEVEL = '||:lev||' ';\n"
-        "\n"
-        "  STM := 'INSERT INTO '||:rdt||' VALUES (:1, :lev, :2-1, :3-1, :4-1 ,\n"
-        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
-        "    SDO_ORDINATE_ARRAY(:5, :6, :7-1, :8-1)), EMPTY_BLOB() )';\n"
-        "\n"
-        "  FOR b IN 1..BB LOOP\n"
-        "    Y := 0;\n"
-        "    FOR r IN 1..RB LOOP\n"
-        "      X := 0;\n"
-        "      FOR c IN 1..CB LOOP\n"
-        "        EXECUTE IMMEDIATE STM USING :rid, b, r, c, Y, X, (Y+H), (X+W);\n"
-        "        X := X + W;\n"
-        "      END LOOP;\n"
-        "      Y := Y + H;\n"
-        "    END LOOP;\n"
-        "  END LOOP;\n"
-        "END;" );
-
-    char pszDataTable[OWNAME];
-    
-    poStmt->Bind( &nBlockColumns );
-    poStmt->Bind( &nBlockRows );
-    poStmt->Bind( &nBandBlocks );
-    poStmt->Bind( &nRowBlocks );
-    poStmt->Bind( &nColumnBlocks );
-    poStmt->BindName( ":rdt", pszDataTable );
-    poStmt->BindName( ":rid", &nRasterId );
-    poStmt->BindName( ":lev", &nLevel );
-
-    if( ! poStmt->Execute() )
-    {
-        delete poStmt;
-        return false;
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                UnpackNBits()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::UnpackNBits( GByte* pabyData )
-{
-    int nPixCount = nColumnBlockSize * nRowBlockSize * nBandBlockSize;
-
-    if( EQUAL( sCellDepth.c_str(), "4BIT" ) )
-    {
-        for( int ii = nPixCount - 2; ii >= 0; ii -= 2 )
-        {
-            int k = ii >> 1;
-            pabyData[ii+1] = (pabyData[k]     ) & 0xf;
-            pabyData[ii]   = (pabyData[k] >> 4) & 0xf;
-        }
-    }
-    else if( EQUAL( sCellDepth.c_str(), "2BIT" ) )
-    {
-        for( int ii = nPixCount - 4; ii >= 0; ii -= 4 )
-        {
-            int k = ii >> 2;
-            pabyData[ii+3] = (pabyData[k]     ) & 0x3;
-            pabyData[ii+2] = (pabyData[k] >> 2) & 0x3;
-            pabyData[ii+1] = (pabyData[k] >> 4) & 0x3;
-            pabyData[ii]   = (pabyData[k] >> 6) & 0x3;
-        }
-    }
-    else
-    {
-        for( int ii = nPixCount - 1; ii >= 0; ii-- )
-        {
-            if( ( pabyData[ii>>3] & ( 128 >> (ii & 0x7) ) ) )
-                pabyData[ii] = 1;
-            else
-                pabyData[ii] = 0;
-        }
-    }
-}
-
-//  ---------------------------------------------------------------------------
-//                                                                  PackNBits()
-//  ---------------------------------------------------------------------------
-
-void GeoRasterWrapper::PackNBits( GByte* pabyData )
-{
-    int nPixCount = nBandBlockSize * nRowBlockSize * nColumnBlockSize;
-
-    GByte* pabyBuffer = (GByte*) VSIMalloc( nPixCount * sizeof(GByte*) );
-
-    if( pabyBuffer == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory, "PackNBits" );
-        return;
-    }
-
-    if( nCellSizeBits == 4 )
-    {
-        for( int ii = 0; ii < nPixCount - 1; ii += 2 )
-        {
-            int k = ii >> 1;
-            pabyBuffer[k] =
-                  ((((GByte *) pabyData)[ii+1] & 0xf)     )
-                | ((((GByte *) pabyData)[ii]   & 0xf) << 4);
-        }
-    }
-    else if( nCellSizeBits == 2 )
-    {
-        for( int ii = 0; ii < nPixCount - 3; ii += 4 )
-        {
-            int k = ii >> 2;
-            pabyBuffer[k] =
-                  ((((GByte *) pabyData)[ii+3] & 0x3)     )
-                | ((((GByte *) pabyData)[ii+2] & 0x3) << 2)
-                | ((((GByte *) pabyData)[ii+1] & 0x3) << 4)
-                | ((((GByte *) pabyData)[ii]   & 0x3) << 6);
-        }
-    }
-    else
-    {
-        for( int ii = 0; ii < nPixCount - 7; ii += 8 )
-        {
-            int k = ii >> 3;
-            pabyBuffer[k] =
-                  ((((GByte *) pabyData)[ii+7] & 0x1)     )
-                | ((((GByte *) pabyData)[ii+6] & 0x1) << 1)
-                | ((((GByte *) pabyData)[ii+5] & 0x1) << 2)
-                | ((((GByte *) pabyData)[ii+4] & 0x1) << 3)
-                | ((((GByte *) pabyData)[ii+3] & 0x1) << 4)
-                | ((((GByte *) pabyData)[ii+2] & 0x1) << 5)
-                | ((((GByte *) pabyData)[ii+1] & 0x1) << 6)
-                | ((((GByte *) pabyData)[ii]   & 0x1) << 7);
-        }
-    }
-
-    memcpy( pabyData, pabyBuffer, nPixCount );
-
-    CPLFree( pabyBuffer );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                             UncompressJpeg()
-//  ---------------------------------------------------------------------------
-
-const static int K2Chrominance[64] =
-{
-    17, 18, 24, 47, 99, 99, 99, 99,
-    18, 21, 26, 66, 99, 99, 99, 99,
-    24, 26, 56, 99, 99, 99, 99, 99,
-    47, 66, 99, 99, 99, 99, 99, 99,
-    99, 99, 99, 99, 99, 99, 99, 99,
-    99, 99, 99, 99, 99, 99, 99, 99,
-    99, 99, 99, 99, 99, 99, 99, 99,
-    99, 99, 99, 99, 99, 99, 99, 99
-};
-
-static const int AC_BITS[16] =
-{
-    0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119
-};
-
-static const int AC_HUFFVAL[256] =
-{
-      0,   1,   2,   3,  17,   4,   5,  33,  49,   6,  18,
-     65,  81,   7,  97, 113,  19,  34,  50, 129,   8,  20,
-     66, 145, 161, 177, 193,   9,  35,  51,  82, 240,  21,
-     98, 114, 209,  10,  22,  36,  52, 225,  37, 241,  23,
-     24,  25,  26,  38,  39,  40,  41,  42,  53,  54,  55,
-     56,  57,  58,  67,  68,  69,  70,  71,  72,  73,  74,
-     83,  84,  85,  86,  87,  88,  89,  90,  99, 100, 101,
-    102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120,
-    121, 122, 130, 131, 132, 133, 134, 135, 136, 137, 138,
-    146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163,
-    164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181,
-    182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199,
-    200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217,
-    218, 226, 227, 228, 229, 230, 231, 232, 233, 234, 242,
-    243, 244, 245, 246, 247, 248, 249, 250
-};
-
-static const int DC_BITS[16] =
-{
-    0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
-};
-
-static const int DC_HUFFVAL[256] =
-{
-    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
-};
-
-/***
- *
- * Load the tables based on the Java's JAI default values.
- *
- * JPEGQTable.K2Chrominance.getScaledInstance()
- * JPEGHuffmanTable.StdACChrominance
- * JPEGHuffmanTable.StdDCChrominance
- *
- ***/
-
-void JPEG_LoadTables( JQUANT_TBL* hquant_tbl_ptr,
-                      JHUFF_TBL* huff_ac_ptr,
-                      JHUFF_TBL* huff_dc_ptr,
-                      unsigned int nQuality )
-{
-    int i = 0;
-    float fscale_factor;
-
-    //  --------------------------------------------------------------------
-    //  Scale Quantization table based on quality
-    //  --------------------------------------------------------------------
-
-    fscale_factor = (float) jpeg_quality_scaling( nQuality ) / (float) 100.0;
-
-    for ( i = 0; i < 64; i++ )
-    {
-        UINT16 temp = (UINT16) floor( K2Chrominance[i] * fscale_factor + 0.5 );
-        if ( temp <= 0 )
-            temp = 1;
-        if ( temp > 255 )
-            temp = 255;
-        hquant_tbl_ptr->quantval[i] = (UINT16) temp;
-    }
-
-    //  --------------------------------------------------------------------
-    //  Load AC huffman table
-    //  --------------------------------------------------------------------
-
-    for ( i = 1; i <= 16; i++ )
-    {
-        /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
-        huff_ac_ptr->bits[i] = (UINT8) AC_BITS[i-1];
-    }
-
-    for ( i = 0; i < 256; i++ )
-    {
-        /* symbols[] is the list of Huffman symbols, in code-length order */
-        huff_ac_ptr->huffval[i] = (UINT8) AC_HUFFVAL[i];
-    }
-
-    //  --------------------------------------------------------------------
-    //  Load DC huffman table
-    //  --------------------------------------------------------------------
-
-    for ( i = 1; i <= 16; i++ )
-    {
-        /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
-        huff_dc_ptr->bits[i] = (UINT8) DC_BITS[i-1];
-    }
-
-    for ( i = 0; i < 256; i++ )
-    {
-        /* symbols[] is the list of Huffman symbols, in code-length order */
-        huff_dc_ptr->huffval[i] = (UINT8) DC_HUFFVAL[i];
-    }
-}
-
-void GeoRasterWrapper::UncompressJpeg( unsigned long nInSize )
-{
-    //  --------------------------------------------------------------------
-    //  Load JPEG in a virtual file
-    //  --------------------------------------------------------------------
-
-    const char* pszMemFile = CPLSPrintf( "/vsimem/geor_%p.jpg", pabyBlockBuf );
-
-    VSILFILE *fpImage = VSIFOpenL( pszMemFile, "wb" );
-    VSIFWriteL( pabyBlockBuf, nInSize, 1, fpImage );
-    VSIFCloseL( fpImage );
-
-    fpImage = VSIFOpenL( pszMemFile, "rb" );
-
-    //  --------------------------------------------------------------------
-    //  Initialize decompressor
-    //  --------------------------------------------------------------------
-
-    if( ! sDInfo.global_state )
-    {
-        sDInfo.err = jpeg_std_error( &sJErr );
-        jpeg_create_decompress( &sDInfo );
-
-        // -----------------------------------------------------------------
-        // Load table for abbreviated JPEG-B
-        // -----------------------------------------------------------------
-
-        int nComponentsToLoad = -1; /* doesn't load any table */
-
-        if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
-        {
-            nComponentsToLoad = nBandBlockSize;
-        }
-
-        for( int n = 0; n < nComponentsToLoad; n++ )
-        {
-            sDInfo.quant_tbl_ptrs[n] =
-                jpeg_alloc_quant_table( (j_common_ptr) &sDInfo );
-            sDInfo.ac_huff_tbl_ptrs[n] =
-                jpeg_alloc_huff_table( (j_common_ptr) &sDInfo );
-            sDInfo.dc_huff_tbl_ptrs[n] =
-                jpeg_alloc_huff_table( (j_common_ptr) &sDInfo );
-            
-            JPEG_LoadTables( sDInfo.quant_tbl_ptrs[n],
-                             sDInfo.ac_huff_tbl_ptrs[n],
-                             sDInfo.dc_huff_tbl_ptrs[n],
-                             nCompressQuality );
-        }
-
-    }
-
-    jpeg_vsiio_src( &sDInfo, fpImage );
-    jpeg_read_header( &sDInfo, TRUE );
-
-    sDInfo.out_color_space = ( nBandBlockSize == 1 ? JCS_GRAYSCALE : JCS_RGB );
-
-    jpeg_start_decompress( &sDInfo );
-
-    GByte* pabyScanline = pabyBlockBuf;
-
-    for( int iLine = 0; iLine < nRowBlockSize; iLine++ )
-    {
-        JSAMPLE* ppSamples = (JSAMPLE*) pabyScanline;
-        jpeg_read_scanlines( &sDInfo, &ppSamples, 1 );
-        pabyScanline += ( nColumnBlockSize * nBandBlockSize );
-    }
-
-    jpeg_finish_decompress( &sDInfo );
-
-    VSIFCloseL( fpImage );
-
-    VSIUnlink( pszMemFile );
-}
-
-//  ---------------------------------------------------------------------------
-//                                                               CompressJpeg()
-//  ---------------------------------------------------------------------------
-
-unsigned long GeoRasterWrapper::CompressJpeg( void )
-{
-    //  --------------------------------------------------------------------
-    //  Load JPEG in a virtual file
-    //  --------------------------------------------------------------------
-
-    const char* pszMemFile = CPLSPrintf( "/vsimem/geor_%p.jpg", pabyBlockBuf );
-
-    VSILFILE *fpImage = VSIFOpenL( pszMemFile, "wb" );
-
-    bool write_all_tables = TRUE;
-
-    if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
-    {
-        write_all_tables = FALSE;
-    }
-
-    //  --------------------------------------------------------------------
-    //  Initialize compressor
-    //  --------------------------------------------------------------------
-
-    if( ! sCInfo.global_state )
-    {
-        sCInfo.err = jpeg_std_error( &sJErr );
-        jpeg_create_compress( &sCInfo );
-
-        jpeg_vsiio_dest( &sCInfo, fpImage );
-        
-        sCInfo.image_width = nColumnBlockSize;
-        sCInfo.image_height = nRowBlockSize;
-        sCInfo.input_components = nBandBlockSize;
-        sCInfo.in_color_space = (nBandBlockSize == 1 ? JCS_GRAYSCALE : JCS_RGB);
-        jpeg_set_defaults( &sCInfo );
-        sCInfo.JFIF_major_version = 1;
-        sCInfo.JFIF_minor_version = 2;
-        jpeg_set_quality( &sCInfo, nCompressQuality, TRUE );
-
-        // -----------------------------------------------------------------
-        // Load table for abbreviated JPEG-B
-        // -----------------------------------------------------------------
-
-        int nComponentsToLoad = -1; /* doesn't load any table */
-
-        if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
-        {
-            nComponentsToLoad = nBandBlockSize;
-        }
-
-        for( int n = 0; n < nComponentsToLoad; n++ )
-        {
-            sCInfo.quant_tbl_ptrs[n] =
-                jpeg_alloc_quant_table( (j_common_ptr) &sCInfo );
-            sCInfo.ac_huff_tbl_ptrs[n] =
-                jpeg_alloc_huff_table( (j_common_ptr) &sCInfo );
-            sCInfo.dc_huff_tbl_ptrs[n] =
-                jpeg_alloc_huff_table( (j_common_ptr) &sCInfo );
-
-            JPEG_LoadTables( sCInfo.quant_tbl_ptrs[n],
-                             sCInfo.ac_huff_tbl_ptrs[n],
-                             sCInfo.dc_huff_tbl_ptrs[n],
-                             nCompressQuality );
-        }
-    }
-    else
-    {
-        jpeg_vsiio_dest( &sCInfo, fpImage );
-    }
-    
-    jpeg_suppress_tables( &sCInfo, ! write_all_tables );
-    jpeg_start_compress( &sCInfo, write_all_tables );
-    
-    GByte* pabyScanline = pabyBlockBuf;
-
-    for( int iLine = 0; iLine < nRowBlockSize; iLine++ )
-    {
-        JSAMPLE* ppSamples = (JSAMPLE*) pabyScanline;
-        jpeg_write_scanlines( &sCInfo, &ppSamples, 1 );
-        pabyScanline += ( nColumnBlockSize * nBandBlockSize );
-    }
-
-    jpeg_finish_compress( &sCInfo );
-
-    VSIFCloseL( fpImage );
-
-    fpImage = VSIFOpenL( pszMemFile, "rb" );
-    size_t nSize = VSIFReadL( pabyCompressBuf, 1, nBlockBytes, fpImage );
-    VSIFCloseL( fpImage );
-
-    VSIUnlink( pszMemFile );
-
-    return (unsigned long) nSize;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                          UncompressDeflate()
-//  ---------------------------------------------------------------------------
-
-bool GeoRasterWrapper::UncompressDeflate( unsigned long nBufferSize )
-{
-    GByte* pabyBuf = (GByte*) VSIMalloc( nBufferSize );
-
-    if( pabyBuf == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory, "UncompressDeflate" );
-        return false;
-    }
-
-    memcpy( pabyBuf, pabyBlockBuf, nBufferSize );
-
-    // Call ZLib uncompress
-
-    unsigned long nDestLen = nBlockBytes;
-
-    int nRet = uncompress( pabyBlockBuf, &nDestLen, pabyBuf, nBufferSize );
-
-    CPLFree( pabyBuf );
-
-    if( nRet != Z_OK )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, "ZLib return code (%d)", nRet );
-        return false;
-    }
-
-    if( nDestLen != nBlockBytes )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-            "ZLib decompressed buffer size (%ld) expected (%ld)", nDestLen, nBlockBytes );
-        return false;
-    }
-
-    return true;
-}
-
-//  ---------------------------------------------------------------------------
-//                                                            CompressDeflate()
-//  ---------------------------------------------------------------------------
-
-unsigned long GeoRasterWrapper::CompressDeflate( void )
-{
-    unsigned long nLen = ((unsigned long)(nBlockBytes * 1.1)) + 12;
-
-    GByte* pabyBuf = (GByte*) VSIMalloc( nBlockBytes );
-
-    if( pabyBuf == NULL )
-    {
-        CPLError( CE_Failure, CPLE_OutOfMemory, "CompressDeflate" );
-        return 0;
-    }
-
-    memcpy( pabyBuf, pabyBlockBuf, nBlockBytes );
-
-    // Call ZLib compress
-
-    int nRet = compress( pabyCompressBuf, &nLen, pabyBuf, nBlockBytes );
-
-    CPLFree( pabyBuf );
-
-    if( nRet != Z_OK )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, "ZLib return code (%d)", nRet );
-        return 0;
-    }
-
-    return nLen;
-}
+/******************************************************************************
+ * $Id: $
+ *
+ * Name:     georaster_wrapper.cpp
+ * Project:  Oracle Spatial GeoRaster Driver
+ * Purpose:  Implement GeoRasterWrapper methods
+ * Author:   Ivan Lucena [ivan.lucena at oracle.com]
+ *
+ ******************************************************************************
+ * Copyright (c) 2008, Ivan Lucena
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files ( the "Software" ),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *****************************************************************************/
+
+#include <string.h>
+
+#include "georaster_priv.h"
+#include "cpl_error.h"
+#include "cpl_string.h"
+#include "cpl_minixml.h"
+
+//  ---------------------------------------------------------------------------
+//                                                           GeoRasterWrapper()
+//  ---------------------------------------------------------------------------
+
+GeoRasterWrapper::GeoRasterWrapper()
+{
+    nRasterId           = -1;
+    phMetadata          = NULL;
+    nRasterRows         = 0;
+    nRasterColumns      = 0;
+    nRasterBands        = 0;
+    nRowBlockSize       = 0;
+    nColumnBlockSize    = 0;
+    nBandBlockSize      = 0;
+    nTotalColumnBlocks  = 0;
+    nTotalRowBlocks     = 0;
+    nTotalBandBlocks    = 0;
+    nCellSizeBits       = 0;
+    nGDALCellBytes      = 0;
+    dfXCoefficient[0]   = 1.0;
+    dfXCoefficient[1]   = 0.0;
+    dfXCoefficient[2]   = 0.0;
+    dfYCoefficient[0]   = 0.0;
+    dfYCoefficient[1]   = 1.0;
+    dfYCoefficient[2]   = 0.0;
+    sCompressionType    = "NONE";
+    nCompressQuality    = 75;
+    bGenPyramid         = false;
+    nPyramidLevels      = 0;
+    sPyramidResampling  = "NN";
+    pahLocator          = NULL;
+    pabyBlockBuf        = NULL;
+    pabyCompressBuf     = NULL;
+    bIsReferenced       = false;
+    poBlockStmt         = NULL;
+    nCacheBlockId       = -1;
+    nCurrentLevel       = -1;
+    pahLevels           = NULL;
+    nLevelOffset        = 0L;
+    sInterleaving       = "BSQ";
+    bUpdate             = false;
+    bInitializeIO       = false;
+    bFlushMetadata      = false;
+    nSRID               = 0;
+    nExtentSRID         = 0;
+    bGenSpatialIndex    = false;
+    bCreateObjectTable  = false;
+    nPyramidMaxLevel    = 0;
+    nBlockCount         = 0L;
+    nGDALBlockBytes     = 0L;
+    sDInfo.global_state = 0;
+    sCInfo.global_state = 0;
+    bHasBitmapMask      = false;
+    nBlockBytes         = 0L;
+    bFlushBlock         = false;
+    nFlushBlockSize     = 0L;
+    bUniqueFound        = false;
+    sValueAttributeTab  = "";
+    psNoDataList        = NULL;
+    bWriteOnly          = false;
+    bBlocking           = true;
+    bAutoBlocking       = false;
+    eModelCoordLocation = MCL_DEFAULT;
+    phRPC               = NULL;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                           GeoRasterDataset()
+//  ---------------------------------------------------------------------------
+
+GeoRasterWrapper::~GeoRasterWrapper()
+{
+    FlushMetadata();
+
+    if( pahLocator && nBlockCount )
+    {
+        OWStatement::Free( pahLocator, nBlockCount );
+    }
+
+    CPLFree( pahLocator );
+    CPLFree( pabyBlockBuf );
+    CPLFree( pabyCompressBuf );
+    CPLFree( pahLevels );
+    
+    if( CPLListCount( psNoDataList ) )
+    {
+        CPLList* psList = NULL;
+        
+        for( psList = psNoDataList; psList ; psList = psList->psNext )
+        {
+            CPLFree( psList->pData );
+        }
+        
+        CPLListDestroy( psNoDataList );
+    }
+
+    if( poBlockStmt )
+    {
+        delete poBlockStmt;
+    }
+
+    CPLDestroyXMLNode( phMetadata );
+    
+    if( sDInfo.global_state )
+    {
+        jpeg_destroy_decompress( &sDInfo );
+    }
+
+    if( sCInfo.global_state )
+    {
+        jpeg_destroy_compress( &sCInfo );
+    }
+
+    if( poConnection )
+    {
+        delete poConnection;
+    }
+
+    if( phRPC )
+    {
+        CPLFree( phRPC );
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                         ParseIdentificator()
+//  ---------------------------------------------------------------------------
+//
+//  StringID:
+//      {georaster,geor}:<name>{/,,}<password>{/,@}<db>,<tab>,<col>,<where>
+//      {georaster,geor}:<name>{/,,}<password>{/,@}<db>,<rdt>,<rid>
+//
+//  ---------------------------------------------------------------------------
+
+char** GeoRasterWrapper::ParseIdentificator( const char* pszStringID )
+{
+
+    char* pszStartPos = (char*) strstr( pszStringID, ":" ) + 1;
+
+    char** papszParam = CSLTokenizeString2( pszStartPos, ",@",
+                            CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS |
+                            CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES );
+
+    //  -------------------------------------------------------------------
+    //  The "/" should not be catch on the previous parser
+    //  -------------------------------------------------------------------
+
+    if( CSLCount( papszParam ) > 0 )
+    {
+        char** papszFirst2 = CSLTokenizeString2( papszParam[0], "/",
+                             CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
+        if( CSLCount( papszFirst2 ) == 2 )
+        {
+            papszParam = CSLInsertStrings( papszParam, 0, papszFirst2 );
+            papszParam = CSLRemoveStrings( papszParam, 2, 1, NULL );
+        }
+        CSLDestroy( papszFirst2 );
+    }
+
+    return papszParam;
+
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                       Open()
+//  ---------------------------------------------------------------------------
+
+GeoRasterWrapper* GeoRasterWrapper::Open( const char* pszStringId, bool bUpdate )
+{
+    char** papszParam = ParseIdentificator( pszStringId );
+
+    //  ---------------------------------------------------------------
+    //  Validate identificator
+    //  ---------------------------------------------------------------
+
+    int nArgc = CSLCount( papszParam );
+
+    for( ; nArgc < 3; nArgc++ )
+    {
+        papszParam = CSLAddString( papszParam, "" );
+    }
+
+    //  ---------------------------------------------------------------
+    //  Create a GeoRasterWrapper object
+    //  ---------------------------------------------------------------
+
+    GeoRasterWrapper* poGRW = new GeoRasterWrapper();
+
+    if( ! poGRW )
+    {
+        return NULL;
+    }
+
+    poGRW->bUpdate = bUpdate;
+    
+    //  ---------------------------------------------------------------
+    //  Get a connection with Oracle server
+    //  ---------------------------------------------------------------
+
+    poGRW->poConnection = new OWConnection( papszParam[0],
+                                            papszParam[1],
+                                            papszParam[2] );
+
+    if( ! poGRW->poConnection->Succeeded() )
+    {
+        CSLDestroy( papszParam );
+        delete poGRW;
+        return NULL;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Extract schema name
+    //  -------------------------------------------------------------------
+
+    if( nArgc > 3 )
+    {
+        char** papszSchema = CSLTokenizeString2( papszParam[3], ".",
+                                CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
+
+        if( CSLCount( papszSchema ) == 2 )
+        {
+            poGRW->sOwner  = papszSchema[0];
+            poGRW->sSchema = CPLSPrintf( "%s.", poGRW->sOwner.c_str() );
+
+            papszParam = CSLRemoveStrings( papszParam, 3, 1, NULL );
+
+            if( ! EQUAL( papszSchema[1], "" ) )
+            {
+                papszParam = CSLInsertString( papszParam, 3, papszSchema[1] );
+            }
+
+            nArgc = CSLCount( papszParam );
+        }
+        else
+        {
+            poGRW->sSchema = "";
+            poGRW->sOwner  = poGRW->poConnection->GetUser();
+        }
+        
+        CSLDestroy( papszSchema );
+    }
+    else
+    {
+        poGRW->sSchema = "";
+        poGRW->sOwner  = poGRW->poConnection->GetUser();
+    }
+
+    //  -------------------------------------------------------------------
+    //  Assign parameters from Identification string
+    //  -------------------------------------------------------------------
+
+    switch( nArgc )
+    {
+    case 6 :
+        poGRW->sTable   = papszParam[3];
+        poGRW->sColumn  = papszParam[4];
+        poGRW->sWhere   = papszParam[5];
+        break;
+    case 5 :
+        if( OWIsNumeric( papszParam[4] ) )
+        {
+            poGRW->sDataTable   = papszParam[3];
+            poGRW->nRasterId    = atoi( papszParam[4]);
+            break;
+        }
+        else
+        {
+            poGRW->sTable   = papszParam[3];
+            poGRW->sColumn  = papszParam[4];
+            return poGRW;
+        }
+    case 4 :
+        poGRW->sTable   = papszParam[3];
+        return poGRW;
+    default :
+        return poGRW;
+    }
+
+    CSLDestroy( papszParam );
+
+    //  -------------------------------------------------------------------
+    //  Query all the basic information at once to reduce round trips
+    //  -------------------------------------------------------------------
+
+    char szOwner[OWCODE];
+    char szTable[OWCODE];
+    char szColumn[OWTEXT];
+    char szDataTable[OWCODE];
+    char szWhere[OWTEXT];
+    int nRasterId = -1;
+    int nSizeX = 0;
+    int nSizeY = 0;
+    int nSRID  = 0;
+    OCILobLocator* phLocator = NULL;
+    double dfULx = 0.0;
+    double dfURx = 0.0;
+    double dfLRx = 0.0;
+    double dfULy = 0.0;
+    double dfLLy = 0.0;
+    double dfLRy = 0.0;
+    char szWKText[3 * OWTEXT];
+    char szAuthority[OWTEXT];
+    char szMLC[OWTEXT];
+
+    szOwner[0]     = '\0';
+    szTable[0]     = '\0';
+    szColumn[0]    = '\0';
+    szDataTable[0] = '\0';
+    szWhere[0]     = '\0';
+    szWKText[0]    = '\0';
+    szAuthority[0] = '\0';
+    szMLC[0]       = '\0';
+
+    if( ! poGRW->sOwner.empty() )
+    {
+      strcpy( szOwner, poGRW->sOwner.c_str() );
+    }
+
+    if( ! poGRW->sTable.empty() )
+    {
+      strcpy( szTable, poGRW->sTable.c_str() );
+    }
+
+    if( ! poGRW->sColumn.empty() )
+    {
+      strcpy( szColumn, poGRW->sColumn.c_str() );
+    }
+
+    if( ! poGRW->sDataTable.empty() )
+    {
+      strcpy( szDataTable, poGRW->sDataTable.c_str() );
+    }
+
+    nRasterId = poGRW->nRasterId;
+
+    if( ! poGRW->sWhere.empty() )
+    {
+      strcpy( szWhere, poGRW->sWhere.c_str() );
+    }
+
+    OWStatement* poStmt = poGRW->poConnection->CreateStatement(
+      "DECLARE\n"
+      "  SCM VARCHAR2(64) := 'xmlns=\"http://xmlns.oracle.com/spatial/georaster\"';\n"
+      "  GUL SDO_GEOMETRY := null;\n"
+      "  GUR SDO_GEOMETRY := null;\n"
+      "  GLL SDO_GEOMETRY := null;\n"
+      "  GLR SDO_GEOMETRY := null;\n"
+      "BEGIN\n"
+      "\n"
+      "    IF :datatable IS NOT NULL AND :rasterid  > 0 THEN\n"
+      "\n"
+      "      EXECUTE IMMEDIATE\n"
+      "        'SELECT OWNER, TABLE_NAME, COLUMN_NAME\n"
+      "         FROM   ALL_SDO_GEOR_SYSDATA\n"
+      "         WHERE  RDT_TABLE_NAME = UPPER(:1)\n"
+      "           AND  RASTER_ID = :2'\n"
+      "        INTO  :owner, :table, :column\n"
+      "        USING :datatable, :rasterid;\n"
+      "\n"
+      "      EXECUTE IMMEDIATE\n"
+      "        'SELECT T.'||:column||'.METADATA.getClobVal()\n"
+      "         FROM   '||:owner||'.'||:table||' T\n"
+      "         WHERE  T.'||:column||'.RASTERDATATABLE = UPPER(:1)\n"
+      "           AND  T.'||:column||'.RASTERID = :2'\n"
+      "        INTO  :metadata\n"
+      "        USING :datatable, :rasterid;\n"
+      "      :counter := 1;\n"
+      "\n"
+      "    ELSE\n"
+      "\n"
+      "      EXECUTE IMMEDIATE\n"
+      "        'SELECT T.'||:column||'.RASTERDATATABLE,\n"
+      "                T.'||:column||'.RASTERID,\n"
+      "                T.'||:column||'.METADATA.getClobVal()\n"
+      "         FROM  '||:owner||'.'||:table||' T\n"
+      "         WHERE '||:where\n"
+      "        INTO  :datatable, :rasterid, :metadata;\n"
+      "      :counter := 1;\n"
+      "\n"
+      "    END IF;\n"
+      "\n"
+      "  SELECT\n"
+      "    extractValue(XMLType(:metadata),"
+      "'/georasterMetadata/rasterInfo/dimensionSize[@type=\"ROW\"]/size', "
+      "SCM),\n"
+      "    extractValue(XMLType(:metadata),"
+      "'/georasterMetadata/rasterInfo/dimensionSize[@type=\"COLUMN\"]/size', "
+      "SCM),\n"
+      "    extractValue(XMLType(:metadata),"
+      "'/georasterMetadata/spatialReferenceInfo/SRID', "
+      "SCM),\n"
+      "    extractValue(XMLType(:metadata),"
+      "'/georasterMetadata/spatialReferenceInfo/modelCoordinateLocation', "
+      "SCM)\n"
+      "    INTO :sizey, :sizex, :srid, :mcl FROM DUAL;\n"
+      "\n"
+      "  EXECUTE IMMEDIATE\n"
+      "    'SELECT\n"
+      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
+      "SDO_NUMBER_ARRAY(0, 0)),\n"
+      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
+      "SDO_NUMBER_ARRAY(0, '||:sizex||')),\n"
+      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
+      "SDO_NUMBER_ARRAY('||:sizey||', 0)),\n"
+      "      SDO_GEOR.getModelCoordinate('||:column||', 0, "
+      "SDO_NUMBER_ARRAY('||:sizey||', '||:sizex||'))\n"
+      "     FROM  '||:owner||'.'||:table||' T\n"
+      "     WHERE T.'||:column||'.RASTERDATATABLE = UPPER(:1)\n"
+      "       AND T.'||:column||'.RASTERID = :2'\n"
+      "    INTO  GUL, GLL, GUR, GLR\n"
+      "    USING :datatable, :rasterid;\n"
+      "\n"
+      "  :ULx := GUL.sdo_point.x;\n"
+      "  :URx := GUR.sdo_point.x;\n"
+      "  :LRx := GLR.sdo_point.x;\n"
+      "  :ULy := GUL.sdo_point.y;\n"
+      "  :LLy := GLL.sdo_point.y;\n"
+      "  :LRy := GLR.sdo_point.y;\n"
+      "\n"
+      "  BEGIN\n"
+      "    EXECUTE IMMEDIATE\n"
+      "      'SELECT WKTEXT, AUTH_NAME\n"
+      "       FROM   MDSYS.CS_SRS\n"
+      "       WHERE  SRID = :1 AND WKTEXT IS NOT NULL'\n"
+      "      INTO   :wktext, :authority\n"
+      "      USING  :srid;\n"
+      "  EXCEPTION\n"
+      "    WHEN no_data_found THEN\n"
+      "      :wktext := '';\n"
+      "      :authority := '';\n"
+      "  END;\n"
+      "\n"
+      "  EXCEPTION\n"
+      "    WHEN no_data_found THEN :counter := 0;\n"
+      "    WHEN too_many_rows THEN :counter := 2;\n"
+      "END;" );
+
+    int nCounter = 0;
+
+    poStmt->BindName( ":datatable", szDataTable );
+    poStmt->BindName( ":rasterid", &nRasterId );
+    poStmt->BindName( ":owner", szOwner );
+    poStmt->BindName( ":table", szTable );
+    poStmt->BindName( ":column", szColumn );
+    poStmt->BindName( ":where", szWhere );
+    poStmt->BindName( ":counter", &nCounter );
+    poStmt->BindName( ":metadata", &phLocator );
+    poStmt->BindName( ":sizex", &nSizeX );
+    poStmt->BindName( ":sizey", &nSizeY );
+    poStmt->BindName( ":srid", &nSRID );
+    poStmt->BindName( ":mcl", szMLC );
+    poStmt->BindName( ":ULx", &dfULx );
+    poStmt->BindName( ":URx", &dfURx );
+    poStmt->BindName( ":LRx", &dfLRx );
+    poStmt->BindName( ":ULy", &dfULy );
+    poStmt->BindName( ":LLy", &dfLLy );
+    poStmt->BindName( ":LRy", &dfLRy );
+    poStmt->BindName( ":wktext", szWKText, sizeof(szWKText) );
+    poStmt->BindName( ":authority", szAuthority );
+
+    CPLErrorReset();
+
+    if( ! poStmt->Execute() )
+    {
+        delete poStmt;
+        delete poGRW;
+        return NULL;
+    }
+
+    if( nCounter < 1 )
+    {
+        delete poStmt;
+        delete poGRW;
+        return NULL;
+    }
+
+    poGRW->sSchema  = CPLSPrintf( "%s.", szOwner );
+    poGRW->sOwner   = szOwner;
+    poGRW->sTable   = szTable;
+    poGRW->sColumn  = szColumn;
+
+    if( nCounter == 1 )
+    {
+        poGRW->bUniqueFound = true;
+    }
+    else
+    {
+        poGRW->bUniqueFound = false;
+        
+        delete poStmt;
+        return poGRW;
+    }
+
+    poGRW->sWKText      = szWKText;
+    poGRW->sAuthority   = szAuthority;
+    poGRW->sDataTable   = szDataTable;
+    poGRW->nRasterId    = nRasterId;
+    poGRW->sWhere       = CPLSPrintf(
+        "T.%s.RASTERDATATABLE = UPPER('%s') AND T.%s.RASTERID = %d",
+        poGRW->sColumn.c_str(),
+        poGRW->sDataTable.c_str(),
+        poGRW->sColumn.c_str(),
+        poGRW->nRasterId );
+    
+    //  -------------------------------------------------------------------
+    //  Read Metadata XML in text
+    //  -------------------------------------------------------------------
+
+    char* pszXML = poStmt->ReadCLob( phLocator );
+
+    if( pszXML )
+    {
+        //  -----------------------------------------------------------
+        //  Get basic information from xml metadata
+        //  -----------------------------------------------------------
+
+        poGRW->phMetadata = CPLParseXMLString( pszXML );
+        poGRW->GetRasterInfo();
+    }
+    else
+    {
+        poGRW->sDataTable = "";
+        poGRW->nRasterId  = 0;
+    }
+
+    // --------------------------------------------------------------------
+    // Load Coefficients matrix
+    // --------------------------------------------------------------------
+
+    if ( EQUAL( szMLC, "UPPERLEFT" ) )
+    {
+      poGRW->eModelCoordLocation = MCL_UPPERLEFT;
+    }
+    else
+    {
+      poGRW->eModelCoordLocation = MCL_DEFAULT;
+    }
+
+    double dfRotation = 0.0;
+
+    if( ! CPLIsEqual( dfULy, dfLLy ) )
+    {
+        dfRotation = ( dfURx - dfULx ) / ( dfLLy - dfULy );
+    }
+
+    poGRW->dfXCoefficient[0] = ( dfLRx - dfULx ) / nSizeX;
+    poGRW->dfXCoefficient[1] = dfRotation;
+    poGRW->dfXCoefficient[2] = dfULx;
+    poGRW->dfYCoefficient[0] = -dfRotation;
+    poGRW->dfYCoefficient[1] = ( dfLRy - dfULy ) / nSizeY;
+    poGRW->dfYCoefficient[2] = dfULy;
+
+    if ( poGRW->eModelCoordLocation == MCL_CENTER )
+    {
+      poGRW->dfXCoefficient[2] -= poGRW->dfXCoefficient[0] / 2;
+      poGRW->dfYCoefficient[2] -= poGRW->dfYCoefficient[1] / 2;
+
+      CPLDebug("GEOR","eModelCoordLocation = MCL_CENTER");
+    }
+    else
+    {
+      CPLDebug("GEOR","eModelCoordLocation = MCL_UPPERLEFT");
+    }
+
+    //  -------------------------------------------------------------------
+    //  Apply ULTCoordinate
+    //  -------------------------------------------------------------------
+
+    poGRW->dfXCoefficient[2] += 
+                ( poGRW->anULTCoordinate[0] * poGRW->dfXCoefficient[0] );
+
+    poGRW->dfYCoefficient[2] += 
+                ( poGRW->anULTCoordinate[1] * poGRW->dfYCoefficient[1] );
+
+    //  -------------------------------------------------------------------
+    //  Clean up
+    //  -------------------------------------------------------------------
+
+    OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
+    CPLFree( pszXML );
+    delete poStmt;
+    
+    //  -------------------------------------------------------------------
+    //  Return a GeoRasterWrapper object
+    //  -------------------------------------------------------------------
+
+    return poGRW;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     Create()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::Create( char* pszDescription,
+                               char* pszInsert,
+                               bool bUpdate )
+{
+    CPLString sValues;
+    CPLString sFormat;
+
+    if( sTable.empty() ||
+        sColumn.empty() )
+    {
+        return false;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Parse RDT/RID from the current szValues
+    //  -------------------------------------------------------------------
+
+    char szRDT[OWNAME];
+    char szRID[OWCODE];
+
+    if( ! sDataTable.empty() )
+    {
+        strcpy( szRDT, CPLSPrintf( "'%s'", sDataTable.c_str() ) );
+    }
+    else
+    {
+        strcpy( szRDT, OWParseSDO_GEOR_INIT( sValues.c_str(), 1 ) );
+    }
+
+    if ( nRasterId > 0 )
+    {
+        strcpy( szRID, CPLSPrintf( "%d", nRasterId ) );
+    }
+    else
+    {
+        strcpy( szRID, OWParseSDO_GEOR_INIT( sValues.c_str(), 2 ) );
+
+        if ( EQUAL( szRID, "" ) )
+        {
+            strcpy( szRID, "NULL" );
+        }
+    }
+
+    //  -------------------------------------------------------------------
+    //  Description parameters
+    //  -------------------------------------------------------------------
+
+    char szDescription[OWTEXT];
+
+    if( bUpdate == false )
+    {
+
+        if ( pszDescription  )
+        {
+            strcpy( szDescription, pszDescription );
+        }
+        else
+        {
+            strcpy( szDescription, CPLSPrintf(
+                "(%s MDSYS.SDO_GEORASTER)", sColumn.c_str() ) );
+        }
+
+        //  ---------------------------------------------------------------
+        //  Insert parameters
+        //  ---------------------------------------------------------------
+
+        if( pszInsert )
+        {
+            sValues = pszInsert;
+
+            if( pszInsert[0] == '(' && sValues.ifind( "VALUES" ) == std::string::npos )
+            {
+                sValues = CPLSPrintf( "VALUES %s", pszInsert );
+            }
+        }
+        else
+        {
+            sValues = CPLSPrintf( "VALUES (SDO_GEOR.INIT(%s,%s))", szRDT, szRID );
+        }
+    }
+
+    //  -----------------------------------------------------------
+    //  Storage parameters
+    //  -----------------------------------------------------------
+
+    nColumnBlockSize = nColumnBlockSize == 0 ? DEFAULT_BLOCK_COLUMNS : nColumnBlockSize;
+    nRowBlockSize    = nRowBlockSize    == 0 ? DEFAULT_BLOCK_ROWS    : nRowBlockSize;
+    nBandBlockSize   = nBandBlockSize   == 0 ? 1 : nBandBlockSize;
+
+    //  -----------------------------------------------------------
+    //  Blocking storage paramters
+    //  -----------------------------------------------------------
+
+    CPLString sBlocking;
+
+    if( bBlocking == true )
+    {
+        if( bAutoBlocking == true )
+        {
+            int nBlockXSize = nColumnBlockSize;
+            int nBlockYSize = nRowBlockSize;
+            int nBlockBSize = nBandBlockSize;
+
+            OWStatement* poStmt;
+
+            poStmt = poConnection->CreateStatement(
+                "DECLARE\n"
+                "  dimensionSize    sdo_number_array;\n"
+                "  blockSize        sdo_number_array;\n"
+                "BEGIN\n"
+                "  dimensionSize := sdo_number_array(:1, :2, :3);\n"
+                "  blockSize     := sdo_number_array(:4, :5, :6);\n"
+                "  sdo_geor_utl.calcOptimizedBlockSize(dimensionSize,blockSize);\n"
+                "  :4 := blockSize(1);\n"
+                "  :5 := blockSize(2);\n"
+                "  :6 := blockSize(3);\n"
+                "END;" );
+
+            poStmt->Bind( &nRasterColumns );
+            poStmt->Bind( &nRasterRows );
+            poStmt->Bind( &nRasterBands );
+            poStmt->Bind( &nBlockXSize );
+            poStmt->Bind( &nBlockYSize );
+            poStmt->Bind( &nBlockBSize );
+
+            if( poStmt->Execute() )
+            {
+                nColumnBlockSize = nBlockXSize;
+                nRowBlockSize = nBlockYSize;
+                nBandBlockSize = nBlockBSize;
+            }
+
+            delete poStmt;
+        }
+
+        if( nRasterBands == 1 )
+        {
+            sBlocking = CPLSPrintf( 
+                "blockSize=(%d, %d)", 
+                nRowBlockSize, 
+                nColumnBlockSize );
+        }
+        else
+        {
+            sBlocking = CPLSPrintf( 
+                "blockSize=(%d, %d, %d)", 
+                nRowBlockSize, 
+                nColumnBlockSize, 
+                nBandBlockSize );
+        }
+    }
+    else
+    {
+        sBlocking = "blocking=FALSE";
+
+        nColumnBlockSize = nRasterColumns;
+        nRowBlockSize = nRasterRows;
+        nBandBlockSize = nRasterBands;
+    }
+
+    //  -----------------------------------------------------------
+    //  Complete format paramters
+    //  -----------------------------------------------------------
+
+    if( poConnection->GetVersion() > 10 )
+    {
+        if( nRasterBands == 1 )
+        {
+            sFormat = CPLSPrintf( 
+                "20001, '"
+                "dimSize=(%d,%d) ", 
+                nRasterRows, nRasterColumns );
+        }
+        else
+        {
+            sFormat = CPLSPrintf( 
+                "21001, '"
+                "dimSize=(%d,%d,%d) ", 
+                nRasterRows, nRasterColumns, nRasterBands );
+        }
+
+        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+        {
+            sFormat.append( CPLSPrintf( 
+                    "%s "
+                    "cellDepth=%s "
+                    "interleaving=%s "
+                    "compression=%s "
+                    "quality=%d'",
+                    sBlocking.c_str(),
+                    sCellDepth.c_str(),
+                    sInterleaving.c_str(),
+                    sCompressionType.c_str(),
+                    nCompressQuality) );
+        }
+        else
+        {
+            sFormat.append( CPLSPrintf( 
+                    "%s "
+                    "cellDepth=%s "
+                    "interleaving=%s "
+                    "compression=%s'",
+                    sBlocking.c_str(),
+                    sCellDepth.c_str(),
+                    sInterleaving.c_str(),
+                    sCompressionType.c_str() ) );
+        }
+    }
+    else
+    {
+        //  -------------------------------------------------------
+        //  For versions 10g or older
+        //  -------------------------------------------------------
+
+        sFormat = CPLSPrintf(
+            "%s "
+            "cellDepth=%s "
+            "interleaving=%s "
+            "pyramid=FALSE "
+            "compression=NONE",
+            sBlocking.c_str(),
+            sCellDepth.c_str(),
+            sInterleaving.c_str() );
+    }
+
+    nTotalColumnBlocks = (int)
+        ( ( nRasterColumns + nColumnBlockSize - 1 ) / nColumnBlockSize );
+
+    nTotalRowBlocks = (int)
+        ( ( nRasterRows + nRowBlockSize - 1 ) / nRowBlockSize );
+
+    nTotalBandBlocks = (int)
+        ( ( nRasterBands + nBandBlockSize - 1) / nBandBlockSize );
+
+    //  -------------------------------------------------------------------
+    //  Create Georaster Table if needed
+    //  -------------------------------------------------------------------
+
+    OWStatement* poStmt;
+
+    if( ! bUpdate )
+    {
+        poStmt = poConnection->CreateStatement( CPLSPrintf(
+            "DECLARE\n"
+            "  TAB VARCHAR2(68)  := UPPER('%s');\n"
+            "  COL VARCHAR2(68)  := UPPER('%s');\n"
+            "  OWN VARCHAR2(68)  := UPPER('%s');\n"
+            "  CNT NUMBER        := 0;\n"
+            "BEGIN\n"
+            "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_TABLES\n"
+            "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
+            "      INTO CNT USING TAB, OWN;\n"
+            "\n"
+            "  IF CNT = 0 THEN\n"
+            "    EXECUTE IMMEDIATE 'CREATE TABLE %s%s %s';\n"
+            "    SDO_GEOR_UTL.createDMLTrigger( TAB,  COL );\n"
+            "  END IF;\n"
+            "END;",
+                sTable.c_str(),
+                sColumn.c_str(),
+                sOwner.c_str(),
+                sSchema.c_str(),
+                sTable.c_str(),
+                szDescription ) );
+
+        if( ! poStmt->Execute() )
+        {
+            delete ( poStmt );
+            return false;
+        }
+
+        delete poStmt;
+    }
+
+    //  -----------------------------------------------------------
+    //  Prepare UPDATE or INSERT comand
+    //  -----------------------------------------------------------
+
+    CPLString sCommand;
+
+    if( bUpdate )
+    {
+        sCommand = CPLSPrintf(
+            "SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;",
+            sColumn.c_str(),
+            sSchema.c_str(),
+            sTable.c_str(),
+            sWhere.c_str() );
+    }
+    else
+    {
+        sCommand = CPLSPrintf(
+            "INSERT INTO %s%s %s RETURNING %s INTO GR1;",
+            sSchema.c_str(),
+            sTable.c_str(),
+            sValues.c_str(),
+            sColumn.c_str() );
+    }
+
+    //  -----------------------------------------------------------
+    //  Create RTD if needed and insert/update GeoRaster
+    //  -----------------------------------------------------------
+
+    char szBindRDT[OWNAME];
+    int  nBindRID = 0;
+    szBindRDT[0] = '\0';
+
+    CPLString sObjectTable;
+    CPLString sSecureFile;
+
+    // For version > 11 create RDT as relational table by default,
+    // if it is not specified by create-option OBJECTTABLE=TRUE
+
+    if( poConnection->GetVersion() <= 11 || bCreateObjectTable )
+    {
+        sObjectTable = "OF MDSYS.SDO_RASTER\n      (";
+    }
+    else
+    {
+        sObjectTable = CPLSPrintf("(\n"
+                       "      RASTERID           NUMBER,\n"
+                       "      PYRAMIDLEVEL       NUMBER,\n"
+                       "      BANDBLOCKNUMBER    NUMBER,\n"
+                       "      ROWBLOCKNUMBER     NUMBER,\n"
+                       "      COLUMNBLOCKNUMBER  NUMBER,\n"
+                       "      BLOCKMBR           SDO_GEOMETRY,\n"
+                       "      RASTERBLOCK        BLOB,\n"
+                       "      CONSTRAINT '||:rdt||'_RDT_PK ");
+    }
+
+    // For version >= 11 create RDT rasterBlock as securefile
+
+    if( poConnection->GetVersion() >= 11 )
+    {
+        sSecureFile = "SECUREFILE(CACHE)";
+    }
+    else
+    {
+        sSecureFile = "(NOCACHE NOLOGGING)";
+    }
+
+    if( poConnection->GetVersion() > 10 )
+    {
+        poStmt = poConnection->CreateStatement( CPLSPrintf(
+            "DECLARE\n"
+            "  TAB  VARCHAR2(68)    := UPPER('%s');\n"
+            "  COL  VARCHAR2(68)    := UPPER('%s');\n"
+            "  OWN  VARCHAR2(68)    := UPPER('%s');\n"
+            "  CNT  NUMBER          := 0;\n"
+            "  GR1  SDO_GEORASTER   := NULL;\n"
+            "BEGIN\n"
+            "\n"
+            "  %s\n"
+            "\n"
+            "  GR1.spatialExtent := NULL;\n"
+            "\n"
+            "  SELECT GR1.RASTERDATATABLE INTO :rdt FROM DUAL;\n"
+            "  SELECT GR1.RASTERID        INTO :rid FROM DUAL;\n"
+            "\n"
+            "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_OBJECT_TABLES\n"
+            "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
+            "      INTO CNT USING :rdt, OWN;\n"
+            "\n"
+            "  IF CNT = 0 THEN\n"
+            "    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_TABLES\n"
+            "      WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
+            "        INTO CNT USING :rdt, OWN;\n"
+            "  END IF;\n"
+            "\n"
+            "  IF CNT = 0 THEN\n"
+            "    EXECUTE IMMEDIATE 'CREATE TABLE %s'||:rdt||' %s"
+            "PRIMARY KEY (RASTERID, PYRAMIDLEVEL,\n"
+            "      BANDBLOCKNUMBER, ROWBLOCKNUMBER, COLUMNBLOCKNUMBER))\n"
+            "      LOB(RASTERBLOCK) STORE AS %s';\n"
+            "  END IF;\n"
+            "\n"
+            "  SDO_GEOR.createTemplate(GR1, %s, null, 'TRUE');\n"
+            "\n"
+            "  UPDATE %s%s T SET %s = GR1 WHERE\n"
+            "    T.%s.RasterDataTable = :rdt AND\n"
+            "    T.%s.RasterId = :rid;\n"
+            "\n"
+            "  EXECUTE IMMEDIATE\n"
+            "    'SELECT T.%s.METADATA.getClobVal()\n"
+            "     FROM   %s%s T\n"
+            "     WHERE  T.%s.RASTERDATATABLE = UPPER(:1)\n"
+            "       AND  T.%s.RASTERID = :2'\n"
+            "      INTO  :metadata\n"
+            "     USING  :rdt, :rid;\n"
+            "\n"
+            "  COMMIT;\n"
+            "\n"
+            "END;\n",
+                sTable.c_str(),
+                sColumn.c_str(),
+                sOwner.c_str(),
+                sCommand.c_str(),
+                sSchema.c_str(),
+                sObjectTable.c_str(),
+                sSecureFile.c_str(),
+                sFormat.c_str(),
+                sSchema.c_str(),
+                sTable.c_str(),
+                sColumn.c_str(),
+                sColumn.c_str(),
+                sColumn.c_str(),
+                sColumn.c_str(),
+                sSchema.c_str(),
+                sTable.c_str(),
+                sColumn.c_str(),
+                sColumn.c_str() ) );
+
+        OCILobLocator* phLocator = NULL;
+
+        poStmt->BindName( ":metadata", &phLocator );
+        poStmt->BindName( ":rdt", szBindRDT );
+        poStmt->BindName( ":rid", &nBindRID );
+
+        CPLErrorReset();
+
+        if( ! poStmt->Execute() )
+        {
+            delete poStmt;
+            return false;
+        }
+
+        sDataTable = szBindRDT;
+        nRasterId  = nBindRID;
+
+        OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
+
+        
+        delete poStmt;
+
+        return true;
+    }
+
+    //  -----------------------------------------------------------
+    //  Procedure for Server version older than 11
+    //  -----------------------------------------------------------
+
+    char szCreateBlank[OWTEXT];
+
+    if( nRasterBands == 1 )
+    {
+        strcpy( szCreateBlank, CPLSPrintf( "SDO_GEOR.createBlank(20001, "
+            "SDO_NUMBER_ARRAY(0, 0), "
+            "SDO_NUMBER_ARRAY(%d, %d), 0, :rdt, :rid)",
+            nRasterRows, nRasterColumns ) );
+    }
+    else
+    {
+        strcpy( szCreateBlank, CPLSPrintf( "SDO_GEOR.createBlank(21001, "
+            "SDO_NUMBER_ARRAY(0, 0, 0), "
+            "SDO_NUMBER_ARRAY(%d, %d, %d), 0, :rdt, :rid)",
+            nRasterRows, nRasterColumns, nRasterBands ) );
+    }
+
+    poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "DECLARE\n"
+        "  W    NUMBER          := :1;\n"
+        "  H    NUMBER          := :2;\n"
+        "  BB   NUMBER          := :3;\n"
+        "  RB   NUMBER          := :4;\n"
+        "  CB   NUMBER          := :5;\n"
+        "  OWN  VARCHAR2(68)    := UPPER('%s');\n"
+        "  X    NUMBER          := 0;\n"
+        "  Y    NUMBER          := 0;\n"
+        "  CNT  NUMBER          := 0;\n"
+        "  GR1  SDO_GEORASTER   := NULL;\n"
+        "  GR2  SDO_GEORASTER   := NULL;\n"
+        "  STM  VARCHAR2(1024)  := '';\n"
+        "BEGIN\n"
+        "\n"
+        "  %s\n"
+        "\n"
+        "  SELECT GR1.RASTERDATATABLE INTO :rdt FROM DUAL;\n"
+        "  SELECT GR1.RASTERID        INTO :rid FROM DUAL;\n"
+        "\n"
+        "  SELECT %s INTO GR2 FROM %s%s T WHERE"
+        " T.%s.RasterDataTable = :rdt AND"
+        " T.%s.RasterId = :rid FOR UPDATE;\n"
+        "\n"
+        "  GR1 := %s;\n"
+        "\n"
+        "  SDO_GEOR.changeFormatCopy(GR1, '%s', GR2);\n"
+        "\n"
+        "  UPDATE %s%s T SET %s = GR2 WHERE"
+        " T.%s.RasterDataTable = :rdt AND"
+        " T.%s.RasterId = :rid;\n"
+        "\n"
+        "  EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ALL_OBJECT_TABLES\n"
+        "    WHERE TABLE_NAME = :1 AND OWNER = UPPER(:2)'\n"
+        "      INTO CNT USING :rdt, OWN;\n"
+        "\n"
+        "  IF CNT = 0 THEN\n"
+        "    EXECUTE IMMEDIATE 'CREATE TABLE %s'||:rdt||' OF MDSYS.SDO_RASTER\n"
+        "      (PRIMARY KEY (RASTERID, PYRAMIDLEVEL, BANDBLOCKNUMBER,\n"
+        "      ROWBLOCKNUMBER, COLUMNBLOCKNUMBER))\n"
+        "      LOB(RASTERBLOCK) STORE AS (NOCACHE NOLOGGING)';\n"
+        "  ELSE\n"
+        "    EXECUTE IMMEDIATE 'DELETE FROM %s'||:rdt||' WHERE RASTERID ='||:rid||' ';\n"
+        "  END IF;\n"
+        "\n"
+        "  STM := 'INSERT INTO %s'||:rdt||' VALUES (:1,0,:2-1,:3-1,:4-1,\n"
+        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
+        "    SDO_ORDINATE_ARRAY(:5,:6,:7-1,:8-1)), EMPTY_BLOB() )';\n\n"
+        "  FOR b IN 1..BB LOOP\n"
+        "    Y := 0;\n"
+        "    FOR r IN 1..RB LOOP\n"
+        "      X := 0;\n"
+        "      FOR c IN 1..CB LOOP\n"
+        "        EXECUTE IMMEDIATE STM USING :rid, b, r, c, Y, X, (Y+H), (X+W);\n"
+        "        X := X + W;\n"
+        "      END LOOP;\n"
+        "      Y := Y + H;\n"
+        "    END LOOP;\n"
+        "  END LOOP;\n"
+        "\n"
+        "  SDO_GEOR.georeference(GR1, %d, %d,"
+        " SDO_NUMBER_ARRAY(1.0, 0.0, 0.0),"
+        " SDO_NUMBER_ARRAY(0.0, 1.0, 0.0));\n"
+        "\n"
+        "  UPDATE %s%s T SET %s = GR1 WHERE"
+        " T.%s.RasterDataTable = :rdt AND"
+        " T.%s.RasterId = :rid;\n"
+        "\n"
+        "  COMMIT;\n"
+        "\n"
+        "END;",
+            sOwner.c_str(),
+            sCommand.c_str(),
+            sColumn.c_str(), sSchema.c_str(), sTable.c_str(),
+            sColumn.c_str(), sColumn.c_str(),
+            szCreateBlank,
+            sFormat.c_str(), 
+            sSchema.c_str(), sTable.c_str(),
+            sColumn.c_str(), sColumn.c_str(), sColumn.c_str(),
+            sSchema.c_str(), sSchema.c_str(), sSchema.c_str(),
+            DEFAULT_CRS, MCL_DEFAULT,
+            sSchema.c_str(), sTable.c_str(),
+            sColumn.c_str(), sColumn.c_str(), sColumn.c_str() ) );
+
+    poStmt->Bind( &nColumnBlockSize );
+    poStmt->Bind( &nRowBlockSize );
+    poStmt->Bind( &nTotalBandBlocks );
+    poStmt->Bind( &nTotalRowBlocks );
+    poStmt->Bind( &nTotalColumnBlocks );
+    
+    poStmt->BindName( ":rdt", szBindRDT );
+    poStmt->BindName( ":rid", &nBindRID );
+
+    if( ! poStmt->Execute() )
+    {
+        delete poStmt;
+        return false;
+    }
+
+    sDataTable = szBindRDT;
+    nRasterId  = nBindRID;
+
+    delete poStmt;
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                         PrepareToOverwrite()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::PrepareToOverwrite( void )
+{
+    nTotalColumnBlocks  = 0;
+    nTotalRowBlocks     = 0;
+    nTotalBandBlocks    = 0;
+    if( sscanf( sCellDepth.c_str(), "%dBIT", &nCellSizeBits ) )
+    {
+        nGDALCellBytes   = GDALGetDataTypeSize(
+                          OWGetDataType( sCellDepth.c_str() ) ) / 8;
+    }
+    else
+    {
+        nGDALCellBytes   = 1;
+    }
+    dfXCoefficient[0]   = 1.0;
+    dfXCoefficient[1]   = 0.0;
+    dfXCoefficient[2]   = 0.0;
+    dfYCoefficient[0]   = 0.0;
+    dfYCoefficient[1]   = 1.0;
+    dfYCoefficient[2]   = 0.0;
+    sCompressionType    = "NONE";
+    nCompressQuality    = 75;
+    bGenPyramid         = false;
+    nPyramidLevels      = 0;
+    sPyramidResampling  = "NN";
+    bIsReferenced       = false;
+    nCacheBlockId       = -1;
+    nCurrentLevel       = -1;
+    pahLevels           = NULL;
+    nLevelOffset        = 0L;
+    sInterleaving       = "BSQ";
+    bUpdate             = false;
+    bInitializeIO       = false;
+    bFlushMetadata      = false;
+    nSRID               = 0;
+    nExtentSRID         = 0;
+    bGenSpatialIndex    = false;
+    bCreateObjectTable  = false;
+    nPyramidMaxLevel    = 0;
+    nBlockCount         = 0L;
+    sDInfo.global_state = 0;
+    sCInfo.global_state = 0;
+    bHasBitmapMask      = false;
+    bWriteOnly          = false;
+    bBlocking           = true;
+    bAutoBlocking       = false;
+    eModelCoordLocation = MCL_DEFAULT;
+    bFlushBlock         = false;
+    nFlushBlockSize     = 0L;
+    phRPC               = NULL;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     Delete()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::Delete( void )
+{
+    if( ! bUniqueFound )
+    {
+        return false;
+    }
+    
+    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
+      "UPDATE %s%s T SET %s = NULL WHERE %s\n",
+            sSchema.c_str(),
+            sTable.c_str(),
+            sColumn.c_str(),
+            sWhere.c_str() ) );
+
+    bool bReturn = poStmt->Execute();
+
+    delete poStmt;
+
+    return bReturn;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            SetGeoReference()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::SetGeoReference( int nSRIDIn )
+{
+    nSRID = nSRIDIn;
+
+    bIsReferenced = true;
+
+    bFlushMetadata = true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              GetRasterInfo()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::GetRasterInfo( void )
+{
+    //  -------------------------------------------------------------------
+    //  Get dimensions
+    //  -------------------------------------------------------------------
+
+    int nCount  = 0;
+
+    CPLXMLNode* phDimSize   = NULL;
+    const char* pszType     = NULL;
+
+    nCount      = atoi( CPLGetXMLValue( phMetadata,
+                  "rasterInfo.totalDimensions", "0" ) );
+    phDimSize   = CPLGetXMLNode( phMetadata, "rasterInfo.dimensionSize" );
+
+    int i = 0;
+
+    for( i = 0; i < nCount; i++ )
+    {
+        pszType = CPLGetXMLValue( phDimSize, "type", "0" );
+
+        if( EQUAL( pszType, "ROW" ) )
+        {
+            nRasterRows = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
+        }
+
+        if( EQUAL( pszType, "COLUMN" ) )
+        {
+            nRasterColumns = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
+        }
+
+        if( EQUAL( pszType, "BAND" ) )
+        {
+            nRasterBands = atoi( CPLGetXMLValue( phDimSize, "size", "0" ) );
+        }
+
+        phDimSize = phDimSize->psNext;
+    }
+
+    if( nRasterBands == 0 )
+    {
+        nRasterBands = 1;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Load NoData Values 
+    //  -------------------------------------------------------------------
+
+    LoadNoDataValues();
+
+    //  -------------------------------------------------------------------
+    //  Get ULTCoordinate values
+    //  -------------------------------------------------------------------
+
+    anULTCoordinate[0] = atoi(CPLGetXMLValue( 
+            phMetadata, "rasterInfo.ULTCoordinate.column", "0"));
+
+    anULTCoordinate[1] = atoi(CPLGetXMLValue( 
+            phMetadata, "rasterInfo.ULTCoordinate.row", "0"));
+
+    anULTCoordinate[2] = atoi(CPLGetXMLValue( 
+            phMetadata, "rasterInfo.ULTCoordinate.band", "0"));
+
+    //  -------------------------------------------------------------------
+    //  Get Interleaving mode
+    //  -------------------------------------------------------------------
+
+    sInterleaving = CPLGetXMLValue( phMetadata,
+        "rasterInfo.interleaving", "BSQ" );
+
+    //  -------------------------------------------------------------------
+    //  Get blocking
+    //  -------------------------------------------------------------------
+
+    nRowBlockSize       = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.rowBlockSize",
+                            CPLSPrintf( "%d", nRasterRows ) ) );
+
+    nColumnBlockSize    = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.columnBlockSize",
+                            CPLSPrintf( "%d", nRasterColumns ) ) );
+
+    nBandBlockSize      = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.bandBlockSize",
+                            CPLSPrintf( "%d", nRasterBands ) ) );
+
+    nTotalColumnBlocks  = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.totalColumnBlocks","1") );
+
+    nTotalRowBlocks     = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.totalRowBlocks", "1" ) );
+
+    nTotalBandBlocks    = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.blocking.totalBandBlocks", "1" ) );
+
+    if( nBandBlockSize == -1 )
+    {
+       nBandBlockSize = nRasterBands;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Get data type
+    //  -------------------------------------------------------------------
+
+    sCellDepth = CPLGetXMLValue( phMetadata, "rasterInfo.cellDepth", "8BIT_U" );
+
+    if( sscanf( sCellDepth.c_str(), "%dBIT", &nCellSizeBits ) )
+    {
+        nGDALCellBytes   = GDALGetDataTypeSize(
+            OWGetDataType( sCellDepth.c_str() ) ) / 8;
+    }
+    else
+    {
+        nGDALCellBytes   = 1;
+    }
+
+    sCompressionType  = CPLGetXMLValue( phMetadata,
+        "rasterInfo.compression.type", "NONE" );
+
+    if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+    {
+        nCompressQuality = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.compression.quality", "75" ) );
+    }
+
+    if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+    {
+        sInterleaving = "BIP";
+    }
+
+    //  -------------------------------------------------------------------
+    //  Get default RGB Bands
+    //  -------------------------------------------------------------------
+
+    iDefaultRedBand     = atoi( CPLGetXMLValue( phMetadata,
+                            "objectInfo.defaultRed", "-1" ) );
+
+    iDefaultGreenBand   = atoi( CPLGetXMLValue( phMetadata,
+                            "objectInfo.defaultGreen", "-1" ) );
+
+    iDefaultBlueBand    = atoi( CPLGetXMLValue( phMetadata,
+                            "objectInfo.defaultBlue", "-1" ) );
+
+    //  -------------------------------------------------------------------
+    //  Get Pyramid details
+    //  -------------------------------------------------------------------
+
+    char szPyramidType[OWCODE];
+
+    strcpy( szPyramidType, CPLGetXMLValue( phMetadata,
+                            "rasterInfo.pyramid.type", "None" ) );
+
+    if( EQUAL( szPyramidType, "DECREASE" ) )
+    {
+        nPyramidMaxLevel = atoi( CPLGetXMLValue( phMetadata,
+                            "rasterInfo.pyramid.maxLevel", "0" ) );
+    }
+
+    //  -------------------------------------------------------------------
+    //  Check for RPCs
+    //  -------------------------------------------------------------------
+
+    const char* pszModelType = CPLGetXMLValue( phMetadata,
+                               "spatialReferenceInfo.modelType", "None" );
+
+    if( EQUAL( pszModelType, "FunctionalFitting" ) )
+    {
+        GetRPC();
+    }
+
+    //  -------------------------------------------------------------------
+    //  Prepare to get Extents
+    //  -------------------------------------------------------------------
+
+    bIsReferenced       = EQUAL( "TRUE", CPLGetXMLValue( phMetadata,
+                            "spatialReferenceInfo.isReferenced", "FALSE" ) );
+
+    nSRID               = atoi( CPLGetXMLValue( phMetadata,
+                            "spatialReferenceInfo.SRID", "0" ) );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              GetStatistics()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::GetStatistics( int nBand,
+                                      char* pszMin,
+                                      char* pszMax,
+                                      char* pszMean,
+                                      char* pszMedian,
+                                      char* pszMode,
+                                      char* pszStdDev,
+                                      char* pszSampling )
+{
+    int n = 1;
+
+    CPLXMLNode *phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
+    {
+        if( n == nBand && CPLGetXMLNode( phSubLayer, "statisticDataset" ) )
+        {
+            strncpy( pszSampling, CPLGetXMLValue( phSubLayer, 
+                "statisticDataset.samplingFactor",  "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszMin, CPLGetXMLValue( phSubLayer, 
+                "statisticDataset.MIN",  "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszMax, CPLGetXMLValue( phSubLayer,
+                "statisticDataset.MAX",  "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszMean, CPLGetXMLValue( phSubLayer,
+                "statisticDataset.MEAN", "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszMedian, CPLGetXMLValue( phSubLayer,
+                "statisticDataset.MEDIAN", "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszMode, CPLGetXMLValue( phSubLayer,
+                "statisticDataset.MODEVALUE", "0.0" ), MAX_DOUBLE_STR_REP );
+            strncpy( pszStdDev, CPLGetXMLValue( phSubLayer,
+                "statisticDataset.STD",  "0.0" ), MAX_DOUBLE_STR_REP );
+            return true;
+        }
+    }
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              SetStatistics()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::SetStatistics( int nBand,
+                                      const char* pszMin,
+                                      const char* pszMax,
+                                      const char* pszMean,
+                                      const char* pszMedian,
+                                      const char* pszMode,
+                                      const char* pszStdDev,
+                                      const char* pszSampling )
+{
+    InitializeLayersNode();
+
+    bFlushMetadata = true;
+
+    int n = 1;
+
+    CPLXMLNode* phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
+    {
+        if( n != nBand )
+        {
+            continue;
+        }
+
+        CPLXMLNode* psSDaset = CPLGetXMLNode( phSubLayer, "statisticDataset" );
+
+        if( psSDaset != NULL )
+        {
+            CPLRemoveXMLChild( phSubLayer, psSDaset );
+            CPLDestroyXMLNode( psSDaset );
+        }
+
+        psSDaset = CPLCreateXMLNode(phSubLayer,CXT_Element,"statisticDataset");
+
+        CPLCreateXMLElementAndValue(psSDaset,"samplingFactor", pszSampling );
+        CPLCreateXMLElementAndValue(psSDaset,"MIN", pszMin );
+        CPLCreateXMLElementAndValue(psSDaset,"MAX", pszMax );
+        CPLCreateXMLElementAndValue(psSDaset,"MEAN", pszMean );
+        CPLCreateXMLElementAndValue(psSDaset,"MEDIAN", pszMedian );
+        CPLCreateXMLElementAndValue(psSDaset,"MODEVALUE", pszMode );
+        CPLCreateXMLElementAndValue(psSDaset,"STD", pszStdDev );
+
+        return true;
+    }
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              HasColorTable()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::HasColorMap( int nBand )
+{
+    CPLXMLNode *psLayers;
+
+    int n = 1;
+
+    psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( ; psLayers; psLayers = psLayers->psNext, n++ )
+    {
+        if( n == nBand )
+        {
+            if( CPLGetXMLNode( psLayers, "colorMap.colors" ) )
+            {
+                return true;
+            }
+        }
+    }
+
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                        InitializeLayersNode()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::InitializeLayersNode()
+{
+    CPLXMLNode *pslInfo  = CPLGetXMLNode( phMetadata, "layerInfo" );
+
+    int n = 1;
+
+    for( n = 0 ; n < nRasterBands; n++ )
+    {
+        CPLXMLNode *psSLayer = CPLGetXMLNode( pslInfo,    "subLayer" );
+
+        if( psSLayer == NULL )
+        {
+            psSLayer = CPLCreateXMLNode( pslInfo, CXT_Element, "subLayer" );
+
+            CPLCreateXMLElementAndValue( psSLayer, "layerNumber",
+                CPLSPrintf( "%d", n + 1 ) );
+
+            CPLCreateXMLElementAndValue( psSLayer, "layerDimensionOrdinate",
+                CPLSPrintf( "%d", n ) );
+
+            CPLCreateXMLElementAndValue( psSLayer, "layerID", "" );
+        }
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              GetColorTable()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::GetColorMap( int nBand, GDALColorTable* poCT )
+{
+    GDALColorEntry oEntry;
+
+    CPLXMLNode* psLayers;
+
+    int n = 1;
+
+    psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( ; psLayers; psLayers = psLayers->psNext, n++ )
+    {
+        if( n != nBand )
+        {
+            continue;
+        }
+
+        CPLXMLNode* psColors = CPLGetXMLNode( psLayers, "colorMap.colors.cell" );
+
+        int iColor = 0;
+
+        for(  ; psColors; psColors = psColors->psNext )
+        {
+            iColor    = (short) atoi( CPLGetXMLValue( psColors, "value","0"));
+            oEntry.c1 = (short) atoi( CPLGetXMLValue( psColors, "red",  "0"));
+            oEntry.c2 = (short) atoi( CPLGetXMLValue( psColors, "green","0"));
+            oEntry.c3 = (short) atoi( CPLGetXMLValue( psColors, "blue", "0"));
+            oEntry.c4 = (short) atoi( CPLGetXMLValue( psColors, "alpha","0"));
+            poCT->SetColorEntry( iColor, &oEntry );
+        }
+        break;
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              SetColorTable()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::SetColorMap( int nBand, GDALColorTable* poCT )
+{
+    InitializeLayersNode();
+
+    bFlushMetadata = true;
+
+    GDALColorEntry oEntry;
+
+    int n = 1;
+
+    CPLXMLNode* phSubLayer = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( n = 1 ; phSubLayer ; phSubLayer = phSubLayer->psNext, n++ )
+    {
+        if( n != nBand )
+        {
+            continue;
+        }
+
+        CPLXMLNode* psCMap = CPLGetXMLNode( phSubLayer, "colorMap" );
+
+        if( psCMap != NULL )
+        {
+            CPLRemoveXMLChild( phSubLayer, psCMap );
+            CPLDestroyXMLNode( psCMap );
+        }
+
+        psCMap = CPLCreateXMLNode( phSubLayer, CXT_Element, "colorMap" );
+
+        CPLXMLNode* psColor = CPLCreateXMLNode( psCMap, CXT_Element, "colors" );
+
+        // ------------------------------------------------
+        // Clean existing colors entry (RGB color table)
+        // ------------------------------------------------
+
+        if( psColor != NULL )
+        {
+            CPLRemoveXMLChild( psCMap, psColor );
+            CPLDestroyXMLNode( psColor );
+        }
+
+        psColor = CPLCreateXMLNode( psCMap, CXT_Element, "colors" );
+
+        int iColor = 0;
+
+        int nCount = 0;
+
+        switch( nCellSizeBits )
+        {
+            case 1 :
+                nCount = 2;
+                break;
+            case 2 :
+                nCount = 4;
+                break;
+            case 4:
+                nCount = 16;
+                break;
+            default:
+                nCount = poCT->GetColorEntryCount();
+        }
+
+
+        for( iColor = 0; iColor < nCount; iColor++ )
+        {
+            poCT->GetColorEntryAsRGB( iColor, &oEntry );
+
+            CPLXMLNode* psCell = CPLCreateXMLNode( psColor, CXT_Element, "cell" );
+
+            CPLSetXMLValue( psCell, "#value", CPLSPrintf("%d", iColor) );
+            CPLSetXMLValue( psCell, "#blue",  CPLSPrintf("%d", oEntry.c3) );
+            CPLSetXMLValue( psCell, "#red",   CPLSPrintf("%d", oEntry.c1) );
+            CPLSetXMLValue( psCell, "#green", CPLSPrintf("%d", oEntry.c2) );
+            CPLSetXMLValue( psCell, "#alpha", CPLSPrintf("%d", oEntry.c4) );
+        }
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                               InitializeIO()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::InitializeIO( void )
+{
+    bInitializeIO = true;
+    
+    // --------------------------------------------------------------------
+    // Initialize Pyramid level details
+    // --------------------------------------------------------------------
+
+    pahLevels = (hLevelDetails*) CPLCalloc( sizeof(hLevelDetails),
+                                            nPyramidMaxLevel + 1 );
+
+    // --------------------------------------------------------------------
+    // Calculate number and size of the blocks in level zero
+    // --------------------------------------------------------------------
+
+    nBlockCount = (unsigned long) ( nTotalColumnBlocks * nTotalRowBlocks * nTotalBandBlocks );
+    nBlockBytes = (unsigned long) ( nColumnBlockSize * nRowBlockSize * nBandBlockSize *
+                                    nCellSizeBits / 8L );
+    nGDALBlockBytes = (unsigned long) ( nColumnBlockSize * nRowBlockSize * nGDALCellBytes );
+
+    pahLevels[0].nColumnBlockSize   = nColumnBlockSize;
+    pahLevels[0].nRowBlockSize      = nRowBlockSize;
+    pahLevels[0].nTotalColumnBlocks = nTotalColumnBlocks;
+    pahLevels[0].nTotalRowBlocks    = nTotalRowBlocks;
+    pahLevels[0].nBlockCount        = nBlockCount;
+    pahLevels[0].nBlockBytes        = nBlockBytes;
+    pahLevels[0].nGDALBlockBytes    = nGDALBlockBytes;
+    pahLevels[0].nOffset            = 0L;
+
+    // --------------------------------------------------------------------
+    // Calculate number and size of the blocks in Pyramid levels
+    // --------------------------------------------------------------------
+
+    int iLevel = 1;
+    
+    for( iLevel = 1; iLevel <= nPyramidMaxLevel; iLevel++ )
+    {
+        int nRBS = nRowBlockSize;
+        int nCBS = nColumnBlockSize;
+        int nTCB = nTotalColumnBlocks;
+        int nTRB = nTotalRowBlocks;
+
+        // --------------------------------------------------------------------
+        // Calculate the actual size of a lower resolution block
+        // --------------------------------------------------------------------
+
+        double dfScale = pow( (double) 2.0, (double) iLevel );
+
+        int nXSize  = (int) floor( (double) nRasterColumns / dfScale );
+        int nYSize  = (int) floor( (double) nRasterRows / dfScale );
+        int nXBlock = (int) floor( (double) nCBS / 2.0 );
+        int nYBlock = (int) floor( (double) nRBS / 2.0 );
+
+        if( nXSize <= nXBlock && nYSize <= nYBlock )
+        {
+            // ------------------------------------------------------------
+            // Calculate the size of the singe small blocks
+            // ------------------------------------------------------------
+
+            nCBS = nXSize;
+            nRBS = nYSize;
+            nTCB = 1;
+            nTRB = 1;
+        }
+        else
+        {
+            // ------------------------------------------------------------
+            // Recalculate blocks quantity
+            // ------------------------------------------------------------
+
+            nTCB = (int) ceil( (double) nXSize / nCBS );
+            nTRB = (int) ceil( (double) nYSize / nRBS );
+        }
+
+        // --------------------------------------------------------------------
+        // Save level datails
+        // --------------------------------------------------------------------
+
+        pahLevels[iLevel].nColumnBlockSize   = nCBS;
+        pahLevels[iLevel].nRowBlockSize      = nRBS;
+        pahLevels[iLevel].nTotalColumnBlocks = nTCB;
+        pahLevels[iLevel].nTotalRowBlocks    = nTRB;
+        pahLevels[iLevel].nBlockCount        = (unsigned long ) ( nTCB * nTRB * nTotalBandBlocks );
+        pahLevels[iLevel].nBlockBytes        = (unsigned long ) ( nCBS * nRBS * nBandBlockSize *
+                                                                  nCellSizeBits / 8L );
+        pahLevels[iLevel].nGDALBlockBytes    = (unsigned long ) ( nCBS * nRBS * nGDALCellBytes );
+        pahLevels[iLevel].nOffset            = 0L;
+    }
+    
+    // --------------------------------------------------------------------
+    // Calculate total row count and level's offsets
+    // --------------------------------------------------------------------
+
+    nBlockCount = 0L;
+    
+    for( iLevel = 0; iLevel <= nPyramidMaxLevel; iLevel++ )
+    {
+        pahLevels[iLevel].nOffset = nBlockCount;
+        nBlockCount += pahLevels[iLevel].nBlockCount;
+    }
+
+    // --------------------------------------------------------------------
+    // Allocate buffer for one raster block
+    // --------------------------------------------------------------------
+
+    long nMaxBufferSize = MAX( nBlockBytes, nGDALBlockBytes );
+
+    pabyBlockBuf = (GByte*) VSIMalloc( sizeof(GByte) * nMaxBufferSize );
+
+    if ( pabyBlockBuf == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory, 
+            "InitializeIO - Block Buffer error\n"
+            "Cannot allocate memory buffer of (%ld) bytes "
+            "Consider the use of *smaller* block size",
+            nMaxBufferSize );
+        return false;
+    }
+
+    // --------------------------------------------------------------------
+    // Allocate buffer for one compressed raster block
+    // --------------------------------------------------------------------
+
+    if( bUpdate && ! EQUAL( sCompressionType.c_str(), "NONE") )
+    {
+        pabyCompressBuf = (GByte*) VSIMalloc( sizeof(GByte) * nMaxBufferSize );
+
+        if ( pabyCompressBuf == NULL )
+        {
+            CPLError( CE_Failure, CPLE_OutOfMemory,
+                "InitializeIO - Compression Buffer error\n"
+                "Cannot allocate memory buffer of (%ld) bytes "
+                "Consider the use of *smaller* block size",
+                nMaxBufferSize );
+            return false;
+        }
+    }
+
+    // --------------------------------------------------------------------
+    // Allocate array of LOB Locators
+    // --------------------------------------------------------------------
+
+    pahLocator = (OCILobLocator**) VSIMalloc( sizeof(void*) * nBlockCount );
+
+    if ( pahLocator == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory,
+                "InitializeIO - LobLocator Array error\n"
+                "Cannot allocate memory buffer of (%ld) bytes "
+                "Consider the use of *bigger* block size",
+                (sizeof(void*) * nBlockCount) );
+        return false;
+    }
+
+    //  --------------------------------------------------------------------
+    //  Issue a statement to load the locators
+    //  --------------------------------------------------------------------
+
+    const char* pszUpdate = "";
+
+    if( bUpdate )
+    {
+        pszUpdate = CPLStrdup( "\nFOR UPDATE" );
+    }
+
+    poBlockStmt = poConnection->CreateStatement( CPLSPrintf(
+        "SELECT RASTERBLOCK\n"
+        "FROM   %s%s\n"
+        "WHERE  RASTERID = :1\n"
+        "ORDER BY\n"
+        "       PYRAMIDLEVEL ASC,\n"
+        "       BANDBLOCKNUMBER ASC,\n"
+        "       ROWBLOCKNUMBER ASC,\n"
+        "       COLUMNBLOCKNUMBER ASC%s",
+        sSchema.c_str(),
+        sDataTable.c_str(),
+        pszUpdate ) );
+
+    poBlockStmt->Bind( &nRasterId );
+    poBlockStmt->Define( pahLocator, nBlockCount );
+
+    if( ! poBlockStmt->Execute( nBlockCount ) )
+    {
+        return false;
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            InitializeLevel()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::InitializeLevel( int nLevel )
+{
+    nCurrentLevel       = nLevel;
+    nColumnBlockSize    = pahLevels[nLevel].nColumnBlockSize;
+    nRowBlockSize       = pahLevels[nLevel].nRowBlockSize;
+    nTotalColumnBlocks  = pahLevels[nLevel].nTotalColumnBlocks;
+    nTotalRowBlocks     = pahLevels[nLevel].nTotalRowBlocks;
+    nBlockBytes         = pahLevels[nLevel].nBlockBytes;
+    nGDALBlockBytes     = pahLevels[nLevel].nGDALBlockBytes;
+    nLevelOffset        = pahLevels[nLevel].nOffset;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                               GetDataBlock()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::GetDataBlock( int nBand,
+                                     int nLevel,
+                                     int nXOffset,
+                                     int nYOffset,
+                                     void* pData )
+{
+    if( ! bInitializeIO )
+    {
+        if( InitializeIO() == false )
+        {
+            return false;
+        }
+    }
+
+    if( nCurrentLevel != nLevel )
+    {
+        InitializeLevel( nLevel );
+    }
+    
+    long nBlock = GetBlockNumber( nBand, nXOffset, nYOffset );
+
+    CPLDebug( "Read  ", 
+              "Block = %4ld Size = %7ld Band = %d Level = %d X = %d Y = %d", 
+              nBlock, nBlockBytes, nBand, nLevel, nXOffset, nYOffset );
+
+    if( nCacheBlockId != nBlock )
+    {
+        if ( bFlushBlock )       
+        {
+            if( ! FlushBlock( nCacheBlockId ) )
+            {
+                return false;
+            }
+        }
+
+        nCacheBlockId = nBlock;
+
+        unsigned long nBytesRead = 0;
+
+        nBytesRead = poBlockStmt->ReadBlob( pahLocator[nBlock],
+                                            pabyBlockBuf,
+                                            nBlockBytes );
+
+        CPLDebug( "Load  ", "Block = %4ld Size = %7ld", nBlock, nBlockBytes );
+
+        if( nBytesRead == 0 )
+        {
+            memset( pData, 0, nGDALBlockBytes );
+            return true;
+        }
+
+        if( nBytesRead < nBlockBytes && 
+            EQUAL( sCompressionType.c_str(), "NONE") )
+        {
+            CPLError( CE_Warning, CPLE_AppDefined, 
+                "BLOB size (%ld) is smaller than expected (%ld) !", 
+                nBytesRead,  nBlockBytes );
+            memset( pData, 0, nGDALBlockBytes );
+            return true;
+        }
+
+        if( nBytesRead > nBlockBytes )
+        {
+            CPLError( CE_Warning, CPLE_AppDefined, 
+                "BLOB size (%ld) is bigger than expected (%ld) !",
+                nBytesRead,  nBlockBytes );
+            memset( pData, 0, nGDALBlockBytes );
+            return true;
+        }
+
+#ifndef CPL_MSB
+        if( nCellSizeBits > 8 )
+        {
+            int nWordSize  = nCellSizeBits / 8;
+            int nWordCount = nColumnBlockSize * nRowBlockSize * nBandBlockSize;
+            GDALSwapWords( pabyBlockBuf, nWordSize, nWordCount, nWordSize );
+        }
+#endif
+
+        //  ----------------------------------------------------------------
+        //  Uncompress
+        //  ----------------------------------------------------------------
+
+        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+        {
+            UncompressJpeg( nBytesRead );
+        }
+        else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
+        {
+            UncompressDeflate( nBytesRead );
+        }
+
+        //  ----------------------------------------------------------------
+        //  Unpack NBits
+        //  ----------------------------------------------------------------
+
+        if( nCellSizeBits < 8 || nLevel == DEFAULT_BMP_MASK )
+        {
+            UnpackNBits( pabyBlockBuf );
+        }
+    }
+
+    //  --------------------------------------------------------------------
+    //  Uninterleaving, extract band from block buffer
+    //  --------------------------------------------------------------------
+
+    int nStart = ( nBand - 1 ) % nBandBlockSize;
+
+    if( EQUAL( sInterleaving.c_str(), "BSQ" ) || nBandBlockSize == 1 )
+    {
+        nStart *= nGDALBlockBytes;
+
+        memcpy( pData, &pabyBlockBuf[nStart], nGDALBlockBytes );
+    }
+    else
+    {
+        int nIncr   = nBandBlockSize * nGDALCellBytes;
+        int nSize   = nGDALCellBytes;
+
+        if( EQUAL( sInterleaving.c_str(), "BIL" ) )
+        {
+            nStart  *= nColumnBlockSize;
+            nIncr   *= nColumnBlockSize;
+            nSize   *= nColumnBlockSize;
+        }
+
+        GByte* pabyData = (GByte*) pData;
+
+        unsigned long ii = 0;
+        unsigned long jj = nStart * nGDALCellBytes;
+
+        for( ii = 0; ii < nGDALBlockBytes; ii += nSize, jj += nIncr )
+        {
+            memcpy( &pabyData[ii], &pabyBlockBuf[jj], nSize );
+        }
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                               SetDataBlock()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::SetDataBlock( int nBand,
+                                     int nLevel,
+                                     int nXOffset,
+                                     int nYOffset,
+                                     void* pData )
+{
+#ifndef CPL_MSB
+    if( nCellSizeBits > 8 )
+    {
+        int nWordSize  = nCellSizeBits / 8;
+        int nWordCount = nColumnBlockSize * nRowBlockSize;
+        GDALSwapWords( pData, nWordSize, nWordCount, nWordSize );
+    }
+#endif
+
+    if( ! bInitializeIO )
+    {
+        if( InitializeIO() == false )
+        {
+            return false;
+        }
+    }
+
+    if( nCurrentLevel != nLevel )
+    {
+        InitializeLevel( nLevel );
+    }
+
+    long nBlock = GetBlockNumber( nBand, nXOffset, nYOffset );
+
+    CPLDebug( "Write ", 
+              "Block = %4ld Size = %7ld Band = %d Level = %d X = %d Y = %d", 
+              nBlock, nBlockBytes, nBand, nLevel, nXOffset, nYOffset );
+
+    //  --------------------------------------------------------------------
+    //  Flush previous block
+    //  --------------------------------------------------------------------
+
+    if( nCacheBlockId != nBlock && bFlushBlock )
+    {
+        if( ! FlushBlock( nCacheBlockId ) )
+        {
+            return false;
+        }
+    }
+
+    //  --------------------------------------------------------------------
+    //  Re-load interleaved block
+    //  --------------------------------------------------------------------
+
+    if( nBandBlockSize > 1 && bWriteOnly == false && nCacheBlockId != nBlock )
+    {
+        nCacheBlockId = nBlock;
+
+        unsigned long nBytesRead = 0;
+
+        nBytesRead = poBlockStmt->ReadBlob( pahLocator[nBlock],
+                                            pabyBlockBuf,
+                                            nBlockBytes );
+
+        CPLDebug( "Reload", "Block = %4ld Size = %7ld", nBlock, nBlockBytes );
+
+        if( nBytesRead == 0 )
+        {
+            memset( pabyBlockBuf, 0, nBlockBytes );
+        }
+        else
+        {
+            //  ------------------------------------------------------------
+            //  Uncompress
+            //  ------------------------------------------------------------
+
+            if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+            {
+                UncompressJpeg( nBytesRead );
+            }
+            else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
+            {
+                UncompressDeflate( nBytesRead );
+            }
+            
+            //  ------------------------------------------------------------
+            //  Unpack NBits
+            //  ------------------------------------------------------------
+
+            if( nCellSizeBits < 8 || nLevel == DEFAULT_BMP_MASK )
+            {
+                UnpackNBits( pabyBlockBuf );
+            }
+        }
+    }
+
+    GByte *pabyInBuf = (GByte *) pData;
+
+    //  --------------------------------------------------------------------
+    //  Interleave
+    //  --------------------------------------------------------------------
+
+    int nStart = ( nBand - 1 ) % nBandBlockSize;
+
+    if( EQUAL( sInterleaving.c_str(), "BSQ" ) || nBandBlockSize == 1 )
+    {
+        nStart *= nGDALBlockBytes;
+
+        memcpy( &pabyBlockBuf[nStart], pabyInBuf, nGDALBlockBytes );
+    }
+    else
+    {
+        int nIncr   = nBandBlockSize * nGDALCellBytes;
+        int nSize   = nGDALCellBytes;
+
+        if( EQUAL( sInterleaving.c_str(), "BIL" ) )
+        {
+            nStart  *= nColumnBlockSize;
+            nIncr   *= nColumnBlockSize;
+            nSize   *= nColumnBlockSize;
+        }
+
+        unsigned long ii = 0;
+        unsigned long jj = nStart * nGDALCellBytes;
+
+        for( ii = 0; ii < nGDALBlockBytes; ii += nSize, jj += nIncr )
+        {
+            memcpy( &pabyBlockBuf[jj], &pabyInBuf[ii], nSize );
+        }
+    }
+
+    //  --------------------------------------------------------------------
+    //  Flag the flush block
+    //  --------------------------------------------------------------------
+
+    nCacheBlockId   = nBlock;
+    bFlushBlock     = true;
+    nFlushBlockSize = nBlockBytes;
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                 FlushBlock()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::FlushBlock( long nCacheBlock )
+{
+    GByte* pabyFlushBuffer = (GByte *) pabyBlockBuf;
+
+    //  --------------------------------------------------------------------
+    //  Pack bits ( inside pabyOutBuf )
+    //  --------------------------------------------------------------------
+
+    if( nCellSizeBits < 8 || nCurrentLevel == DEFAULT_BMP_MASK )
+    {
+        PackNBits( pabyFlushBuffer );
+    }
+
+    //  --------------------------------------------------------------------
+    //  Compress ( from pabyBlockBuf to pabyBlockBuf2 )
+    //  --------------------------------------------------------------------
+
+    if( ! EQUAL( sCompressionType.c_str(), "NONE" ) )
+    {
+        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+        {
+            nFlushBlockSize = CompressJpeg();
+        }
+        else if ( EQUAL( sCompressionType.c_str(), "DEFLATE" ) )
+        {
+            nFlushBlockSize = CompressDeflate();
+        }
+
+        pabyFlushBuffer = pabyCompressBuf;
+    }
+
+    //  --------------------------------------------------------------------
+    //  Write BLOB
+    //  --------------------------------------------------------------------
+
+    CPLDebug( "Flush ", "Block = %4ld Size = %7ld", nCacheBlock, 
+              nFlushBlockSize );
+
+    if( ! poBlockStmt->WriteBlob( pahLocator[nCacheBlock],
+                                  pabyFlushBuffer,
+                                  nFlushBlockSize ) )
+    {
+        return false;
+    }
+
+    bFlushBlock     = false;
+    bFlushMetadata  = true;
+    nFlushBlockSize = nBlockBytes;
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                           LoadNoDataValues()
+//  ---------------------------------------------------------------------------
+
+CPLList* AddToNoDataList( CPLXMLNode* phNode, int nNumber, CPLList* poList )
+{
+    CPLXMLNode* psChild = phNode->psChild;
+
+    const char* pszMin = NULL;
+    const char* pszMax = NULL;
+
+    for( ; psChild ; psChild = psChild->psNext )
+    {
+        if( EQUAL( psChild->pszValue, "value" ) )
+        {
+            pszMin = CPLGetXMLValue( psChild, NULL, "NONE" );
+            pszMax = pszMin;
+        }
+        else if ( EQUAL( psChild->pszValue, "range" ) )
+        {
+            pszMin = CPLGetXMLValue( psChild, "min", "NONE" );
+            pszMax = CPLGetXMLValue( psChild, "max", "NONE" );
+        }
+        else
+        {
+            continue;
+        }
+
+        hNoDataItem* poItem = (hNoDataItem*) CPLMalloc( sizeof( hNoDataItem ) );
+
+        poItem->nBand = nNumber;
+        poItem->dfLower = CPLAtof( pszMin );
+        poItem->dfUpper = CPLAtof( pszMax );
+
+        poList = CPLListAppend( poList, poItem );
+    }
+
+    return poList;
+}
+
+void GeoRasterWrapper::LoadNoDataValues( void )
+{
+    CPLListDestroy( psNoDataList );
+
+    CPLXMLNode* phLayerInfo = CPLGetXMLNode( phMetadata, "layerInfo" );
+
+    if( phLayerInfo == NULL )
+    {
+        return;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Load NoDatas from list of values and list of value ranges
+    //  -------------------------------------------------------------------
+
+    CPLXMLNode* phObjNoData = CPLGetXMLNode( phLayerInfo, "objectLayer.NODATA" );
+
+    for( ; phObjNoData ; phObjNoData = phObjNoData->psNext )
+    {
+        psNoDataList = AddToNoDataList( phObjNoData, 0, psNoDataList );
+    }
+
+    CPLXMLNode* phSubLayer = CPLGetXMLNode( phLayerInfo, "subLayer" );
+
+    for( ; phSubLayer ; phSubLayer = phSubLayer->psNext )
+    {
+        int nNumber = atoi( CPLGetXMLValue( phSubLayer, "layerNumber", "-1") );
+
+        CPLXMLNode* phSubNoData = CPLGetXMLNode( phSubLayer, "NODATA" );
+
+        if( phSubNoData )
+        {
+            psNoDataList = AddToNoDataList( phSubNoData, nNumber, psNoDataList );
+        }
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     GetRPC()
+//  ---------------------------------------------------------------------------
+
+/* This is the order for storing 20 coeffients in GeoRaster Metadata */
+
+static const int anOrder[] = { 
+    1, 2, 8, 12, 3, 5, 15, 9, 13, 16, 4, 6, 18, 7, 11, 19, 10, 14, 17, 20
+};
+
+void GeoRasterWrapper::GetRPC()
+{
+    int i;
+
+    CPLXMLNode* phSRSInfo = CPLGetXMLNode( phMetadata, 
+                                           "spatialReferenceInfo" );
+
+    if( phSRSInfo == NULL )
+    {
+        return;
+    }
+
+    const char* pszModelType = CPLGetXMLValue( phMetadata,
+                               "spatialReferenceInfo.modelType", "None" );
+
+    if( EQUAL( pszModelType, "FunctionalFitting" ) == false )
+    {
+        return;
+    }
+
+    CPLXMLNode* phPolyModel = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
+
+    if ( phPolyModel == NULL )
+    {
+        return;
+    }
+
+    // pPolynomial refers to LINE_NUM
+
+    CPLXMLNode* phPolynomial = CPLGetXMLNode( phPolyModel, "pPolynomial" );
+
+    if ( phPolynomial == NULL )
+    {
+        return;
+    }
+
+    int nNumCoeff = atoi( CPLGetXMLValue( phPolynomial, "nCoefficients", "0" ) );
+
+    if ( nNumCoeff != 20 )
+    {
+        return;
+    }
+
+    const char* pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
+
+    if ( EQUAL( pszPolyCoeff, "None" ) )
+    {
+        return;
+    }
+
+    char** papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
+
+    if( CSLCount( papszCeoff ) != 20 )
+    {
+        return;
+    }
+
+    phRPC = (GDALRPCInfo*) VSIMalloc( sizeof(GDALRPCInfo) );
+    
+    phRPC->dfLINE_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "rowOff", "0" ) );
+    phRPC->dfSAMP_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "columnOff", "0" ) );
+    phRPC->dfLONG_OFF     = CPLAtof( CPLGetXMLValue( phPolyModel, "xOff", "0" ) );
+    phRPC->dfLAT_OFF      = CPLAtof( CPLGetXMLValue( phPolyModel, "yOff", "0" ) );
+    phRPC->dfHEIGHT_OFF   = CPLAtof( CPLGetXMLValue( phPolyModel, "zOff", "0" ) );
+
+    phRPC->dfLINE_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "rowScale", "0" ) );
+    phRPC->dfSAMP_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "columnScale", "0" ) );
+    phRPC->dfLONG_SCALE   = CPLAtof( CPLGetXMLValue( phPolyModel, "xScale", "0" ) );
+    phRPC->dfLAT_SCALE    = CPLAtof( CPLGetXMLValue( phPolyModel, "yScale", "0" ) );
+    phRPC->dfHEIGHT_SCALE = CPLAtof( CPLGetXMLValue( phPolyModel, "zScale", "0" ) );
+
+    for( i = 0; i < 20; i++ )
+    {
+        phRPC->adfLINE_NUM_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
+    }
+
+    // qPolynomial refers to LINE_DEN
+
+    phPolynomial = CPLGetXMLNode( phPolyModel, "qPolynomial" );
+
+    if ( phPolynomial == NULL )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
+
+    if ( EQUAL( pszPolyCoeff, "None" ) )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
+
+    if( CSLCount( papszCeoff ) != 20 )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    for( i = 0; i < 20; i++ )
+    {
+        phRPC->adfLINE_DEN_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
+    }
+
+    // rPolynomial refers to SAMP_NUM
+
+    phPolynomial = CPLGetXMLNode( phPolyModel, "rPolynomial" );
+
+    if ( phPolynomial == NULL )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
+
+    if ( EQUAL( pszPolyCoeff, "None" ) )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
+
+    if( CSLCount( papszCeoff ) != 20 )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    for( i = 0; i < 20; i++ )
+    {
+        phRPC->adfSAMP_NUM_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
+    }
+
+    // sPolynomial refers to SAMP_DEN
+
+    phPolynomial = CPLGetXMLNode( phPolyModel, "sPolynomial" );
+
+    if ( phPolynomial == NULL )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    pszPolyCoeff = CPLGetXMLValue( phPolynomial, "polynomialCoefficients", "None" );
+
+    if ( EQUAL( pszPolyCoeff, "None" ) )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    papszCeoff = CSLTokenizeString2( pszPolyCoeff, " ", CSLT_STRIPLEADSPACES );
+
+    if( CSLCount( papszCeoff ) != 20 )
+    {
+        CPLFree( phRPC );
+        phRPC = NULL;
+        return;
+    }
+
+    for( i = 0; i < 20; i++ )
+    {
+        phRPC->adfSAMP_DEN_COEFF[anOrder[i] - 1] = CPLAtof( papszCeoff[i] );
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     SetRPC()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::SetRPC()
+{
+    //  -------------------------------------------------------------------
+    //  Remove "layerInfo" tree
+    //  -------------------------------------------------------------------
+
+    CPLXMLNode* phLayerInfo = CPLGetXMLNode( phMetadata, "layerInfo" );
+    CPLXMLNode* phClone = NULL;
+
+    if( phLayerInfo )
+    {
+        phClone = CPLCloneXMLTree( phLayerInfo );
+        CPLRemoveXMLChild( phMetadata, phLayerInfo );
+    }
+
+    //  -------------------------------------------------------------------
+    //  Start loading the RPC to "spatialReferenceInfo" tree
+    //  -------------------------------------------------------------------
+
+    int i = 0;
+    CPLString osField, osMultiField;
+    CPLXMLNode* phPolynomial = NULL;
+
+    CPLXMLNode* phSRSInfo = CPLGetXMLNode( phMetadata, 
+                                           "spatialReferenceInfo" );
+
+    if( ! phSRSInfo )
+    {
+        phSRSInfo = CPLCreateXMLNode( phMetadata, CXT_Element, 
+                                      "spatialReferenceInfo" );
+    }
+    else
+    {
+        CPLXMLNode* phNode = NULL;
+
+        phNode = CPLGetXMLNode( phSRSInfo, "isReferenced" );
+        if( phNode )
+        {
+            CPLRemoveXMLChild( phSRSInfo, phNode );
+        }
+
+        phNode = CPLGetXMLNode( phSRSInfo, "SRID" );
+        if( phNode )
+        {
+            CPLRemoveXMLChild( phSRSInfo, phNode );
+        }
+
+        phNode = CPLGetXMLNode( phSRSInfo, "modelCoordinateLocation" );
+        if( phNode )
+        {
+            CPLRemoveXMLChild( phSRSInfo, phNode );
+        }
+
+        phNode = CPLGetXMLNode( phSRSInfo, "modelType" );
+        if( phNode )
+        {
+            CPLRemoveXMLChild( phSRSInfo, phNode );
+        }
+
+        phNode = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
+        if( phNode )
+        {
+            CPLRemoveXMLChild( phSRSInfo, phNode );
+        }
+    }
+
+    CPLCreateXMLElementAndValue( phSRSInfo, "isReferenced", "true" );
+    CPLCreateXMLElementAndValue( phSRSInfo, "SRID", "4327" );
+    CPLCreateXMLElementAndValue( phSRSInfo, "modelCoordinateLocation", 
+                                            "CENTER" );
+    CPLCreateXMLElementAndValue( phSRSInfo, "modelType", "FunctionalFitting" );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#rowOff",      
+                                    CPLSPrintf( "%.15g", phRPC->dfLINE_OFF ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#columnOff",   
+                                    CPLSPrintf( "%.15g", phRPC->dfSAMP_OFF ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#xOff",        
+                                    CPLSPrintf( "%.15g", phRPC->dfLONG_OFF ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#yOff",        
+                                    CPLSPrintf( "%.15g", phRPC->dfLAT_OFF ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#zOff",        
+                                    CPLSPrintf( "%.15g", phRPC->dfHEIGHT_OFF ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#rowScale",    
+                                    CPLSPrintf( "%.15g", phRPC->dfLINE_SCALE ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#columnScale", 
+                                    CPLSPrintf( "%.15g", phRPC->dfSAMP_SCALE ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#xScale",      
+                                    CPLSPrintf( "%.15g", phRPC->dfLONG_SCALE ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#yScale",      
+                                    CPLSPrintf( "%.15g", phRPC->dfLAT_SCALE ) );
+    CPLSetXMLValue( phSRSInfo, "polynomialModel.#zScale",      
+                                    CPLSPrintf( "%.15g", phRPC->dfHEIGHT_SCALE ) );
+    CPLXMLNode*     phPloyModel = CPLGetXMLNode( phSRSInfo, "polynomialModel" );
+
+    // pPolynomial refers to LINE_NUM
+
+    CPLSetXMLValue( phPloyModel, "pPolynomial.#pType",         "1" );
+    CPLSetXMLValue( phPloyModel, "pPolynomial.#nVars",         "3" );
+    CPLSetXMLValue( phPloyModel, "pPolynomial.#order",         "3" );
+    CPLSetXMLValue( phPloyModel, "pPolynomial.#nCoefficients", "20" );
+    for( i = 0; i < 20; i++ )
+    {
+        osField.Printf( "%.15g", phRPC->adfLINE_NUM_COEFF[anOrder[i] - 1] );
+        if( i > 0 )
+            osMultiField += " ";
+        else
+            osMultiField = "";
+        osMultiField += osField;
+    }
+    phPolynomial = CPLGetXMLNode( phPloyModel, "pPolynomial" );
+    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
+                                 osMultiField );
+
+    // qPolynomial refers to LINE_DEN
+
+    CPLSetXMLValue( phPloyModel, "qPolynomial.#pType",         "1" );
+    CPLSetXMLValue( phPloyModel, "qPolynomial.#nVars",         "3" );
+    CPLSetXMLValue( phPloyModel, "qPolynomial.#order",         "3" );
+    CPLSetXMLValue( phPloyModel, "qPolynomial.#nCoefficients", "20" );
+    for( i = 0; i < 20; i++ )
+    {
+        osField.Printf( "%.15g", phRPC->adfLINE_DEN_COEFF[anOrder[i] - 1] );
+        if( i > 0 )
+            osMultiField += " ";
+        else
+            osMultiField = "";
+        osMultiField += osField;
+    }
+    phPolynomial = CPLGetXMLNode( phPloyModel, "qPolynomial" );
+    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
+                                 osMultiField );
+
+    // rPolynomial refers to SAMP_NUM
+
+    CPLSetXMLValue( phPloyModel, "rPolynomial.#pType",         "1" );
+    CPLSetXMLValue( phPloyModel, "rPolynomial.#nVars",         "3" );
+    CPLSetXMLValue( phPloyModel, "rPolynomial.#order",         "3" );
+    CPLSetXMLValue( phPloyModel, "rPolynomial.#nCoefficients", "20" );
+    for( i = 0; i < 20; i++ )
+    {
+        osField.Printf( "%.15g", phRPC->adfSAMP_NUM_COEFF[anOrder[i] - 1] );
+        if( i > 0 )
+            osMultiField += " ";
+        else
+            osMultiField = "";
+        osMultiField += osField;
+    }
+    phPolynomial = CPLGetXMLNode( phPloyModel, "rPolynomial" );
+    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
+                                 osMultiField );
+
+    // sPolynomial refers to SAMP_DEN
+
+    CPLSetXMLValue( phPloyModel, "sPolynomial.#pType",         "1" );
+    CPLSetXMLValue( phPloyModel, "sPolynomial.#nVars",         "3" );
+    CPLSetXMLValue( phPloyModel, "sPolynomial.#order",         "3" );
+    CPLSetXMLValue( phPloyModel, "sPolynomial.#nCoefficients", "20" );
+    for( i = 0; i < 20; i++ )
+    {
+        osField.Printf( "%.15g", phRPC->adfSAMP_DEN_COEFF[anOrder[i] - 1] );
+        if( i > 0 )
+            osMultiField += " ";
+        else
+            osMultiField = "";
+        osMultiField += osField;
+    }
+    phPolynomial = CPLGetXMLNode( phPloyModel, "sPolynomial" );
+    CPLCreateXMLElementAndValue( phPolynomial, "polynomialCoefficients", 
+                                 osMultiField );
+
+    //  -------------------------------------------------------------------
+    //  Add "layerInfo" tree back
+    //  -------------------------------------------------------------------
+
+    CPLAddXMLChild( phMetadata, phClone );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                  GetNoData()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::GetNoData( int nLayer, double* pdfNoDataValue )
+{
+    if( psNoDataList == NULL || CPLListCount( psNoDataList ) == 0 )
+    {
+        return false;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Get only single value NoData, no list of values or value ranges
+    //  -------------------------------------------------------------------
+
+    int nCount = 0;
+    double dfValue = 0.0;
+
+    CPLList* psList = NULL;
+
+    //  -------------------------------------------------------------------
+    //  Process Object Layer values
+    //  -------------------------------------------------------------------
+
+    for( psList = psNoDataList; psList ; psList = psList->psNext )
+    {
+        hNoDataItem* phItem = (hNoDataItem*) psList->pData;
+
+        if( phItem->nBand == 0 )
+        {
+            if( phItem->dfLower == phItem->dfUpper )
+            {
+                dfValue = phItem->dfLower;
+                nCount++;
+            }
+            else
+            {
+                return false; // value range
+            }
+        }
+    }
+
+    //  -------------------------------------------------------------------
+    //  Values from the Object Layer override values from the layers 
+    //  -------------------------------------------------------------------
+
+    if( nCount == 1 )
+    {
+        *pdfNoDataValue = dfValue;
+        return true;
+    }
+
+    //  -------------------------------------------------------------------
+    //  Process SubLayer values
+    //  -------------------------------------------------------------------
+
+    for( psList = psNoDataList; psList ; psList = psList->psNext )
+    {
+        hNoDataItem* phItem = (hNoDataItem*) psList->pData;
+
+        if( phItem->nBand == nLayer )
+        {
+            if( phItem->dfLower == phItem->dfUpper )
+            {
+                dfValue = phItem->dfLower;
+                nCount++;
+            }
+            else
+            {
+                return false; // value range
+            }
+        }
+    }
+
+    if( nCount == 1 )
+    {
+        *pdfNoDataValue = dfValue;
+        return true;
+    }
+
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                             SetNoDataValue()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::SetNoData( int nLayer, const char* pszValue )
+{
+    // ------------------------------------------------------------
+    //  Set one NoData per dataset on "rasterInfo" section (10g)
+    // ------------------------------------------------------------
+
+    if( poConnection->GetVersion() < 11 )
+    {
+        CPLXMLNode* psRInfo = CPLGetXMLNode( phMetadata, "rasterInfo" );
+        CPLXMLNode* psNData = CPLSearchXMLNode( psRInfo, "NODATA" );
+
+        if( psNData == NULL )
+        {
+            psNData = CPLCreateXMLNode( NULL, CXT_Element, "NODATA" );
+
+            CPLXMLNode* psCDepth = CPLGetXMLNode( psRInfo, "cellDepth" );
+
+            CPLXMLNode* psPointer = psCDepth->psNext;
+            psCDepth->psNext = psNData;
+            psNData->psNext = psPointer;
+        }
+
+        CPLSetXMLValue( psRInfo, "NODATA", pszValue );
+        bFlushMetadata = true;
+        return true;
+    }
+
+    // ------------------------------------------------------------
+    //  Add NoData for all bands (layer=0) or for a specific band
+    // ------------------------------------------------------------
+
+    char szRDT[OWCODE];
+    char szNoData[OWTEXT];
+    
+    strcpy( szRDT, sDataTable.c_str() );
+    strcpy( szNoData, pszValue );
+
+    int nRID = nRasterId;
+
+    // ------------------------------------------------------------
+    //  Write the in memory XML metada to avoid lossing other changes
+    // ------------------------------------------------------------
+
+    char* pszMetadata = CPLSerializeXMLTree( phMetadata );
+
+    if( pszMetadata == NULL )
+    {
+        return false;
+    }
+
+    OCILobLocator* phLocatorR = NULL;
+    OCILobLocator* phLocatorW = NULL;
+    
+    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "DECLARE\n"
+        "  GR1 sdo_georaster;\n"
+        "BEGIN\n"
+        "  SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;\n"
+        "\n"
+        "  GR1.metadata := sys.xmltype.createxml(:1);\n"
+        "\n"
+        "  SDO_GEOR.addNODATA( GR1, :2, :3 );\n"
+        "\n"
+        "  UPDATE %s%s T SET %s = GR1 WHERE %s;\n"
+        "\n"
+        "  EXECUTE IMMEDIATE\n"
+        "    'SELECT T.%s.METADATA.getClobVal() FROM %s%s T \n"
+        "     WHERE  T.%s.RASTERDATATABLE = UPPER(:1)\n"
+        "       AND  T.%s.RASTERID = :2'\n"
+        "    INTO :metadata USING :rdt, :rid;\n"
+        "\n"
+        "  COMMIT;\n"
+        "END;",
+            sColumn.c_str(), sSchema.c_str(), sTable.c_str(), sWhere.c_str(),
+            sSchema.c_str(), sTable.c_str(), sColumn.c_str(), sWhere.c_str(),
+            sColumn.c_str(), sSchema.c_str(), sTable.c_str(),
+            sColumn.c_str(),
+            sColumn.c_str() ) );
+
+    poStmt->WriteCLob( &phLocatorW, pszMetadata );
+
+    poStmt->Bind( &phLocatorW );
+    poStmt->Bind( &nLayer );
+    poStmt->Bind( szNoData );
+    poStmt->BindName( ":metadata", &phLocatorR );
+    poStmt->BindName( ":rdt", szRDT );
+    poStmt->BindName( ":rid", &nRID );
+
+    CPLFree( pszMetadata );    
+
+    if( ! poStmt->Execute() )
+    {
+        OCIDescriptorFree( phLocatorR, OCI_DTYPE_LOB );
+        OCIDescriptorFree( phLocatorW, OCI_DTYPE_LOB );
+        delete poStmt;
+        return false;
+    }
+
+    OCIDescriptorFree( phLocatorW, OCI_DTYPE_LOB );
+
+    // ------------------------------------------------------------
+    //  Read the XML metadata from db to memory with nodata updates
+    // ------------------------------------------------------------
+
+    char* pszXML = poStmt->ReadCLob( phLocatorR );
+
+    if( pszXML )
+    {
+        CPLDestroyXMLNode( phMetadata );
+        phMetadata = CPLParseXMLString( pszXML );
+        CPLFree( pszXML );
+    }
+
+    OCIDescriptorFree( phLocatorR, OCI_DTYPE_LOB );
+
+    bFlushMetadata = true;
+    delete poStmt;
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     SetVAT()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::SetVAT( int nBand, const char* pszName )
+{
+    InitializeLayersNode();
+
+    bFlushMetadata = true;
+
+    int n = 1;
+
+    CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    for( ; psLayers; psLayers = psLayers->psNext, n++ )
+    {
+        if( n != nBand )
+        {
+            continue;
+        }
+
+        CPLXMLNode* psVAT = CPLGetXMLNode( psLayers, "vatTableName" );
+
+        if( psVAT != NULL )
+        {
+            CPLRemoveXMLChild( psLayers, psVAT );
+            CPLDestroyXMLNode( psVAT );
+        }
+
+        CPLCreateXMLElementAndValue(psLayers, "vatTableName", pszName );
+
+        // ------------------------------------------------------------
+        // To be updated at Flush Metadata in SDO_GEOR.setVAT()
+        // ------------------------------------------------------------
+
+        sValueAttributeTab = pszName;
+
+        return true;
+    }
+
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                     GetVAT()
+//  ---------------------------------------------------------------------------
+
+char* GeoRasterWrapper::GetVAT( int nBand )
+{
+    CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo.subLayer" );
+
+    if( psLayers == NULL )
+    {
+        return NULL;
+    }
+
+    char* pszTablename = NULL;
+
+    int n = 1;
+
+    for( ; psLayers; psLayers = psLayers->psNext, n++ )
+    {
+        if( n != nBand )
+        {
+            continue;
+        }
+
+        CPLXMLNode* psVAT = CPLGetXMLNode( psLayers, "vatTableName" );
+
+        if( psVAT != NULL )
+        {
+            pszTablename = CPLStrdup(
+                CPLGetXMLValue( psLayers, "vatTableName", "" ) );
+        }
+
+        break;
+    }
+
+    return pszTablename;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                              FlushMetadata()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::FlushMetadata()
+{
+    if( bFlushBlock )
+    {
+        FlushBlock( nCacheBlockId );
+    }
+
+    if( ! bFlushMetadata )
+    {
+        return true;
+    }
+
+    bFlushMetadata = false;
+
+    //  --------------------------------------------------------------------
+    //  Change the isBlank setting left by SDO_GEOR.createBlank() to 'false'
+    //  --------------------------------------------------------------------
+
+    CPLXMLNode* psOInfo = CPLGetXMLNode( phMetadata, "objectInfo" );
+    CPLXMLNode* psNode  = NULL;
+
+    CPLSetXMLValue( psOInfo,  "isBlank", "false" );
+
+    psNode  = CPLGetXMLNode( psOInfo, "blankCellValue" );
+
+    if( psNode != NULL )
+    {
+        CPLRemoveXMLChild( psOInfo, psNode );
+        CPLDestroyXMLNode( psNode );
+    }
+
+    const char* pszRed   = "1";
+    const char* pszGreen = "1";
+    const char* pszBlue  = "1";
+
+    if( ( nRasterBands > 2 ) &&
+        ( ! HasColorMap( 1 ) ) &&
+        ( ! HasColorMap( 2 ) ) &&
+        ( ! HasColorMap( 3 ) ) )
+    {
+        pszRed   = "1";
+        pszGreen = "2";
+        pszBlue  = "3";
+    }
+
+    psNode = CPLGetXMLNode( psOInfo, "defaultRed" );
+    if( psNode )
+    {
+        CPLRemoveXMLChild( psOInfo, psNode );
+        CPLDestroyXMLNode( psNode );
+    }
+    CPLCreateXMLElementAndValue( psOInfo, "defaultRed",   pszRed );
+
+    psNode = CPLGetXMLNode( psOInfo, "defaultGreen" );
+    if( psNode )
+    {
+        CPLRemoveXMLChild( psOInfo, psNode );
+        CPLDestroyXMLNode( psNode );
+    }
+    CPLCreateXMLElementAndValue( psOInfo, "defaultGreen",   pszGreen );
+
+    psNode = CPLGetXMLNode( psOInfo, "defaultBlue" );
+    if( psNode )
+    {
+        CPLRemoveXMLChild( psOInfo, psNode );
+        CPLDestroyXMLNode( psNode );
+    }
+    CPLCreateXMLElementAndValue( psOInfo, "defaultBlue",   pszBlue );
+
+    //  --------------------------------------------------------------------
+    //  Set compression
+    //  --------------------------------------------------------------------
+
+    psNode = CPLGetXMLNode( phMetadata, "rasterInfo.compression" );
+
+    if( psNode )
+    {
+        CPLSetXMLValue( psNode, "type", sCompressionType.c_str() );
+
+        if( EQUALN( sCompressionType.c_str(), "JPEG", 4 ) )
+        {
+            CPLSetXMLValue( psNode, "quality",
+                CPLSPrintf( "%d", nCompressQuality ) );
+        }
+    }
+
+    //  --------------------------------------------------------------------
+    //  Update BitmapMask info
+    //  --------------------------------------------------------------------
+
+    if( bHasBitmapMask )
+    {
+        CPLXMLNode* psLayers = CPLGetXMLNode( phMetadata, "layerInfo" );
+
+        if( psLayers )
+        {
+            CPLCreateXMLElementAndValue( psLayers, "bitmapMask", "true" );
+        }
+    }
+
+    //  --------------------------------------------------------------------
+    //  Update the Metadata directly from the XML text
+    //  --------------------------------------------------------------------
+
+    double dfXCoef[3];
+    double dfYCoef[3];
+    int nMLC;
+
+    dfXCoef[0] = dfXCoefficient[0];
+    dfXCoef[1] = dfXCoefficient[1];
+    dfXCoef[2] = dfXCoefficient[2];
+
+    dfYCoef[0] = dfYCoefficient[0];
+    dfYCoef[1] = dfYCoefficient[1];
+    dfYCoef[2] = dfYCoefficient[2];
+
+    if ( eModelCoordLocation == MCL_CENTER )
+    {
+      dfXCoef[2] += dfXCoefficient[0] / 2;
+      dfYCoef[2] += dfYCoefficient[1] / 2;
+      nMLC = MCL_CENTER;
+    }
+    else
+    {
+      nMLC = MCL_UPPERLEFT;
+    }
+
+    if( phRPC )
+    {
+        SetRPC();
+        nSRID = 0;
+    }
+
+    //  --------------------------------------------------------------------
+    //  Serialize XML metadata to plain text
+    //  --------------------------------------------------------------------
+
+    char* pszMetadata = CPLSerializeXMLTree( phMetadata );
+
+    if( pszMetadata == NULL )
+    {
+        return false;
+    }
+
+    if( bGenSpatialIndex )
+    {
+        nExtentSRID = nExtentSRID == 0 ? nSRID : nExtentSRID;
+    }
+    else
+    {
+        nExtentSRID = 0; /* Set spatialExtent to null */
+    }
+
+    //  --------------------------------------------------------------------
+    //  Update GeoRaster Metadata
+    //  --------------------------------------------------------------------
+
+    int nException = 0;
+
+    OCILobLocator* phLocator = NULL;
+
+    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "DECLARE\n"
+        "  GR1      sdo_georaster;\n"
+        "  GM1      sdo_geometry;\n"
+        "  SRID     number  := :1;\n"
+        "  EXT_SRID number  := :2;\n"
+        "  VAT      varchar2(128);\n"
+        "BEGIN\n"
+        "\n"
+        "  SELECT %s INTO GR1 FROM %s%s T WHERE %s FOR UPDATE;\n"
+        "\n"
+        "  GR1.metadata := sys.xmltype.createxml(:3);\n"
+        "\n"
+        "  IF SRID != 0 THEN\n"
+        "    SDO_GEOR.georeference( GR1, SRID, :4,"
+        "      SDO_NUMBER_ARRAY(:5, :6, :7), SDO_NUMBER_ARRAY(:8, :9, :10));\n"
+        "  END IF;\n"
+        "\n"
+        "  IF EXT_SRID = 0 THEN\n"
+        "    GM1 := NULL;\n"
+        "  ELSE\n"
+        "    GM1 := SDO_GEOR.generateSpatialExtent( GR1 );\n"
+        "    IF EXT_SRID != SRID THEN\n"
+        "      GM1 := SDO_CS.transform( GM1, EXT_SRID );\n"
+        "    END IF;\n"
+        "  END IF;\n"
+        "\n"
+        "  GR1.spatialExtent := GM1;\n"
+        "\n"
+        "  VAT := '%s';\n"
+        "  IF VAT != '' THEN\n"
+        "    SDO_GEOR.setVAT(GR1, 1, VAT);\n"
+        "  END IF;\n"
+        "\n"
+        "  BEGIN\n"
+        "    UPDATE %s%s T SET %s = GR1\n"
+        "    WHERE %s;\n"
+        "  EXCEPTION\n"
+        "    WHEN OTHERS THEN\n"
+        "      :except := SQLCODE;\n"
+        "      IF (SQLCODE != -29877) THEN\n"
+        "        RAISE;\n"
+        "      END IF;\n"
+        "  END\n"
+        "\n"
+        "  COMMIT;\n"
+        "END;",
+            sColumn.c_str(),
+            sSchema.c_str(),
+            sTable.c_str(),
+            sWhere.c_str(),
+            sValueAttributeTab.c_str(),
+            sSchema.c_str(),
+            sTable.c_str(),
+            sColumn.c_str(),
+            sWhere.c_str() ) );
+
+    poStmt->WriteCLob( &phLocator, pszMetadata );
+    
+    poStmt->Bind( &nSRID );
+    poStmt->Bind( &nExtentSRID );
+    poStmt->Bind( &phLocator );
+    poStmt->Bind( &nMLC );
+    poStmt->Bind( &dfXCoef[0] );
+    poStmt->Bind( &dfXCoef[1] );
+    poStmt->Bind( &dfXCoef[2] );
+    poStmt->Bind( &dfYCoef[0] );
+    poStmt->Bind( &dfYCoef[1] );
+    poStmt->Bind( &dfYCoef[2] );
+    poStmt->BindName( ":except", &nException );
+
+    CPLFree( pszMetadata );
+
+    if( ! poStmt->Execute() )
+    {
+        OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
+        delete poStmt;
+        return false;
+    }
+
+    OCIDescriptorFree( phLocator, OCI_DTYPE_LOB );
+
+    delete poStmt;
+
+    if( nException )
+    {
+        CPLError( CE_Warning, CPLE_AppDefined, 
+            "Cannot generate spatialExtent! (ORA-%d) ", nException );
+    }
+
+    if (bGenPyramid) 
+    {
+        if (GeneratePyramid( nPyramidLevels, sPyramidResampling.c_str(), true ))
+        {
+            CPLDebug("GEOR", "Generated pyramid successfully.");
+        }
+        else
+        {
+            CPLError( CE_Warning, CPLE_AppDefined, "Error generating pyramid!");
+        }
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            GeneratePyramid()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::GeneratePyramid( int nLevels,
+                                        const char* pszResampling,
+                                        bool bInternal )
+{
+    nPyramidMaxLevel = nLevels;
+
+    if( bInternal )
+    {
+        CPLString sLevels = "";
+
+        if (nLevels > 0)
+        {
+            sLevels = CPLSPrintf("rlevel=%d", nLevels);
+        }
+
+        OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
+            "DECLARE\n"
+            "  gr sdo_georaster;\n"
+            "BEGIN\n"
+            "  SELECT %s INTO gr FROM %s t WHERE %s FOR UPDATE;\n"
+            "  sdo_geor.generatePyramid(gr, '%s resampling=%s');\n"
+            "  UPDATE %s t SET %s = gr WHERE %s;\n"
+            "  COMMIT;\n"
+            "END;\n",
+                sColumn.c_str(),
+                sTable.c_str(),
+                sWhere.c_str(),
+                sLevels.c_str(),
+                pszResampling,
+                sTable.c_str(),
+                sColumn.c_str(),
+                sWhere.c_str() ) );
+
+        if( poStmt->Execute() )
+        {
+            delete poStmt;
+            return true;
+        }
+
+        delete poStmt;
+        return false;
+    }
+
+    //  -----------------------------------------------------------
+    //  Create rows for pyramid levels
+    //  -----------------------------------------------------------
+
+    OWStatement* poStmt = NULL;
+
+    poStmt = poConnection->CreateStatement(
+        "DECLARE\n"
+        "  SCL  NUMBER         := 0;\n"
+        "  RC   NUMBER         := 0;\n"
+        "  RR   NUMBER         := 0;\n"
+        "  CBS2 NUMBER         := 0;\n"
+        "  RBS2 NUMBER         := 0;\n"
+        "  TBB  NUMBER         := 0;\n"
+        "  TRB  NUMBER         := 0;\n"
+        "  TCB  NUMBER         := 0;\n"
+        "  X    NUMBER         := 0;\n"
+        "  Y    NUMBER         := 0;\n"
+        "  W    NUMBER         := 0;\n"
+        "  H    NUMBER         := 0;\n"
+        "  STM  VARCHAR2(1024) := '';\n"
+        "BEGIN\n"
+        "  EXECUTE IMMEDIATE 'DELETE FROM '||:rdt||' \n"
+        "    WHERE RASTERID = '||:rid||' AND PYRAMIDLEVEL > 0';\n"
+        "  STM := 'INSERT INTO '||:rdt||' VALUES (:1, :2, :3-1, :4-1, :5-1 ,\n"
+        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
+        "    SDO_ORDINATE_ARRAY(:6, :7, :8-1, :9-1)), EMPTY_BLOB() )';\n"
+        "  TBB  := :TotalBandBlocks;\n"
+        "  RBS2 := floor(:RowBlockSize / 2);\n"
+        "  CBS2 := floor(:ColumnBlockSize / 2);\n"
+        "  FOR l IN 1..:level LOOP\n"
+        "    SCL := 2 ** l;\n"
+        "    RR  := floor(:RasterRows / SCL);\n"
+        "    RC  := floor(:RasterColumns / SCL);\n"
+        "    IF (RC <= CBS2) OR (RR <= RBS2) THEN\n"
+        "      H   := RR;\n"
+        "      W   := RC;\n"
+        "    ELSE\n"
+        "      H   := :RowBlockSize;\n"
+        "      W   := :ColumnBlockSize;\n"
+        "    END IF;\n"
+        "    TRB := greatest(1, ceil( ceil(:RasterColumns / :ColumnBlockSize) / SCL));\n"
+        "    TCB := greatest(1, ceil( ceil(:RasterRows / :RowBlockSize) / SCL));\n"
+        "    FOR b IN 1..TBB LOOP\n"
+        "      Y := 0;\n"
+        "      FOR r IN 1..TCB LOOP\n"
+        "        X := 0;\n"
+        "        FOR c IN 1..TRB LOOP\n"
+        "          EXECUTE IMMEDIATE STM USING :rid, l, b, r, c, Y, X, (Y+H), (X+W);\n"
+        "          X := X + W;\n"
+        "        END LOOP;\n"
+        "        Y := Y + H;\n"
+        "      END LOOP;\n"
+        "    END LOOP;\n"
+        "  END LOOP;\n"
+        "  COMMIT;\n"
+        "END;" );
+
+    const char* pszDataTable = sDataTable.c_str();
+
+    poStmt->BindName( ":rdt",             (char*) pszDataTable );
+    poStmt->BindName( ":rid",             &nRasterId );
+    poStmt->BindName( ":level",           &nLevels );
+    poStmt->BindName( ":TotalBandBlocks", &nTotalBandBlocks );
+    poStmt->BindName( ":RowBlockSize",    &nRowBlockSize );
+    poStmt->BindName( ":ColumnBlockSize", &nColumnBlockSize );
+    poStmt->BindName( ":RasterRows",      &nRasterRows );
+    poStmt->BindName( ":RasterColumns",   &nRasterColumns );
+
+    if( ! poStmt->Execute() )
+    {
+        delete poStmt;
+        return false;
+    }
+
+    CPLXMLNode* psNode = CPLGetXMLNode( phMetadata, "rasterInfo.pyramid" );
+
+    if( psNode )
+    {
+        CPLSetXMLValue( psNode, "type", "DECREASE" );
+        CPLSetXMLValue( psNode, "resampling", pszResampling );
+        CPLSetXMLValue( psNode, "maxLevel", CPLSPrintf( "%d", nLevels ) );
+    }
+
+    bFlushMetadata = true;
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            GeneratePyramid()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::DeletePyramid()
+{
+    OWStatement* poStmt = poConnection->CreateStatement( CPLSPrintf(
+        "DECLARE\n"
+        "  gr sdo_georaster;\n"
+        "BEGIN\n"
+        "  SELECT %s INTO gr FROM %s t WHERE %s FOR UPDATE;\n"
+        "  sdo_geor.deletePyramid(gr);\n"
+        "  UPDATE %s t SET %s = gr WHERE %s;\n"
+        "  COMMIT;\n"
+        "END;\n",
+            sColumn.c_str(),
+            sTable.c_str(),
+            sWhere.c_str(),
+            sTable.c_str(),
+            sColumn.c_str(),
+            sWhere.c_str() ) );
+    
+    poStmt->Execute();
+
+    delete poStmt;
+    return false;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                           CreateBitmapMask()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::InitializeMask( int nLevel,
+                                       int nBlockColumns,
+                                       int nBlockRows,
+                                       int nColumnBlocks,
+                                       int nRowBlocks,
+                                       int nBandBlocks )
+{
+    //  -----------------------------------------------------------
+    //  Create rows for the bitmap mask
+    //  -----------------------------------------------------------
+
+    OWStatement* poStmt = NULL;
+
+    poStmt = poConnection->CreateStatement(
+        "DECLARE\n"
+        "  W    NUMBER          := :1;\n"
+        "  H    NUMBER          := :2;\n"
+        "  BB   NUMBER          := :3;\n"
+        "  RB   NUMBER          := :4;\n"
+        "  CB   NUMBER          := :5;\n"
+        "  X    NUMBER          := 0;\n"
+        "  Y    NUMBER          := 0;\n"
+        "  STM  VARCHAR2(1024)  := '';\n"
+        "BEGIN\n"
+        "\n"
+        "  EXECUTE IMMEDIATE 'DELETE FROM '||:rdt||' \n"
+        "    WHERE RASTERID = '||:rid||' AND PYRAMIDLEVEL = '||:lev||' ';\n"
+        "\n"
+        "  STM := 'INSERT INTO '||:rdt||' VALUES (:1, :lev, :2-1, :3-1, :4-1 ,\n"
+        "    SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3),\n"
+        "    SDO_ORDINATE_ARRAY(:5, :6, :7-1, :8-1)), EMPTY_BLOB() )';\n"
+        "\n"
+        "  FOR b IN 1..BB LOOP\n"
+        "    Y := 0;\n"
+        "    FOR r IN 1..RB LOOP\n"
+        "      X := 0;\n"
+        "      FOR c IN 1..CB LOOP\n"
+        "        EXECUTE IMMEDIATE STM USING :rid, b, r, c, Y, X, (Y+H), (X+W);\n"
+        "        X := X + W;\n"
+        "      END LOOP;\n"
+        "      Y := Y + H;\n"
+        "    END LOOP;\n"
+        "  END LOOP;\n"
+        "END;" );
+
+    char pszDataTable[OWNAME];
+    
+    poStmt->Bind( &nBlockColumns );
+    poStmt->Bind( &nBlockRows );
+    poStmt->Bind( &nBandBlocks );
+    poStmt->Bind( &nRowBlocks );
+    poStmt->Bind( &nColumnBlocks );
+    poStmt->BindName( ":rdt", pszDataTable );
+    poStmt->BindName( ":rid", &nRasterId );
+    poStmt->BindName( ":lev", &nLevel );
+
+    if( ! poStmt->Execute() )
+    {
+        delete poStmt;
+        return false;
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                UnpackNBits()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::UnpackNBits( GByte* pabyData )
+{
+    int nPixCount = nColumnBlockSize * nRowBlockSize * nBandBlockSize;
+
+    if( EQUAL( sCellDepth.c_str(), "4BIT" ) )
+    {
+        for( int ii = nPixCount - 2; ii >= 0; ii -= 2 )
+        {
+            int k = ii >> 1;
+            pabyData[ii+1] = (pabyData[k]     ) & 0xf;
+            pabyData[ii]   = (pabyData[k] >> 4) & 0xf;
+        }
+    }
+    else if( EQUAL( sCellDepth.c_str(), "2BIT" ) )
+    {
+        for( int ii = nPixCount - 4; ii >= 0; ii -= 4 )
+        {
+            int k = ii >> 2;
+            pabyData[ii+3] = (pabyData[k]     ) & 0x3;
+            pabyData[ii+2] = (pabyData[k] >> 2) & 0x3;
+            pabyData[ii+1] = (pabyData[k] >> 4) & 0x3;
+            pabyData[ii]   = (pabyData[k] >> 6) & 0x3;
+        }
+    }
+    else
+    {
+        for( int ii = nPixCount - 1; ii >= 0; ii-- )
+        {
+            if( ( pabyData[ii>>3] & ( 128 >> (ii & 0x7) ) ) )
+                pabyData[ii] = 1;
+            else
+                pabyData[ii] = 0;
+        }
+    }
+}
+
+//  ---------------------------------------------------------------------------
+//                                                                  PackNBits()
+//  ---------------------------------------------------------------------------
+
+void GeoRasterWrapper::PackNBits( GByte* pabyData )
+{
+    int nPixCount = nBandBlockSize * nRowBlockSize * nColumnBlockSize;
+
+    GByte* pabyBuffer = (GByte*) VSIMalloc( nPixCount * sizeof(GByte*) );
+
+    if( pabyBuffer == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory, "PackNBits" );
+        return;
+    }
+
+    if( nCellSizeBits == 4 )
+    {
+        for( int ii = 0; ii < nPixCount - 1; ii += 2 )
+        {
+            int k = ii >> 1;
+            pabyBuffer[k] =
+                  ((((GByte *) pabyData)[ii+1] & 0xf)     )
+                | ((((GByte *) pabyData)[ii]   & 0xf) << 4);
+        }
+    }
+    else if( nCellSizeBits == 2 )
+    {
+        for( int ii = 0; ii < nPixCount - 3; ii += 4 )
+        {
+            int k = ii >> 2;
+            pabyBuffer[k] =
+                  ((((GByte *) pabyData)[ii+3] & 0x3)     )
+                | ((((GByte *) pabyData)[ii+2] & 0x3) << 2)
+                | ((((GByte *) pabyData)[ii+1] & 0x3) << 4)
+                | ((((GByte *) pabyData)[ii]   & 0x3) << 6);
+        }
+    }
+    else
+    {
+        for( int ii = 0; ii < nPixCount - 7; ii += 8 )
+        {
+            int k = ii >> 3;
+            pabyBuffer[k] =
+                  ((((GByte *) pabyData)[ii+7] & 0x1)     )
+                | ((((GByte *) pabyData)[ii+6] & 0x1) << 1)
+                | ((((GByte *) pabyData)[ii+5] & 0x1) << 2)
+                | ((((GByte *) pabyData)[ii+4] & 0x1) << 3)
+                | ((((GByte *) pabyData)[ii+3] & 0x1) << 4)
+                | ((((GByte *) pabyData)[ii+2] & 0x1) << 5)
+                | ((((GByte *) pabyData)[ii+1] & 0x1) << 6)
+                | ((((GByte *) pabyData)[ii]   & 0x1) << 7);
+        }
+    }
+
+    memcpy( pabyData, pabyBuffer, nPixCount );
+
+    CPLFree( pabyBuffer );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                             UncompressJpeg()
+//  ---------------------------------------------------------------------------
+
+const static int K2Chrominance[64] =
+{
+    17, 18, 24, 47, 99, 99, 99, 99,
+    18, 21, 26, 66, 99, 99, 99, 99,
+    24, 26, 56, 99, 99, 99, 99, 99,
+    47, 66, 99, 99, 99, 99, 99, 99,
+    99, 99, 99, 99, 99, 99, 99, 99,
+    99, 99, 99, 99, 99, 99, 99, 99,
+    99, 99, 99, 99, 99, 99, 99, 99,
+    99, 99, 99, 99, 99, 99, 99, 99
+};
+
+static const int AC_BITS[16] =
+{
+    0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119
+};
+
+static const int AC_HUFFVAL[256] =
+{
+      0,   1,   2,   3,  17,   4,   5,  33,  49,   6,  18,
+     65,  81,   7,  97, 113,  19,  34,  50, 129,   8,  20,
+     66, 145, 161, 177, 193,   9,  35,  51,  82, 240,  21,
+     98, 114, 209,  10,  22,  36,  52, 225,  37, 241,  23,
+     24,  25,  26,  38,  39,  40,  41,  42,  53,  54,  55,
+     56,  57,  58,  67,  68,  69,  70,  71,  72,  73,  74,
+     83,  84,  85,  86,  87,  88,  89,  90,  99, 100, 101,
+    102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120,
+    121, 122, 130, 131, 132, 133, 134, 135, 136, 137, 138,
+    146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163,
+    164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181,
+    182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199,
+    200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217,
+    218, 226, 227, 228, 229, 230, 231, 232, 233, 234, 242,
+    243, 244, 245, 246, 247, 248, 249, 250
+};
+
+static const int DC_BITS[16] =
+{
+    0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
+};
+
+static const int DC_HUFFVAL[256] =
+{
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
+};
+
+/***
+ *
+ * Load the tables based on the Java's JAI default values.
+ *
+ * JPEGQTable.K2Chrominance.getScaledInstance()
+ * JPEGHuffmanTable.StdACChrominance
+ * JPEGHuffmanTable.StdDCChrominance
+ *
+ ***/
+
+void JPEG_LoadTables( JQUANT_TBL* hquant_tbl_ptr,
+                      JHUFF_TBL* huff_ac_ptr,
+                      JHUFF_TBL* huff_dc_ptr,
+                      unsigned int nQuality )
+{
+    int i = 0;
+    float fscale_factor;
+
+    //  --------------------------------------------------------------------
+    //  Scale Quantization table based on quality
+    //  --------------------------------------------------------------------
+
+    fscale_factor = (float) jpeg_quality_scaling( nQuality ) / (float) 100.0;
+
+    for ( i = 0; i < 64; i++ )
+    {
+        UINT16 temp = (UINT16) floor( K2Chrominance[i] * fscale_factor + 0.5 );
+        if ( temp <= 0 )
+            temp = 1;
+        if ( temp > 255 )
+            temp = 255;
+        hquant_tbl_ptr->quantval[i] = (UINT16) temp;
+    }
+
+    //  --------------------------------------------------------------------
+    //  Load AC huffman table
+    //  --------------------------------------------------------------------
+
+    for ( i = 1; i <= 16; i++ )
+    {
+        /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
+        huff_ac_ptr->bits[i] = (UINT8) AC_BITS[i-1];
+    }
+
+    for ( i = 0; i < 256; i++ )
+    {
+        /* symbols[] is the list of Huffman symbols, in code-length order */
+        huff_ac_ptr->huffval[i] = (UINT8) AC_HUFFVAL[i];
+    }
+
+    //  --------------------------------------------------------------------
+    //  Load DC huffman table
+    //  --------------------------------------------------------------------
+
+    for ( i = 1; i <= 16; i++ )
+    {
+        /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
+        huff_dc_ptr->bits[i] = (UINT8) DC_BITS[i-1];
+    }
+
+    for ( i = 0; i < 256; i++ )
+    {
+        /* symbols[] is the list of Huffman symbols, in code-length order */
+        huff_dc_ptr->huffval[i] = (UINT8) DC_HUFFVAL[i];
+    }
+}
+
+void GeoRasterWrapper::UncompressJpeg( unsigned long nInSize )
+{
+    //  --------------------------------------------------------------------
+    //  Load JPEG in a virtual file
+    //  --------------------------------------------------------------------
+
+    const char* pszMemFile = CPLSPrintf( "/vsimem/geor_%p.jpg", pabyBlockBuf );
+
+    VSILFILE *fpImage = VSIFOpenL( pszMemFile, "wb" );
+    VSIFWriteL( pabyBlockBuf, nInSize, 1, fpImage );
+    VSIFCloseL( fpImage );
+
+    fpImage = VSIFOpenL( pszMemFile, "rb" );
+
+    //  --------------------------------------------------------------------
+    //  Initialize decompressor
+    //  --------------------------------------------------------------------
+
+    if( ! sDInfo.global_state )
+    {
+        sDInfo.err = jpeg_std_error( &sJErr );
+        jpeg_create_decompress( &sDInfo );
+
+        // -----------------------------------------------------------------
+        // Load table for abbreviated JPEG-B
+        // -----------------------------------------------------------------
+
+        int nComponentsToLoad = -1; /* doesn't load any table */
+
+        if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
+        {
+            nComponentsToLoad = nBandBlockSize;
+        }
+
+        for( int n = 0; n < nComponentsToLoad; n++ )
+        {
+            sDInfo.quant_tbl_ptrs[n] =
+                jpeg_alloc_quant_table( (j_common_ptr) &sDInfo );
+            sDInfo.ac_huff_tbl_ptrs[n] =
+                jpeg_alloc_huff_table( (j_common_ptr) &sDInfo );
+            sDInfo.dc_huff_tbl_ptrs[n] =
+                jpeg_alloc_huff_table( (j_common_ptr) &sDInfo );
+            
+            JPEG_LoadTables( sDInfo.quant_tbl_ptrs[n],
+                             sDInfo.ac_huff_tbl_ptrs[n],
+                             sDInfo.dc_huff_tbl_ptrs[n],
+                             nCompressQuality );
+        }
+
+    }
+
+    jpeg_vsiio_src( &sDInfo, fpImage );
+    jpeg_read_header( &sDInfo, TRUE );
+
+    sDInfo.out_color_space = ( nBandBlockSize == 1 ? JCS_GRAYSCALE : JCS_RGB );
+
+    jpeg_start_decompress( &sDInfo );
+
+    GByte* pabyScanline = pabyBlockBuf;
+
+    for( int iLine = 0; iLine < nRowBlockSize; iLine++ )
+    {
+        JSAMPLE* ppSamples = (JSAMPLE*) pabyScanline;
+        jpeg_read_scanlines( &sDInfo, &ppSamples, 1 );
+        pabyScanline += ( nColumnBlockSize * nBandBlockSize );
+    }
+
+    jpeg_finish_decompress( &sDInfo );
+
+    VSIFCloseL( fpImage );
+
+    VSIUnlink( pszMemFile );
+}
+
+//  ---------------------------------------------------------------------------
+//                                                               CompressJpeg()
+//  ---------------------------------------------------------------------------
+
+unsigned long GeoRasterWrapper::CompressJpeg( void )
+{
+    //  --------------------------------------------------------------------
+    //  Load JPEG in a virtual file
+    //  --------------------------------------------------------------------
+
+    const char* pszMemFile = CPLSPrintf( "/vsimem/geor_%p.jpg", pabyBlockBuf );
+
+    VSILFILE *fpImage = VSIFOpenL( pszMemFile, "wb" );
+
+    bool write_all_tables = TRUE;
+
+    if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
+    {
+        write_all_tables = FALSE;
+    }
+
+    //  --------------------------------------------------------------------
+    //  Initialize compressor
+    //  --------------------------------------------------------------------
+
+    if( ! sCInfo.global_state )
+    {
+        sCInfo.err = jpeg_std_error( &sJErr );
+        jpeg_create_compress( &sCInfo );
+
+        jpeg_vsiio_dest( &sCInfo, fpImage );
+        
+        sCInfo.image_width = nColumnBlockSize;
+        sCInfo.image_height = nRowBlockSize;
+        sCInfo.input_components = nBandBlockSize;
+        sCInfo.in_color_space = (nBandBlockSize == 1 ? JCS_GRAYSCALE : JCS_RGB);
+        jpeg_set_defaults( &sCInfo );
+        sCInfo.JFIF_major_version = 1;
+        sCInfo.JFIF_minor_version = 2;
+        jpeg_set_quality( &sCInfo, nCompressQuality, TRUE );
+
+        // -----------------------------------------------------------------
+        // Load table for abbreviated JPEG-B
+        // -----------------------------------------------------------------
+
+        int nComponentsToLoad = -1; /* doesn't load any table */
+
+        if( EQUAL( sCompressionType.c_str(), "JPEG-B") )
+        {
+            nComponentsToLoad = nBandBlockSize;
+        }
+
+        for( int n = 0; n < nComponentsToLoad; n++ )
+        {
+            sCInfo.quant_tbl_ptrs[n] =
+                jpeg_alloc_quant_table( (j_common_ptr) &sCInfo );
+            sCInfo.ac_huff_tbl_ptrs[n] =
+                jpeg_alloc_huff_table( (j_common_ptr) &sCInfo );
+            sCInfo.dc_huff_tbl_ptrs[n] =
+                jpeg_alloc_huff_table( (j_common_ptr) &sCInfo );
+
+            JPEG_LoadTables( sCInfo.quant_tbl_ptrs[n],
+                             sCInfo.ac_huff_tbl_ptrs[n],
+                             sCInfo.dc_huff_tbl_ptrs[n],
+                             nCompressQuality );
+        }
+    }
+    else
+    {
+        jpeg_vsiio_dest( &sCInfo, fpImage );
+    }
+    
+    jpeg_suppress_tables( &sCInfo, ! write_all_tables );
+    jpeg_start_compress( &sCInfo, write_all_tables );
+    
+    GByte* pabyScanline = pabyBlockBuf;
+
+    for( int iLine = 0; iLine < nRowBlockSize; iLine++ )
+    {
+        JSAMPLE* ppSamples = (JSAMPLE*) pabyScanline;
+        jpeg_write_scanlines( &sCInfo, &ppSamples, 1 );
+        pabyScanline += ( nColumnBlockSize * nBandBlockSize );
+    }
+
+    jpeg_finish_compress( &sCInfo );
+
+    VSIFCloseL( fpImage );
+
+    fpImage = VSIFOpenL( pszMemFile, "rb" );
+    size_t nSize = VSIFReadL( pabyCompressBuf, 1, nBlockBytes, fpImage );
+    VSIFCloseL( fpImage );
+
+    VSIUnlink( pszMemFile );
+
+    return (unsigned long) nSize;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                          UncompressDeflate()
+//  ---------------------------------------------------------------------------
+
+bool GeoRasterWrapper::UncompressDeflate( unsigned long nBufferSize )
+{
+    GByte* pabyBuf = (GByte*) VSIMalloc( nBufferSize );
+
+    if( pabyBuf == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory, "UncompressDeflate" );
+        return false;
+    }
+
+    memcpy( pabyBuf, pabyBlockBuf, nBufferSize );
+
+    // Call ZLib uncompress
+
+    unsigned long nDestLen = nBlockBytes;
+
+    int nRet = uncompress( pabyBlockBuf, &nDestLen, pabyBuf, nBufferSize );
+
+    CPLFree( pabyBuf );
+
+    if( nRet != Z_OK )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, "ZLib return code (%d)", nRet );
+        return false;
+    }
+
+    if( nDestLen != nBlockBytes )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+            "ZLib decompressed buffer size (%ld) expected (%ld)", nDestLen, nBlockBytes );
+        return false;
+    }
+
+    return true;
+}
+
+//  ---------------------------------------------------------------------------
+//                                                            CompressDeflate()
+//  ---------------------------------------------------------------------------
+
+unsigned long GeoRasterWrapper::CompressDeflate( void )
+{
+    unsigned long nLen = ((unsigned long)(nBlockBytes * 1.1)) + 12;
+
+    GByte* pabyBuf = (GByte*) VSIMalloc( nBlockBytes );
+
+    if( pabyBuf == NULL )
+    {
+        CPLError( CE_Failure, CPLE_OutOfMemory, "CompressDeflate" );
+        return 0;
+    }
+
+    memcpy( pabyBuf, pabyBlockBuf, nBlockBytes );
+
+    // Call ZLib compress
+
+    int nRet = compress( pabyCompressBuf, &nLen, pabyBuf, nBlockBytes );
+
+    CPLFree( pabyBuf );
+
+    if( nRet != Z_OK )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, "ZLib return code (%d)", nRet );
+        return 0;
+    }
+
+    return nLen;
+}
diff --git a/frmts/gff/gff_dataset.cpp b/frmts/gff/gff_dataset.cpp
index c46cecd..ec050b8 100644
--- a/frmts/gff/gff_dataset.cpp
+++ b/frmts/gff/gff_dataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gff_dataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gff_dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Ground-based SAR Applitcations Testbed File Format driver
  * Purpose:  Support in GDAL for Sandia National Laboratory's GFF format
@@ -36,7 +36,7 @@
 #include "cpl_vsi.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: gff_dataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gff_dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /*******************************************************************
  * Declaration of the GFFDataset class                             *
@@ -137,8 +137,8 @@ GFFRasterBand::GFFRasterBand( GFFDataset *poDS, int nBand,
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GFFRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
-				void *pImage ) 
+CPLErr GFFRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
+                                  void *pImage ) 
 {
     GFFDataset *poGDS = (GFFDataset *)poDS;
     long nOffset = poGDS->nLength;
diff --git a/frmts/gif/biggifdataset.cpp b/frmts/gif/biggifdataset.cpp
index f996508..6ee6679 100644
--- a/frmts/gif/biggifdataset.cpp
+++ b/frmts/gif/biggifdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: biggifdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: biggifdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  BIGGIF Driver
  * Purpose:  Implement GDAL support for reading large GIF files in a 
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include "gifabstractdataset.h"
 
-CPL_CVSID("$Id: biggifdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: biggifdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_BIGGIF(void);
@@ -190,7 +190,7 @@ BIGGifRasterBand::~BIGGifRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr BIGGifRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr BIGGifRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -339,7 +339,7 @@ CPLErr BIGGIFDataset::ReOpen()
 /*      If the file is already open, close it so we can restart.        */
 /* -------------------------------------------------------------------- */
     if( hGifFile != NULL )
-        DGifCloseFile( hGifFile );
+        GIFAbstractDataset::myDGifCloseFile( hGifFile );
 
 /* -------------------------------------------------------------------- */
 /*      If we are actually reopening, then we assume that access to     */
@@ -373,12 +373,7 @@ CPLErr BIGGIFDataset::ReOpen()
     VSIFSeekL( fp, 0, SEEK_SET );
 
     nLastLineRead = -1;
-#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
-    int nError;
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc, &nError );
-#else
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc );
-#endif
+    hGifFile = GIFAbstractDataset::myDGifOpen( fp, VSIGIFReadFunc );
     if( hGifFile == NULL )
     {
         CPLError( CE_Failure, CPLE_OpenFailed, 
@@ -413,7 +408,7 @@ CPLErr BIGGIFDataset::ReOpen()
 
     if( RecordType != IMAGE_DESC_RECORD_TYPE )
     {
-        DGifCloseFile( hGifFile );
+        GIFAbstractDataset::myDGifCloseFile( hGifFile );
         hGifFile = NULL;
 
         CPLError( CE_Failure, CPLE_OpenFailed, 
@@ -423,7 +418,7 @@ CPLErr BIGGIFDataset::ReOpen()
     
     if (DGifGetImageDesc(hGifFile) == GIF_ERROR)
     {
-        DGifCloseFile( hGifFile );
+        GIFAbstractDataset::myDGifCloseFile( hGifFile );
         hGifFile = NULL;
 
         CPLError( CE_Failure, CPLE_OpenFailed, 
diff --git a/frmts/gif/gifabstractdataset.cpp b/frmts/gif/gifabstractdataset.cpp
index 81c6ec3..7fc4978 100644
--- a/frmts/gif/gifabstractdataset.cpp
+++ b/frmts/gif/gifabstractdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gifabstractdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gifabstractdataset.cpp 27459 2014-06-15 11:30:36Z rouault $
  *
  * Project:  GIF Driver
  * Purpose:  GIF Abstract Dataset
@@ -29,7 +29,7 @@
 
 #include "gifabstractdataset.h"
 
-CPL_CVSID("$Id: gifabstractdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gifabstractdataset.cpp 27459 2014-06-15 11:30:36Z rouault $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -82,7 +82,7 @@ GIFAbstractDataset::~GIFAbstractDataset()
     }
 
     if( hGifFile )
-        DGifCloseFile( hGifFile );
+        myDGifCloseFile( hGifFile );
 
     if( fp != NULL )
         VSIFCloseL( fp );
@@ -336,3 +336,45 @@ void GIFAbstractDataset::DetectGeoreferencing( GDALOpenInfo * poOpenInfo )
                                adfGeoTransform );
     }
 }
+
+/************************************************************************/
+/*                            myDGifOpen()                              */
+/************************************************************************/
+
+GifFileType* GIFAbstractDataset::myDGifOpen( void *userPtr, InputFunc readFunc )
+{
+#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
+    int nErrorCode;
+    return DGifOpen( userPtr, readFunc, &nErrorCode );
+#else
+    return DGifOpen( userPtr, readFunc );
+#endif
+}
+
+/************************************************************************/
+/*                          myDGifCloseFile()                           */
+/************************************************************************/
+
+int GIFAbstractDataset::myDGifCloseFile( GifFileType *hGifFile )
+{
+#if defined(GIFLIB_MAJOR) && ((GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) || GIFLIB_MAJOR > 5)
+    int nErrorCode;
+    return DGifCloseFile( hGifFile, &nErrorCode );
+#else
+    return DGifCloseFile( hGifFile );
+#endif
+}
+
+/************************************************************************/
+/*                          myEGifCloseFile()                           */
+/************************************************************************/
+
+int GIFAbstractDataset::myEGifCloseFile( GifFileType *hGifFile )
+{
+#if defined(GIFLIB_MAJOR) && ((GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) || GIFLIB_MAJOR > 5)
+    int nErrorCode;
+    return EGifCloseFile( hGifFile, &nErrorCode );
+#else
+    return EGifCloseFile( hGifFile );
+#endif
+}
diff --git a/frmts/gif/gifabstractdataset.h b/frmts/gif/gifabstractdataset.h
index d61485b..30ad489 100644
--- a/frmts/gif/gifabstractdataset.h
+++ b/frmts/gif/gifabstractdataset.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gifabstractdataset.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gifabstractdataset.h 27459 2014-06-15 11:30:36Z rouault $
  *
  * Project:  GIF Driver
  * Purpose:  GIF Abstract Dataset
@@ -75,6 +75,10 @@ class GIFAbstractDataset : public GDALPamDataset
     virtual char  **GetMetadata( const char * pszDomain = "" );
 
     static int          Identify( GDALOpenInfo * );
+
+    static GifFileType* myDGifOpen( void *userPtr, InputFunc readFunc );
+    static int          myDGifCloseFile( GifFileType *hGifFile );
+    static int          myEGifCloseFile( GifFileType *hGifFile );
 };
 
 
diff --git a/frmts/gif/gifdataset.cpp b/frmts/gif/gifdataset.cpp
index 62a8793..8a69906 100644
--- a/frmts/gif/gifdataset.cpp
+++ b/frmts/gif/gifdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gifdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gifdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GIF Driver
  * Purpose:  Implement GDAL GIF Support using libungif code.  
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "gifabstractdataset.h"
 
-CPL_CVSID("$Id: gifdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gifdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_GIF(void);
@@ -234,7 +234,7 @@ GIFRasterBand::~GIFRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GIFRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr GIFRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -332,12 +332,7 @@ GDALDataset *GIFDataset::Open( GDALOpenInfo * poOpenInfo )
     if( fp == NULL )
         return NULL;
 
-#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
-    int nError;
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc, &nError );
-#else
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc );
-#endif
+    hGifFile = GIFAbstractDataset::myDGifOpen( fp, VSIGIFReadFunc );
     if( hGifFile == NULL )
     {
         VSIFCloseL( fp );
@@ -386,21 +381,17 @@ GDALDataset *GIFDataset::Open( GDALOpenInfo * poOpenInfo )
             CPLDebug( "GIF",
                       "Due to limitations of the GDAL GIF driver we deliberately avoid\n"
                       "opening large GIF files (larger than 100 megapixels).");
-            DGifCloseFile( hGifFile );
+            GIFAbstractDataset::myDGifCloseFile( hGifFile );
             VSIFCloseL( fp );
             return NULL;
         }
     }
 
-    DGifCloseFile( hGifFile );
+    GIFAbstractDataset::myDGifCloseFile( hGifFile );
 
     VSIFSeekL( fp, 0, SEEK_SET);
 
-#if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc, &nError );
-#else
-    hGifFile = DGifOpen( fp, VSIGIFReadFunc );
-#endif
+    hGifFile = GIFAbstractDataset::myDGifOpen( fp, VSIGIFReadFunc );
     if( hGifFile == NULL )
     {
         VSIFCloseL( fp );
@@ -417,7 +408,7 @@ GDALDataset *GIFDataset::Open( GDALOpenInfo * poOpenInfo )
     if( nGifErr != GIF_OK || hGifFile->SavedImages == NULL )
     {
         VSIFCloseL( fp );
-        DGifCloseFile(hGifFile);
+        GIFAbstractDataset::myDGifCloseFile(hGifFile);
 
         if( nGifErr == D_GIF_ERR_DATA_TOO_BIG )
         {
@@ -493,7 +484,11 @@ GDALDataset *GIFDataset::Open( GDALOpenInfo * poOpenInfo )
 /*                        GDALPrintGifError()                           */
 /************************************************************************/
 
-static void GDALPrintGifError(GifFileType *hGifFile, const char* pszMsg)
+static void GDALPrintGifError(
+#if GIFLIB_MAJOR < 5
+CPL_UNUSED 
+#endif
+GifFileType *hGifFile, const char* pszMsg)
 {
 /* GIFLIB_MAJOR is only defined in libgif >= 4.2.0 */
 /* libgif 4.2.0 has retired PrintGifError() and added GifErrorString() */
@@ -649,7 +644,7 @@ GIFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
     {
         GifFreeMapObject(psGifCT);
         GDALPrintGifError(hGifFile, "Error writing gif file.");
-        EGifCloseFile(hGifFile);
+        GIFAbstractDataset::myEGifCloseFile(hGifFile);
         VSIFCloseL( fp );
         return NULL;
     }
@@ -673,7 +668,7 @@ GIFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
     if (EGifPutImageDesc(hGifFile, 0, 0, nXSize, nYSize, bInterlace, NULL) == GIF_ERROR )
     {
         GDALPrintGifError(hGifFile, "Error writing gif file.");
-        EGifCloseFile(hGifFile);
+        GIFAbstractDataset::myEGifCloseFile(hGifFile);
         VSIFCloseL( fp );
         return NULL;
     }
@@ -756,7 +751,7 @@ GIFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
 /* -------------------------------------------------------------------- */
 /*      cleanup                                                         */
 /* -------------------------------------------------------------------- */
-    if (EGifCloseFile(hGifFile) == GIF_ERROR)
+    if (GIFAbstractDataset::myEGifCloseFile(hGifFile) == GIF_ERROR)
     {
         CPLError( CE_Failure, CPLE_AppDefined, 
                   "EGifCloseFile() failed.\n" );
@@ -807,7 +802,7 @@ GIFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
 
 error:
     if (hGifFile)
-        EGifCloseFile(hGifFile);
+        GIFAbstractDataset::myEGifCloseFile(hGifFile);
     if (fp)
         VSIFCloseL( fp );
     if (pabyScanline)
diff --git a/frmts/grib/degrib18/degrib/clock.c b/frmts/grib/degrib18/degrib/clock.c
index 7c9fa2e..878bbe6 100644
--- a/frmts/grib/degrib18/degrib/clock.c
+++ b/frmts/grib/degrib18/degrib/clock.c
@@ -11,6 +11,8 @@
 #include "memwatch.h"
 #endif
 
+#include "cpl_port.h"
+
 /* Take a look at the options in:
  * http://www.unet.univie.ac.at/aix/cmds/aixcmds2/date.htm#A270961
  */
@@ -1392,7 +1394,7 @@ int Clock_ScanMonth (char *ptr)
  * NOTES
  *****************************************************************************
  */
-void Clock_PrintMonth3 (int mon, char *buffer, int buffLen)
+void Clock_PrintMonth3 (int mon, char *buffer, CPL_UNUSED int buffLen)
 {
    static char *MonthName[] = {
       "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
@@ -1420,7 +1422,7 @@ void Clock_PrintMonth3 (int mon, char *buffer, int buffLen)
  * NOTES
  *****************************************************************************
  */
-void Clock_PrintMonth (int mon, char *buffer, int buffLen)
+void Clock_PrintMonth (int mon, char *buffer, CPL_UNUSED int buffLen)
 {
    static char *MonthName[] = {
       "January", "February", "March", "April", "May", "June", "July",
diff --git a/frmts/grib/degrib18/degrib/degrib1.cpp b/frmts/grib/degrib18/degrib/degrib1.cpp
index 759caee..b830522 100644
--- a/frmts/grib/degrib18/degrib/degrib1.cpp
+++ b/frmts/grib/degrib18/degrib/degrib1.cpp
@@ -1240,6 +1240,7 @@ static int ReadGrib1Sect3 (uChar *bms, uInt4 gribLen, uInt4 *curLoc,
    return 0;
 }
 
+#ifdef DEBUG
 static int UnpackCmplx (uChar *bds, uInt4 gribLen, uInt4 *curLoc,
                         short int DSF, double *data, grib_MetaData *meta,
                         char f_bms, uChar *bitmap, double unitM,
@@ -1336,6 +1337,7 @@ static int UnpackCmplx (uChar *bds, uInt4 gribLen, uInt4 *curLoc,
    return -2;
 
 }
+#endif /* DEBUG */
 
 /*****************************************************************************
  * ReadGrib1Sect4() --
@@ -1770,7 +1772,7 @@ int ReadGrib1Record (DataSource &fp, sChar f_unit, double **Grib_Data,
    }
    meta->pds1.gridID = gridID;
    /* Allow data originating from NCEP to be 6371.2 by default. */
-   if ((meta->center == NMC)) {
+   if (meta->center == NMC) {
       if (meta->gds.majEarth == 6367.47) {
          meta->gds.f_sphere = 1;
          meta->gds.majEarth = 6371.2;
diff --git a/frmts/grib/degrib18/degrib/degrib2.cpp b/frmts/grib/degrib18/degrib/degrib2.cpp
index dacb646..49567fc 100644
--- a/frmts/grib/degrib18/degrib/degrib2.cpp
+++ b/frmts/grib/degrib18/degrib/degrib2.cpp
@@ -31,6 +31,8 @@
 //#include "mymapf.h"
 #include "clock.h"
 
+#include "cpl_port.h"
+
 #define GRIB_UNSIGN_INT3(a,b,c) ((a<<16)+(b<<8)+c)
 
 /*****************************************************************************
@@ -815,7 +817,7 @@ int ReadGrib2Record (DataSource &fp, sChar f_unit, double **Grib_Data,
                      uInt4 *grib_DataLen, grib_MetaData *meta,
                      IS_dataType *IS, int subgNum, double majEarth,
                      double minEarth, int simpVer, sInt4 *f_endMsg,
-                     LatLon *lwlf, LatLon *uprt)
+                     CPL_UNUSED LatLon *lwlf, CPL_UNUSED LatLon *uprt)
 {
    sInt4 l3264b;        /* Number of bits in a sInt4.  Needed by FORTRAN
                          * unpack library to determine if system has a 4
diff --git a/frmts/grib/degrib18/degrib/grib1tab.cpp b/frmts/grib/degrib18/degrib/grib1tab.cpp
index 89960af..3b092d5 100644
--- a/frmts/grib/degrib18/degrib/grib1tab.cpp
+++ b/frmts/grib/degrib18/degrib/grib1tab.cpp
@@ -2253,7 +2253,7 @@ GRIB1ParmTable parm_table_ncep_tdl[256] = {
    /* 246 */ {"var246", "undefined", "-", UC_NONE},
    /* 247 */ {"var247", "undefined", "-", UC_NONE},
    /* 248 */ {"var248", "undefined", "-", UC_NONE},
-   /* 249 */ {"BTSTM", "Categorical T-Storm (Ltng)"},
+   /* 249 */ {"BTSTM", "Categorical T-Storm (Ltng)", "-", UC_NONE},
    /* 250 */ {"var250", "undefined", "-", UC_NONE},
    /* 251 */ {"BSVR", "Categorical Severe Weather", "num", UC_NONE},
    /* 252 */ {"var252", "undefined", "-", UC_NONE},
@@ -5692,7 +5692,7 @@ GRIB1ParmTable parm_table_dwd_201[256] = {
               "J/(kg*s)", UC_NONE},
    /* 127 */ {"DQL_GSP", "tendency of total water, grid-scale condensation",
               "1/s", UC_NONE},
-   /* 128 */ {"snowfall", "snowfall  (dimension"},
+   /* 128 */ {"snowfall", "snowfall  (dimension", "-", UC_NONE},
    /* 129 */ {"var129", "undefined", "-", UC_NONE},
    /* 130 */ {"var130", "undefined", "-", UC_NONE},
    /* 131 */ {"var131", "undefined", "-", UC_NONE},
@@ -6290,7 +6290,7 @@ GRIB1ParmTable parm_table_dwd_203[256] = {
    /* 96 */ {"var96", "undefined", "-", UC_NONE},
    /* 97 */ {"var97", "undefined", "-", UC_NONE},
    /* 98 */ {"var98", "undefined", "-", UC_NONE},
-   /* 99 */ {"Wetter_ww", "Wetter (verschluesselt nach ww-Tabelle"},
+   /* 99 */ {"Wetter_ww", "Wetter (verschluesselt nach ww-Tabelle", "-", UC_NONE},
    /* 100 */ {"geostr_Vor", "geostrophische Vorticity", "1/s", UC_NONE},
    /* 101 */ {"Geo_VorAdv", "geostrophische  Vorticityadvektion", "1/s^2",
               UC_NONE},
@@ -6422,7 +6422,7 @@ GRIB1ParmTable parm_table_dwd_203[256] = {
               UC_NONE},
    /* 202 */ {"Lok_Wetter", "Wetter - 2. lokale Abweichung (ww", "-",
               UC_NONE},
-   /* 203 */ {"CLDEPTH", "cloud depth (grey scale"},
+   /* 203 */ {"CLDEPTH", "cloud depth (grey scale", "-", UC_NONE},
    /* 204 */ {"CLCT_MOD", "modified total cloud cover  (0..1)", "1", UC_NONE},
    /* 205 */ {"curr_weath", "current weather (symbol number", "-", UC_NONE},
    /* 206 */ {"var206", "undefined", "-", UC_NONE},
@@ -6590,7 +6590,7 @@ GRIB1ParmTable parm_table_cptec_254[256] = {
    /* 87 */ {"vege", "VEGETATION", "%", UC_NONE},
    /* 88 */ {"var88", "undefined", "-", UC_NONE},
    /* 89 */ {"dens", "DENSITY", "kg/m3", UC_NONE},
-   /* 90 */ {"var90", "Undefined"},
+   /* 90 */ {"var90", "Undefined", "-", UC_NONE},
    /* 91 */ {"icec", "ICE CONCENTRATION", "fraction", UC_NONE},
    /* 92 */ {"icet", "ICE THICKNESS", "m", UC_NONE},
    /* 93 */ {"iced", "DIRECTION OF ICE DRIFT", "deg", UC_NONE},
diff --git a/frmts/grib/degrib18/degrib/grib2api.c b/frmts/grib/degrib18/degrib/grib2api.c
index 64a2c08..9898538 100644
--- a/frmts/grib/degrib18/degrib/grib2api.c
+++ b/frmts/grib/degrib18/degrib/grib2api.c
@@ -25,6 +25,8 @@
 #include "pdstemplates.h"
 #include "drstemplates.h"
 
+#include "cpl_port.h"
+
 //#include "config.h" /*config.h created by configure - ADT mod*/
 
 /* Declare the external FORTRAN routine
@@ -131,7 +133,7 @@ static int mdl_LocalUnpack (unsigned char *local, sInt4 locallen,
    idat[0] = 0;
    rdat[0] = 0;
 
-   for (i = 0; i < numGroup; i++) {
+   for (i = 0; (unsigned int)i < numGroup; i++) {
       if (locallen < BytesUsed + 12) {
 #ifdef DEBUG
          printf ("Locallen is too small.\n");
@@ -268,7 +270,7 @@ static int fillOutSectLen (unsigned char *c_ipack, int lenCpack,
    }
    /* assert that we start with data in either section 2 or 3. */
    myAssert ((c_ipack[4] == 2) || (c_ipack[4] == 3));
-   while (gNum <= subgNum) {
+   while (gNum <= (unsigned int)subgNum) {
       if (lenCpack < offset + 5) {
 #ifdef DEBUG
          printf ("Cpack is not large enough.\n");
@@ -738,15 +740,15 @@ is required for each GRIB2 message.
  * gfld->num_coord = number of values in array gfld->coord_list[].
  *****************************************************************************
  */
-void unpk_g2ncep (sInt4 * kfildo, float * ain, sInt4 * iain, sInt4 * nd2x3,
+void unpk_g2ncep (CPL_UNUSED sInt4 * kfildo, float * ain, sInt4 * iain, sInt4 * nd2x3,
                   sInt4 * idat, sInt4 * nidat, float * rdat, sInt4 * nrdat,
-                  sInt4 * is0, sInt4 * ns0, sInt4 * is1, sInt4 * ns1,
-                  sInt4 * is2, sInt4 * ns2, sInt4 * is3, sInt4 * ns3,
-                  sInt4 * is4, sInt4 * ns4, sInt4 * is5, sInt4 * ns5,
-                  sInt4 * is6, sInt4 * ns6, sInt4 * is7, sInt4 * ns7,
+                  sInt4 * is0, CPL_UNUSED sInt4 * ns0, sInt4 * is1, CPL_UNUSED sInt4 * ns1,
+                  sInt4 * is2, sInt4 * ns2, sInt4 * is3, CPL_UNUSED sInt4 * ns3,
+                  sInt4 * is4, CPL_UNUSED sInt4 * ns4, sInt4 * is5, CPL_UNUSED sInt4 * ns5,
+                  sInt4 * is6, CPL_UNUSED sInt4 * ns6, sInt4 * is7, CPL_UNUSED sInt4 * ns7,
                   sInt4 * ib, sInt4 * ibitmap, unsigned char *c_ipack,
                   sInt4 * nd5, float * xmissp, float * xmisss,
-                  sInt4 * inew, sInt4 * iclean, sInt4 * l3264b,
+                  sInt4 * inew, sInt4 * iclean, CPL_UNUSED sInt4 * l3264b,
                   sInt4 * iendpk, sInt4 * jer, sInt4 * ndjer, sInt4 * kjer)
 {
    int i;               /* A counter used for a number of purposes. */
@@ -805,7 +807,7 @@ void unpk_g2ncep (sInt4 * kfildo, float * ain, sInt4 * iain, sInt4 * nd2x3,
          return;
       }
    } else {
-      if (subgNum + 1 >= numfields) {
+      if (subgNum + 1 >= (unsigned int)numfields) {
          /* Field request error. */
          jer[0 + *ndjer] = 2;
          *kjer = 1;
@@ -1069,7 +1071,7 @@ void unpk_g2ncep (sInt4 * kfildo, float * ain, sInt4 * iain, sInt4 * nd2x3,
    is6[5] = gfld->ibmap;
    is7[4] = 7;
 
-   if (subgNum + 1 == numfields) {
+   if ((subgNum + 1) == (unsigned int)numfields) {
       *iendpk = 1;
    } else {
       *iendpk = 0;
@@ -1380,7 +1382,7 @@ static void clear (float * ain, sInt4 * iain, sInt4 * nd2x3, sInt4 * idat,
  * NOTES
  *****************************************************************************
  */
-static void BigByteCpy (sInt4 * dst, sInt4 * ipack, sInt4 nd5,
+static void BigByteCpy (sInt4 * dst, sInt4 * ipack, CPL_UNUSED sInt4 nd5,
                         unsigned int startInt, unsigned int startByte,
                         int numByte)
 {
@@ -1453,7 +1455,7 @@ static int FindTemplateIDs (sInt4 * ipack, sInt4 nd5, int subgNum,
 
    /* Jump over section 0. */
    offset = 16;
-   while (gNum <= subgNum) {
+   while (gNum <= (unsigned int)subgNum) {
       BigByteCpy (&sectLen, ipack, nd5, (offset / 4), (offset % 4), 4);
       /* Check if we just read section 8.  If so, then it is "7777" =
        * 926365495 regardless of endian'ness. */
@@ -1987,16 +1989,26 @@ int C_pkGrib2 (unsigned char *cgrib, sInt4 *sec0, sInt4 *sec1,
  *
  *****************************************************************************
  */
-void pk_grib2 (sInt4 * kfildo, float * ain, sInt4 * iain, sInt4 * nx,
-               sInt4 * ny, sInt4 * idat, sInt4 * nidat, float * rdat,
-               sInt4 * nrdat, sInt4 * is0, sInt4 * ns0, sInt4 * is1,
-               sInt4 * ns1, sInt4 * is3, sInt4 * ns3, sInt4 * is4,
-               sInt4 * ns4, sInt4 * is5, sInt4 * ns5, sInt4 * is6,
-               sInt4 * ns6, sInt4 * is7, sInt4 * ns7, sInt4 * ib,
-               sInt4 * ibitmap, sInt4 * ipack, sInt4 * nd5, sInt4 * missp,
-               float * xmissp, sInt4 * misss, float * xmisss, sInt4 * inew,
-               sInt4 * minpk, sInt4 * iclean, sInt4 * l3264b, sInt4 * jer,
-               sInt4 * ndjer, sInt4 * kjer)
+/* TODO: Make a better ifdef */
+void pk_grib2 (CPL_UNUSED sInt4 * kfildo, CPL_UNUSED float * ain,
+               CPL_UNUSED sInt4 * iain, CPL_UNUSED sInt4 * nx,
+               CPL_UNUSED sInt4 * ny, CPL_UNUSED sInt4 * idat,
+               CPL_UNUSED sInt4 * nidat, CPL_UNUSED float * rdat,
+               CPL_UNUSED sInt4 * nrdat, CPL_UNUSED sInt4 * is0,
+               CPL_UNUSED sInt4 * ns0, CPL_UNUSED sInt4 * is1,
+               CPL_UNUSED sInt4 * ns1, CPL_UNUSED sInt4 * is3, 
+               CPL_UNUSED sInt4 * ns3, CPL_UNUSED sInt4 * is4,
+               CPL_UNUSED sInt4 * ns4, CPL_UNUSED sInt4 * is5,
+               CPL_UNUSED sInt4 * ns5, CPL_UNUSED sInt4 * is6,
+               CPL_UNUSED sInt4 * ns6, CPL_UNUSED sInt4 * is7,
+               CPL_UNUSED sInt4 * ns7, CPL_UNUSED sInt4 * ib,
+               CPL_UNUSED sInt4 * ibitmap, CPL_UNUSED sInt4 * ipack,
+               CPL_UNUSED sInt4 * nd5, CPL_UNUSED sInt4 * missp,
+               CPL_UNUSED float * xmissp, CPL_UNUSED sInt4 * misss,
+               CPL_UNUSED float * xmisss, CPL_UNUSED sInt4 * inew,
+               CPL_UNUSED sInt4 * minpk, CPL_UNUSED sInt4 * iclean,
+               CPL_UNUSED sInt4 * l3264b, CPL_UNUSED sInt4 * jer,
+               CPL_UNUSED sInt4 * ndjer, CPL_UNUSED sInt4 * kjer)
 {
 #ifndef _FORTRAN
    
diff --git a/frmts/grib/degrib18/degrib/inventory.cpp b/frmts/grib/degrib18/degrib/inventory.cpp
index 6f3a8c4..1b39d87 100644
--- a/frmts/grib/degrib18/degrib/inventory.cpp
+++ b/frmts/grib/degrib18/degrib/inventory.cpp
@@ -31,6 +31,8 @@
 #include "metaname.h"
 #include "filedatasource.h"
 
+#include "cpl_port.h"
+
 #define SECT0LEN_BYTE 16
 
 typedef union {
@@ -242,7 +244,7 @@ static int InventoryParseTime (char *is, double *AnsTime)
  *   May want to put this in degrib2.c
  *****************************************************************************
  */
-static int GRIB2SectToBuffer (DataSource &fp, uInt4 gribLen, sChar *sect,
+static int GRIB2SectToBuffer (DataSource &fp, CPL_UNUSED uInt4 gribLen, sChar *sect,
                               uInt4 *secLen, uInt4 *buffLen, char **buff)
 {
    char *buffer = *buff; /* Local ptr to buff to reduce ptr confusion. */
@@ -314,7 +316,7 @@ static int GRIB2SectToBuffer (DataSource &fp, uInt4 gribLen, sChar *sect,
  *   May want to put this in degrib2.c
  *****************************************************************************
  */
-static int GRIB2SectJump (DataSource &fp, sInt4 gribLen, sChar *sect, uInt4 *secLen)
+static int GRIB2SectJump (DataSource &fp, CPL_UNUSED sInt4 gribLen, sChar *sect, uInt4 *secLen)
 {
    char sectNum;        /* Validates that we are on the correct section. */
    int c;               /* Check that the fseek is still inside the file. */
diff --git a/frmts/grib/degrib18/degrib/metaname.cpp b/frmts/grib/degrib18/degrib/metaname.cpp
index a566210..f34c74a 100644
--- a/frmts/grib/degrib18/degrib/metaname.cpp
+++ b/frmts/grib/degrib18/degrib/metaname.cpp
@@ -21,6 +21,8 @@
 #include "myassert.h"
 #include "myutil.h"
 
+#include "cpl_port.h"
+
 const char *centerLookup (unsigned short int center)
 {
    /* see:
@@ -1483,8 +1485,8 @@ static GRIB2LocalTable *Choose_LocalParmTable (unsigned short int center,
  */
 /* Deal with probability templates 2/16/2006 */
 static void ElemNameProb (uShort2 center, uShort2 subcenter, int prodType,
-                          int templat, uChar cat, uChar subcat, sInt4 lenTime,
-                          uChar timeIncrType, uChar genID, uChar probType,
+                          CPL_UNUSED int templat, uChar cat, uChar subcat, sInt4 lenTime,
+                          uChar timeIncrType, CPL_UNUSED uChar genID, uChar probType,
                           double lowerProb, double upperProb, char **name,
                           char **comment, char **unit, int *convert)
 {
@@ -1658,7 +1660,7 @@ static void ElemNameProb (uShort2 center, uShort2 subcenter, int prodType,
 
 /* Deal with percentile templates 5/1/2006 */
 static void ElemNamePerc (uShort2 center, uShort2 subcenter, int prodType,
-                          int templat, uChar cat, uChar subcat, sInt4 lenTime,
+                          CPL_UNUSED int templat, uChar cat, uChar subcat, sInt4 lenTime,
                           sChar percentile, char **name, char **comment,
                           char **unit, int *convert)
 {
@@ -1746,8 +1748,8 @@ static void ElemNamePerc (uShort2 center, uShort2 subcenter, int prodType,
 /* Deal with non-prob templates 2/16/2006 */
 static void ElemNameNorm (uShort2 center, uShort2 subcenter, int prodType,
                           int templat, uChar cat, uChar subcat, sInt4 lenTime,
-                          uChar timeIncrType, uChar genID, uChar probType,
-                          double lowerProb, double upperProb, char **name,
+                          CPL_UNUSED uChar timeIncrType, CPL_UNUSED uChar genID, CPL_UNUSED uChar probType,
+                          CPL_UNUSED double lowerProb, CPL_UNUSED double upperProb, char **name,
                           char **comment, char **unit, int *convert)
 {
    GRIB2ParmTable *table;
@@ -2389,7 +2391,7 @@ GRIB2LocalSurface NCEP_Surface[] = {
  *****************************************************************************
  */
 GRIB2SurfTable Table45Index (int i, int *f_reserved, uShort2 center,
-                             uShort2 subcenter)
+                             CPL_UNUSED uShort2 subcenter)
 {
    size_t j;
 
diff --git a/frmts/grib/degrib18/degrib/metaparse.cpp b/frmts/grib/degrib18/degrib/metaparse.cpp
index 3657db8..ffb0b3a 100644
--- a/frmts/grib/degrib18/degrib/metaparse.cpp
+++ b/frmts/grib/degrib18/degrib/metaparse.cpp
@@ -28,6 +28,8 @@
 #include "memendian.h"
 #include "myutil.h"
 
+#include "cpl_port.h"
+
 /*****************************************************************************
  * MetaInit() --
  *
@@ -2368,7 +2370,7 @@ void ParseGrid (gridAttribType *attrib, double **Grib_Data,
                 uInt4 *grib_DataLen, uInt4 Nx, uInt4 Ny, int scan,
                 sInt4 *iain, sInt4 ibitmap, sInt4 *ib, double unitM,
                 double unitB, uChar f_wxType, sect2_WxType *WxType,
-                uChar f_subGrid, int startX, int startY, int stopX, int stopY)
+                CPL_UNUSED uChar f_subGrid, int startX, int startY, int stopX, int stopY)
 {
    double xmissp;       /* computed missing value needed for ibitmap = 1,
                          * Also used if unit conversion causes confusion
diff --git a/frmts/grib/degrib18/degrib/myutil.c b/frmts/grib/degrib18/degrib/myutil.c
index 394c0ea..d0914f8 100644
--- a/frmts/grib/degrib18/degrib/myutil.c
+++ b/frmts/grib/degrib18/degrib/myutil.c
@@ -24,6 +24,8 @@
 #include "myutil.h"
 #include "myassert.h"
 
+#include "cpl_port.h"
+
 /* Android compat */
 #ifndef S_IREAD
 #define S_IREAD S_IRUSR
@@ -456,8 +458,8 @@ static int FileMatch (const char *filename, const char *filter)
 }
 **/
 
-int myGlob (const char *dirName, const char *filter, size_t *Argc,
-            char ***Argv)
+int myGlob (CPL_UNUSED const char *dirName, CPL_UNUSED const char *filter, CPL_UNUSED size_t *Argc,
+            CPL_UNUSED char ***Argv)
 {
 return 0; // TODO: reimplement for Win32
 /*
@@ -666,7 +668,7 @@ void strTrim (char *str)
 
    /* Remove the trailing white space before working on the leading ones. */
    len = strlen (str);
-   for (i = len - 1; ((i >= 0) && (isspace ((unsigned char)str[i]))); i--) {
+   for (i = len - 1; (/* (i >= 0) && */ (isspace ((unsigned char)str[i]))); i--) {
    }
    len = i + 1;
    str[len] = '\0';
@@ -715,7 +717,7 @@ void strTrimRight (char *str, char c)
    }
 
    for (i = strlen (str) - 1;
-        ((i >= 0) && ((isspace ((unsigned char)str[i])) || (str[i] == c))); i--) {
+        (/* (i >= 0) && */ ((isspace ((unsigned char)str[i])) || (str[i] == c))); i--) {
    }
    str[i + 1] = '\0';
 }
diff --git a/frmts/grib/degrib18/degrib/tdlpack.cpp b/frmts/grib/degrib18/degrib/tdlpack.cpp
index cb31174..b0931b5 100644
--- a/frmts/grib/degrib18/degrib/tdlpack.cpp
+++ b/frmts/grib/degrib18/degrib/tdlpack.cpp
@@ -796,8 +796,8 @@ static int ReadTDLPSect2 (uChar *gds, sInt4 tdlpLen, sInt4 *curLoc,
  * NOTES
  *****************************************************************************
  */
-static int ReadTDLPSect3 (uChar *bms, sInt4 tdlpLen, sInt4 *curLoc,
-                          uChar *bitmap, sInt4 NxNy)
+static int ReadTDLPSect3 (CPL_UNUSED uChar *bms, CPL_UNUSED sInt4 tdlpLen, CPL_UNUSED sInt4 *curLoc,
+                          CPL_UNUSED uChar *bitmap, CPL_UNUSED sInt4 NxNy)
 {
    errSprintf ("Bitmap data is Not Supported\n");
    return -1;
@@ -847,7 +847,7 @@ static int ReadTDLPSect3 (uChar *bms, sInt4 tdlpLen, sInt4 *curLoc,
  */
 static int ReadTDLPSect4 (uChar *bds, sInt4 tdlpLen, sInt4 *curLoc,
                           short int DSF, short int BSF, double *data,
-                          grib_MetaData *meta, double unitM, double unitB)
+                          grib_MetaData *meta, CPL_UNUSED double unitM, CPL_UNUSED double unitB)
 {
    uInt4 sectLen;       /* Length in bytes of the current section. */
    uChar f_notGridPnt;  /* Not Grid point data? */
@@ -2862,7 +2862,7 @@ static void shiftGroup0 (sInt4 *Data, int start1, int start2, int bit,
  * NOTES
  *****************************************************************************
  */
-static void doSplit (sInt4 *Data, int numData, TDLGroupType * G,
+static void doSplit (sInt4 *Data, CPL_UNUSED int numData, TDLGroupType * G,
                      TDLGroupType ** lclGroup, int *numLclGroup,
                      char f_primMiss, sInt4 li_primMiss,
                      char f_secMiss, sInt4 li_secMiss, int xFactor)
@@ -3001,7 +3001,7 @@ static void doSplit (sInt4 *Data, int numData, TDLGroupType * G,
  * NOTES
  *****************************************************************************
  */
-static void doSplitRight (sInt4 *Data, int numData, TDLGroupType * G,
+static void doSplitRight (sInt4 *Data, CPL_UNUSED int numData, TDLGroupType * G,
                           TDLGroupType * G1, TDLGroupType * G2,
                           char f_primMiss, sInt4 li_primMiss,
                           char f_secMiss, sInt4 li_secMiss)
@@ -3355,7 +3355,7 @@ static int splitGroup (sInt4 *Data, int numData, TDLGroupType * group,
  * NOTES
  *****************************************************************************
  */
-static void shiftGroup (sInt4 *Data, int numData, TDLGroupType ** Group,
+static void shiftGroup (sInt4 *Data, CPL_UNUSED int numData, TDLGroupType ** Group,
                         size_t *NumGroup, char f_primMiss, sInt4 li_primMiss,
                         char f_secMiss, sInt4 li_secMiss, int xFactor)
 {
diff --git a/frmts/grib/degrib18/g2clib-1.0.4/enc_jpeg2000.c b/frmts/grib/degrib18/g2clib-1.0.4/enc_jpeg2000.c
index 9830dcf..9b99f26 100644
--- a/frmts/grib/degrib18/g2clib-1.0.4/enc_jpeg2000.c
+++ b/frmts/grib/degrib18/g2clib-1.0.4/enc_jpeg2000.c
@@ -1,8 +1,19 @@
 #include "grib2.h"
 #ifndef USE_JPEG2000
-int enc_jpeg2000(unsigned char *cin,g2int width,g2int height,g2int nbits,
-                 g2int ltype, g2int ratio, g2int retry, char *outjpc, 
-				 g2int jpclen){return 0;}
+
+#include "cpl_port.h"
+
+int enc_jpeg2000(CPL_UNUSED unsigned char *cin,
+                 CPL_UNUSED g2int width,
+                 CPL_UNUSED g2int height,
+                 CPL_UNUSED g2int nbits,
+                 CPL_UNUSED g2int ltype,
+                 CPL_UNUSED g2int ratio,
+                 CPL_UNUSED g2int retry,
+                 CPL_UNUSED char *outjpc, 
+                 CPL_UNUSED g2int jpclen) {
+    return 0;
+}
 #else   /* USE_JPEG2000 */
 
 #include <stdio.h>
diff --git a/frmts/grib/degrib18/g2clib-1.0.4/g2_addfield.c b/frmts/grib/degrib18/g2clib-1.0.4/g2_addfield.c
index 32813aa..632bf48 100644
--- a/frmts/grib/degrib18/g2clib-1.0.4/g2_addfield.c
+++ b/frmts/grib/degrib18/g2clib-1.0.4/g2_addfield.c
@@ -345,7 +345,7 @@ g2int g2_addfield(unsigned char *cgrib,g2int ipdsnum,g2int *ipdstmpl,
               width=ndpts;
               height=1;
            }
-           else if ( width==allones || height==allones ) {
+           else if ( (unsigned int)width==allones || (unsigned int)height==allones ) {
               width=ndpts;
               height=1;
            }
diff --git a/frmts/grib/degrib18/g2clib-1.0.4/reduce.c b/frmts/grib/degrib18/g2clib-1.0.4/reduce.c
index b1c3502..ae94949 100644
--- a/frmts/grib/degrib18/g2clib-1.0.4/reduce.c
+++ b/frmts/grib/degrib18/g2clib-1.0.4/reduce.c
@@ -13,10 +13,13 @@
 /*#include "f2c.h"*/
 #include <stdlib.h>
 #include "grib2.h"
+
+#include "cpl_port.h"
+
 typedef g2int integer;
 typedef g2float real;
 
-/* Subroutine */ int reduce(integer *kfildo, integer *jmin, integer *jmax, 
+/* Subroutine */ int reduce(CPL_UNUSED integer *kfildo, integer *jmin, integer *jmax, 
 	integer *lbit, integer *nov, integer *lx, integer *ndg, integer *ibit,
 	 integer *jbit, integer *kbit, integer *novref, integer *ibxx2, 
 	integer *ier)
diff --git a/frmts/grib/gribdataset.cpp b/frmts/grib/gribdataset.cpp
index d2d3871..ead99fb 100644
--- a/frmts/grib/gribdataset.cpp
+++ b/frmts/grib/gribdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gribdataset.cpp 27116 2014-04-02 19:29:50Z rouault $
+ * $Id: gribdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GRIB Driver
  * Purpose:  GDALDataset driver for GRIB translator for read support
@@ -41,7 +41,7 @@
 
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: gribdataset.cpp 27116 2014-04-02 19:29:50Z rouault $");
+CPL_CVSID("$Id: gribdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_GRIB(void);
@@ -339,7 +339,7 @@ CPLErr GRIBRasterBand::LoadData()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GRIBRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr GRIBRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                    void * pImage )
 
 {
@@ -858,12 +858,17 @@ void GRIBDataset::SetGribMetaData(grib_MetaData* meta)
           rMinY = meta->gds.lat1;
         }
 
-        if (meta->gds.lon1 > meta->gds.lon2)
+        if( meta->gds.Nx == 1 )
+          rPixelSizeX = meta->gds.Dx;
+        else if (meta->gds.lon1 > meta->gds.lon2)
           rPixelSizeX = (360.0 - (meta->gds.lon1 - meta->gds.lon2)) / (meta->gds.Nx - 1);
         else
           rPixelSizeX = (meta->gds.lon2 - meta->gds.lon1) / (meta->gds.Nx - 1);
 
-        rPixelSizeY = (rMaxY - rMinY) / (meta->gds.Ny - 1);
+        if( meta->gds.Ny == 1 )
+            rPixelSizeY = meta->gds.Dy;
+        else
+            rPixelSizeY = (rMaxY - rMinY) / (meta->gds.Ny - 1);
 
         // Do some sanity checks for cases that can't be handled by the above
         // pixel size corrections. GRIB1 has a minimum precision of 0.001
diff --git a/frmts/gsg/gs7bgdataset.cpp b/frmts/gsg/gs7bgdataset.cpp
index 08fb04f..79167d0 100644
--- a/frmts/gsg/gs7bgdataset.cpp
+++ b/frmts/gsg/gs7bgdataset.cpp
@@ -1,5 +1,5 @@
 /****************************************************************************
- * $Id: gs7bgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gs7bgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Implements the Golden Software Surfer 7 Binary Grid Format.
@@ -61,7 +61,7 @@
 # define SHRT_MAX 32767
 #endif /* SHRT_MAX */
 
-CPL_CVSID("$Id: gs7bgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gs7bgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_GS7BG(void);
@@ -120,7 +120,9 @@ size_t GS7BGDataset::nData_Position = 0;
 const long  nHEADER_TAG = 0x42525344;
 const long  nGRID_TAG = 0x44495247;
 const long  nDATA_TAG = 0x41544144;
+#if 0 /* Unused */
 const long  nFAULT_TAG = 0x49544c46;
+#endif
 
 /************************************************************************/
 /* ==================================================================== */
@@ -1104,9 +1106,9 @@ CPLErr GS7BGDataset::WriteHeader( VSILFILE *fp, GInt32 nXSize, GInt32 nYSize,
 /************************************************************************/
 
 GDALDataset *GS7BGDataset::Create( const char * pszFilename,
-                  int nXSize, int nYSize, int nBands,
-                  GDALDataType eType,
-                  char **papszParmList )
+                                   int nXSize, int nYSize, int nBands,
+                                   GDALDataType eType,
+                                   CPL_UNUSED char **papszParmList )
 
 {
     if( nXSize <= 0 || nYSize <= 0 )
@@ -1181,10 +1183,10 @@ GDALDataset *GS7BGDataset::Create( const char * pszFilename,
 /************************************************************************/
 
 GDALDataset *GS7BGDataset::CreateCopy( const char *pszFilename,
-                      GDALDataset *poSrcDS,
-                      int bStrict, char **papszOptions,
-                      GDALProgressFunc pfnProgress,
-                      void *pProgressData )
+                                       GDALDataset *poSrcDS,
+                                       int bStrict, CPL_UNUSED char **papszOptions,
+                                       GDALProgressFunc pfnProgress,
+                                       void *pProgressData )
 {
     if( pfnProgress == NULL )
         pfnProgress = GDALDummyProgress;
diff --git a/frmts/gsg/gsagdataset.cpp b/frmts/gsg/gsagdataset.cpp
index 2933c9b..f572a0e 100644
--- a/frmts/gsg/gsagdataset.cpp
+++ b/frmts/gsg/gsagdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gsagdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gsagdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Implements the Golden Software ASCII Grid Format.
@@ -50,7 +50,7 @@
 # define INT_MAX 2147483647
 #endif /* INT_MAX */
 
-CPL_CVSID("$Id: gsagdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gsagdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_GSAG(void);
@@ -1192,8 +1192,9 @@ CPLErr GSAGDataset::ShiftFileContents( VSILFILE *fp, vsi_l_offset nShiftStart,
 	return CE_None;
 
     /* make sure start location is sane */
-    if( nShiftStart < 0
-	|| (nShiftSize < 0
+/* Tautology is always false.  nShiftStart is unsigned. */
+    if( /* nShiftStart < 0
+           || */ (nShiftSize < 0
 	    && nShiftStart < static_cast<vsi_l_offset>(-nShiftSize)) )
 	nShiftStart = (nShiftSize > 0) ? 0 : -nShiftSize;
 
@@ -1504,7 +1505,7 @@ CPLErr GSAGDataset::UpdateHeader()
 
 GDALDataset *GSAGDataset::CreateCopy( const char *pszFilename,
 				      GDALDataset *poSrcDS,
-				      int bStrict, char **papszOptions,
+				      int bStrict, CPL_UNUSED char **papszOptions,
 				      GDALProgressFunc pfnProgress,
 				      void *pProgressData )
 {
diff --git a/frmts/gsg/gsbgdataset.cpp b/frmts/gsg/gsbgdataset.cpp
index be20cb0..0393e7e 100644
--- a/frmts/gsg/gsbgdataset.cpp
+++ b/frmts/gsg/gsbgdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gsbgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gsbgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL
  * Purpose:  Implements the Golden Software Binary Grid Format.
@@ -61,7 +61,7 @@
 # define SHRT_MAX 32767
 #endif /* SHRT_MAX */
 
-CPL_CVSID("$Id: gsbgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gsbgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_GSBG(void);
@@ -880,9 +880,9 @@ CPLErr GSBGDataset::WriteHeader( VSILFILE *fp, GInt16 nXSize, GInt16 nYSize,
 /************************************************************************/
 
 GDALDataset *GSBGDataset::Create( const char * pszFilename,
-				  int nXSize, int nYSize, int nBands,
+				  int nXSize, int nYSize, CPL_UNUSED int nBands,
 				  GDALDataType eType,
-				  char **papszParmList )
+				  CPL_UNUSED char **papszParmList )
 
 {
     if( nXSize <= 0 || nYSize <= 0 )
@@ -960,7 +960,7 @@ GDALDataset *GSBGDataset::Create( const char * pszFilename,
 
 GDALDataset *GSBGDataset::CreateCopy( const char *pszFilename,
 				      GDALDataset *poSrcDS,
-				      int bStrict, char **papszOptions,
+				      int bStrict, CPL_UNUSED char **papszOptions,
 				      GDALProgressFunc pfnProgress,
 				      void *pProgressData )
 {
diff --git a/frmts/gtiff/geotiff.cpp b/frmts/gtiff/geotiff.cpp
index e7eafa5..5d9f850 100644
--- a/frmts/gtiff/geotiff.cpp
+++ b/frmts/gtiff/geotiff.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: geotiff.cpp 27107 2014-03-28 20:22:20Z rouault $
+ * $Id: geotiff.cpp 27607 2014-08-27 12:54:43Z rouault $
  *
  * Project:  GeoTIFF Driver
  * Purpose:  GDAL GeoTIFF support.
@@ -60,12 +60,42 @@
 #include "tiffiop.h"
 #endif
 
-CPL_CVSID("$Id: geotiff.cpp 27107 2014-03-28 20:22:20Z rouault $");
+CPL_CVSID("$Id: geotiff.cpp 27607 2014-08-27 12:54:43Z rouault $");
 
 #if SIZEOF_VOIDP == 4
 static int bGlobalStripIntegerOverflow = FALSE;
 #endif
 
+typedef enum
+{
+    GTIFFTAGTYPE_STRING,
+    GTIFFTAGTYPE_SHORT,
+    GTIFFTAGTYPE_FLOAT
+} GTIFFTagTypes;
+
+typedef struct
+{
+    const char    *pszTagName;
+    int            nTagVal;
+    GTIFFTagTypes  eType;
+} GTIFFTags;
+
+static const GTIFFTags asTIFFTags[] =
+{
+    { "TIFFTAG_DOCUMENTNAME", TIFFTAG_DOCUMENTNAME, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_IMAGEDESCRIPTION", TIFFTAG_IMAGEDESCRIPTION, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_SOFTWARE", TIFFTAG_SOFTWARE, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_DATETIME", TIFFTAG_DATETIME, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_ARTIST", TIFFTAG_ARTIST, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_HOSTCOMPUTER", TIFFTAG_HOSTCOMPUTER, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_COPYRIGHT", TIFFTAG_COPYRIGHT, GTIFFTAGTYPE_STRING },
+    { "TIFFTAG_XRESOLUTION", TIFFTAG_XRESOLUTION, GTIFFTAGTYPE_FLOAT },
+    { "TIFFTAG_YRESOLUTION", TIFFTAG_YRESOLUTION, GTIFFTAGTYPE_FLOAT },
+    { "TIFFTAG_RESOLUTIONUNIT", TIFFTAG_RESOLUTIONUNIT, GTIFFTAGTYPE_SHORT }, /* dealt as special case */
+    { "TIFFTAG_MINSAMPLEVALUE", TIFFTAG_MINSAMPLEVALUE, GTIFFTAGTYPE_SHORT },
+    { "TIFFTAG_MAXSAMPLEVALUE", TIFFTAG_MAXSAMPLEVALUE, GTIFFTAGTYPE_SHORT },
+};
+
 /************************************************************************/
 /* ==================================================================== */
 /*                                GDALOverviewDS                        */
@@ -1852,7 +1882,7 @@ CPLErr GTiffRasterBand::SetMetadata( char ** papszMD, const char *pszDomain )
 {
     if( pszDomain == NULL || !EQUAL(pszDomain,"_temporary_") )
     {
-        if( papszMD != NULL )
+        if( papszMD != NULL || GetMetadata(pszDomain) != NULL )
             poGDS->bMetadataChanged = TRUE;
     }
 
@@ -5597,39 +5627,37 @@ static void WriteMDMetadata( GDALMultiDomainMetadata *poMDMD, TIFF *hTIFF,
             if( strlen(papszDomainList[iDomain]) == 0
                 && nBand == 0 && EQUALN(pszItemName,"TIFFTAG_",8) )
             {
-                if( EQUAL(pszItemName,"TIFFTAG_DOCUMENTNAME") )
-                    TIFFSetField( hTIFF, TIFFTAG_DOCUMENTNAME, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_IMAGEDESCRIPTION") )
-                    TIFFSetField( hTIFF, TIFFTAG_IMAGEDESCRIPTION, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_SOFTWARE") )
-                    TIFFSetField( hTIFF, TIFFTAG_SOFTWARE, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_DATETIME") )
-                    TIFFSetField( hTIFF, TIFFTAG_DATETIME, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_ARTIST") )
-                    TIFFSetField( hTIFF, TIFFTAG_ARTIST, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_HOSTCOMPUTER") )
-                    TIFFSetField( hTIFF, TIFFTAG_HOSTCOMPUTER, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_COPYRIGHT") )
-                    TIFFSetField( hTIFF, TIFFTAG_COPYRIGHT, pszItemValue );
-                else if( EQUAL(pszItemName,"TIFFTAG_XRESOLUTION") )
-                    TIFFSetField( hTIFF, TIFFTAG_XRESOLUTION, CPLAtof(pszItemValue) );
-                else if( EQUAL(pszItemName,"TIFFTAG_YRESOLUTION") )
-                    TIFFSetField( hTIFF, TIFFTAG_YRESOLUTION, CPLAtof(pszItemValue) );
-                else if( EQUAL(pszItemName,"TIFFTAG_RESOLUTIONUNIT") ) {
+                if( EQUAL(pszItemName,"TIFFTAG_RESOLUTIONUNIT") ) {
                     /* ResolutionUnit can't be 0, which is the default if atoi() fails.
                        Set to 1=Unknown */
                     int v = atoi(pszItemValue);
                     if (!v) v = RESUNIT_NONE;
                     TIFFSetField( hTIFF, TIFFTAG_RESOLUTIONUNIT, v);
                 }
-                else if( EQUAL(pszItemName,"TIFFTAG_MINSAMPLEVALUE") )
-                    TIFFSetField( hTIFF, TIFFTAG_MINSAMPLEVALUE, atoi(pszItemValue) );
-                else if( EQUAL(pszItemName,"TIFFTAG_MAXSAMPLEVALUE") )
-                    TIFFSetField( hTIFF, TIFFTAG_MAXSAMPLEVALUE, atoi(pszItemValue) );
                 else
-                    CPLError(CE_Warning, CPLE_NotSupported,
-                             "%s metadata item is unhandled and will not be written",
-                             pszItemName);
+                {
+                    int bFoundTag = FALSE;
+                    size_t iTag;
+                    for(iTag=0;iTag<sizeof(asTIFFTags)/sizeof(asTIFFTags[0]);iTag++)
+                    {
+                        if( EQUAL(pszItemName, asTIFFTags[iTag].pszTagName) )
+                        {
+                            bFoundTag = TRUE;
+                            break;
+                        }
+                    }
+
+                    if( bFoundTag && asTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING )
+                        TIFFSetField( hTIFF, asTIFFTags[iTag].nTagVal, pszItemValue );
+                    else if( bFoundTag && asTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT )
+                        TIFFSetField( hTIFF, asTIFFTags[iTag].nTagVal, CPLAtof(pszItemValue) );
+                    else if( bFoundTag && asTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT )
+                        TIFFSetField( hTIFF, asTIFFTags[iTag].nTagVal, atoi(pszItemValue) );
+                    else
+                        CPLError(CE_Warning, CPLE_NotSupported,
+                                "%s metadata item is unhandled and will not be written",
+                                pszItemName);
+                }
             }
             else if( nBand == 0 && EQUAL(pszItemName,GDALMD_AREA_OR_POINT) )
                 /* do nothing, handled elsewhere */;
@@ -5640,6 +5668,37 @@ static void WriteMDMetadata( GDALMultiDomainMetadata *poMDMD, TIFF *hTIFF,
 
             CPLFree( pszItemName );
         }
+
+/* -------------------------------------------------------------------- */
+/*      Remove TIFFTAG_xxxxxx that are already set but no longer in     */
+/*      the metadata list (#5619)                                       */
+/* -------------------------------------------------------------------- */
+        if( strlen(papszDomainList[iDomain]) == 0 && nBand == 0 )
+        {
+            size_t iTag;
+            for(iTag=0;iTag<sizeof(asTIFFTags)/sizeof(asTIFFTags[0]);iTag++)
+            {
+                char* pszText = NULL;
+                int16 nVal = 0;
+                float fVal = 0.0f;
+                const char* pszVal = CSLFetchNameValue(papszMD, asTIFFTags[iTag].pszTagName);
+                if( pszVal == NULL &&
+                    ((asTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING && TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &pszText )) ||
+                     (asTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT && TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &nVal )) ||
+                     (asTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT && TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &fVal ))) )
+                {
+#ifdef HAVE_UNSETFIELD
+                    TIFFUnsetField( hTIFF, asTIFFTags[iTag].nTagVal );
+#else
+                    if( asTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING )
+                    {
+                        TIFFSetField( hTIFF, asTIFFTags[iTag].nTagVal, "" );
+                    }
+#endif
+                }
+            }
+        }
+
     }
 }
 
@@ -7628,52 +7687,34 @@ CPLErr GTiffDataset::OpenOffset( TIFF *hTIFFIn,
 /*      Capture some other potentially interesting information.         */
 /* -------------------------------------------------------------------- */
     char	*pszText, szWorkMDI[200];
-    float   fResolution;
     uint16  nShort;
 
-    if( TIFFGetField( hTIFF, TIFFTAG_DOCUMENTNAME, &pszText ) )
-        SetMetadataItem( "TIFFTAG_DOCUMENTNAME",  pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_IMAGEDESCRIPTION, &pszText ) )
-        SetMetadataItem( "TIFFTAG_IMAGEDESCRIPTION", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_SOFTWARE, &pszText ) )
-        SetMetadataItem( "TIFFTAG_SOFTWARE", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_DATETIME, &pszText ) )
-        SetMetadataItem( "TIFFTAG_DATETIME", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_ARTIST, &pszText ) )
-        SetMetadataItem( "TIFFTAG_ARTIST", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_HOSTCOMPUTER, &pszText ) )
-        SetMetadataItem( "TIFFTAG_HOSTCOMPUTER", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_COPYRIGHT, &pszText ) )
-        SetMetadataItem( "TIFFTAG_COPYRIGHT", pszText );
-
-    if( TIFFGetField( hTIFF, TIFFTAG_XRESOLUTION, &fResolution ) )
-    {
-        sprintf( szWorkMDI, "%.8g", fResolution );
-        SetMetadataItem( "TIFFTAG_XRESOLUTION", szWorkMDI );
-    }
-
-    if( TIFFGetField( hTIFF, TIFFTAG_YRESOLUTION, &fResolution ) )
-    {
-        sprintf( szWorkMDI, "%.8g", fResolution );
-        SetMetadataItem( "TIFFTAG_YRESOLUTION", szWorkMDI );
-    }
-
-    if( TIFFGetField( hTIFF, TIFFTAG_MINSAMPLEVALUE, &nShort ) )
+    size_t iTag;
+    for(iTag=0;iTag<sizeof(asTIFFTags)/sizeof(asTIFFTags[0]);iTag++)
     {
-        sprintf( szWorkMDI, "%d", nShort );
-        SetMetadataItem( "TIFFTAG_MINSAMPLEVALUE", szWorkMDI );
-    }
-
-    if( TIFFGetField( hTIFF, TIFFTAG_MAXSAMPLEVALUE, &nShort ) )
-    {
-        sprintf( szWorkMDI, "%d", nShort );
-        SetMetadataItem( "TIFFTAG_MAXSAMPLEVALUE", szWorkMDI );
+        if( asTIFFTags[iTag].eType == GTIFFTAGTYPE_STRING )
+        {
+            if( TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &pszText ) )
+                SetMetadataItem( asTIFFTags[iTag].pszTagName,  pszText );
+        }
+        else if( asTIFFTags[iTag].eType == GTIFFTAGTYPE_FLOAT )
+        {
+            float   fVal;
+            if( TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &fVal ) )
+            {
+                sprintf( szWorkMDI, "%.8g", fVal );
+                SetMetadataItem( asTIFFTags[iTag].pszTagName, szWorkMDI );
+            }
+        }
+        else if( asTIFFTags[iTag].eType == GTIFFTAGTYPE_SHORT &&
+                 asTIFFTags[iTag].nTagVal != TIFFTAG_RESOLUTIONUNIT )
+        {
+            if( TIFFGetField( hTIFF, asTIFFTags[iTag].nTagVal, &nShort ) )
+            {
+                sprintf( szWorkMDI, "%d", nShort );
+                SetMetadataItem( asTIFFTags[iTag].pszTagName, szWorkMDI );
+            }
+        }
     }
 
     if( TIFFGetField( hTIFF, TIFFTAG_RESOLUTIONUNIT, &nShort ) )
diff --git a/frmts/gtiff/gt_jpeg_copy.cpp b/frmts/gtiff/gt_jpeg_copy.cpp
index 5b11e18..339ba69 100644
--- a/frmts/gtiff/gt_jpeg_copy.cpp
+++ b/frmts/gtiff/gt_jpeg_copy.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gt_jpeg_copy.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gt_jpeg_copy.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GeoTIFF Driver
  * Purpose:  Specialized copy of JPEG content into TIFF.
@@ -33,7 +33,7 @@
 /* Note: JPEG_DIRECT_COPY is not defined by default, because it is mainly */
 /* usefull for debugging purposes */
 
-CPL_CVSID("$Id: gt_jpeg_copy.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gt_jpeg_copy.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #if defined(JPEG_DIRECT_COPY) || defined(HAVE_LIBJPEG)
 
@@ -469,7 +469,7 @@ CPLErr GTIFF_CopyFromJPEG_WriteAdditionalTags(TIFF* hTIFF,
 static CPLErr GTIFF_CopyBlockFromJPEG(TIFF* hTIFF,
                                       jpeg_decompress_struct& sDInfo,
                                       int iX, int iY,
-                                      int nXBlocks, int nYBlocks,
+                                      int nXBlocks, CPL_UNUSED int nYBlocks,
                                       int nXSize, int nYSize,
                                       int nBlockXSize, int nBlockYSize,
                                       int iMCU_sample_width, int iMCU_sample_height,
diff --git a/frmts/gtiff/libgeotiff/geo_print.c b/frmts/gtiff/libgeotiff/geo_print.c
index 9b22db5..6c7f37f 100644
--- a/frmts/gtiff/libgeotiff/geo_print.c
+++ b/frmts/gtiff/libgeotiff/geo_print.c
@@ -180,7 +180,7 @@ static void PrintKey(GeoKey *key, GTIFPrintMethod print, void *aux)
                   message[out_char++] = ch;
 
               /* flush message if buffer full */
-              if( out_char >= sizeof(message)-3 )
+              if( (size_t)out_char >= sizeof(message)-3 )
               {
                   message[out_char] = '\0';
                   print(message,aux);
diff --git a/frmts/gtiff/libgeotiff/geo_set.c b/frmts/gtiff/libgeotiff/geo_set.c
index b6f7ff8..3b2066e 100644
--- a/frmts/gtiff/libgeotiff/geo_set.c
+++ b/frmts/gtiff/libgeotiff/geo_set.c
@@ -160,8 +160,9 @@ int GTIFKeySet(GTIF *gtif, geokey_t keyID, tagtype_t type, int count,...)
         key->gk_type = type;
         key->gk_count = count;
         key->gk_size = _gtiff_size[ type ];
-        if (gtif->gt_keymin > keyID)  gtif->gt_keymin=keyID;
-        if (gtif->gt_keymax < keyID)  gtif->gt_keymax=keyID;
+        /* TODO: Make sure that the following two casts are safe. */
+        if ((geokey_t)gtif->gt_keymin > keyID) gtif->gt_keymin=keyID;
+        if ((geokey_t)gtif->gt_keymax < keyID) gtif->gt_keymax=keyID;
         newvalues = 1;
     }
 
diff --git a/frmts/gtiff/libtiff/tif_jpeg.c b/frmts/gtiff/libtiff/tif_jpeg.c
index b61b91b..a454597 100644
--- a/frmts/gtiff/libtiff/tif_jpeg.c
+++ b/frmts/gtiff/libtiff/tif_jpeg.c
@@ -729,6 +729,7 @@ JPEGFixupTagsSubsampling(TIFF* tif)
         _TIFFFillStriles( tif );
         
         if( tif->tif_dir.td_stripbytecount == NULL
+            || tif->tif_dir.td_stripoffset == NULL
             || tif->tif_dir.td_stripbytecount[0] == 0 )
         {
             /* Do not even try to check if the first strip/tile does not
diff --git a/frmts/gxf/gxfdataset.cpp b/frmts/gxf/gxfdataset.cpp
index 0f1d76e..823d8fa 100644
--- a/frmts/gxf/gxfdataset.cpp
+++ b/frmts/gxf/gxfdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gxfdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gxfdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GXF Reader
  * Purpose:  GDAL binding for GXF reader.
@@ -31,7 +31,7 @@
 #include "gxfopen.h"
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: gxfdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gxfdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #ifndef PI
 #  define PI 3.14159265358979323846
@@ -124,7 +124,7 @@ double GXFRasterBand::GetNoDataValue(int* bGotNoDataValue)
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GXFRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr GXFRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
diff --git a/frmts/hdf5/bagdataset.cpp b/frmts/hdf5/bagdataset.cpp
index 1013f93..8e6839c 100644
--- a/frmts/hdf5/bagdataset.cpp
+++ b/frmts/hdf5/bagdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: bagdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: bagdataset.cpp 27394 2014-05-24 16:37:41Z rouault $
  *
  * Project:  Hierarchical Data Format Release 5 (HDF5)
  * Purpose:  Read BAG datasets.
@@ -35,7 +35,7 @@
 #include "ogr_spatialref.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: bagdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: bagdataset.cpp 27394 2014-05-24 16:37:41Z rouault $");
 
 CPL_C_START
 void    GDALRegister_BAG(void);
@@ -229,7 +229,12 @@ bool BAGRasterBand::Initialize( hid_t hDatasetID, const char *pszName )
                                     dfMaximum ) 
              && GH5_FetchAttribute( hDatasetID, "Minimum Uncertainty Value", 
                                     dfMinimum ) )
-        bMinMaxSet = true;
+    {
+        /* Some products where uncertainty band is completely set to nodata */
+        /* wrongly declare minimum and maximum to 0.0 */
+        if( dfMinimum != 0.0 && dfMaximum != 0.0 )
+            bMinMaxSet = true;
+    }
     else if( EQUAL(pszName,"nominal_elevation") 
              && GH5_FetchAttribute( hDatasetID, "max_value", 
                                     dfMaximum ) 
@@ -286,7 +291,7 @@ double BAGRasterBand::GetNoDataValue( int * pbSuccess )
     if( EQUAL(GetDescription(),"elevation") )
         return  1000000.0;
     else if( EQUAL(GetDescription(),"uncertainty") )
-        return 0.0;
+        return 1000000.0;
     else if( EQUAL(GetDescription(),"nominal_elevation") )
         return 1000000.0;
     else
@@ -560,7 +565,7 @@ GDALDataset *BAGDataset::Open( GDALOpenInfo * poOpenInfo )
         delete poUBand;
 
 /* -------------------------------------------------------------------- */
-/*      Try to do the same for the uncertainty band.                    */
+/*      Try to do the same for the nominal_elevation band.              */
 /* -------------------------------------------------------------------- */
     hid_t hNominal = -1;
 
diff --git a/frmts/hfa/hfadataset.cpp b/frmts/hfa/hfadataset.cpp
index 270b85b..245e53f 100644
--- a/frmts/hfa/hfadataset.cpp
+++ b/frmts/hfa/hfadataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hfadataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hfadataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Name:     hfadataset.cpp
  * Project:  Erdas Imagine Driver
@@ -34,7 +34,7 @@
 #include "hfa_p.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: hfadataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hfadataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_HFA(void);
@@ -3048,7 +3048,7 @@ GDALRasterAttributeTable *HFARasterBand::GetDefaultRAT()
 /*                            WriteNamedRAT()                            */
 /************************************************************************/
  
-CPLErr HFARasterBand::WriteNamedRAT( const char *pszName, const GDALRasterAttributeTable *poRAT )
+CPLErr HFARasterBand::WriteNamedRAT( CPL_UNUSED const char *pszName, const GDALRasterAttributeTable *poRAT )
 {
 /* -------------------------------------------------------------------- */
 /*      Find the requested table.                                       */
@@ -4613,11 +4613,10 @@ HFAPCSStructToWKT( const Eprj_Datum *psDatum,
         break;
 
       case EPRJ_HOTINE_OBLIQUE_MERCATOR_AZIMUTH_CENTER:
-        if( psPro->proParams[12] > 0.0 )
-            oSRS.SetHOMAC( psPro->proParams[5]*R2D, psPro->proParams[4]*R2D,
-                           psPro->proParams[3]*R2D, 0.0,
-                           psPro->proParams[2],
-                           psPro->proParams[6], psPro->proParams[7] );
+        oSRS.SetHOMAC( psPro->proParams[5]*R2D, psPro->proParams[4]*R2D,
+                        psPro->proParams[3]*R2D, 0.0,
+                        psPro->proParams[2],
+                        psPro->proParams[6], psPro->proParams[7] );
         break;
 
       case EPRJ_ROBINSON:
@@ -5816,7 +5815,7 @@ CPLErr HFADataset::CopyFiles( const char *pszNewName, const char *pszOldName )
 
 GDALDataset *
 HFADataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
-                        int bStrict, char ** papszOptions,
+                        CPL_UNUSED int bStrict, char ** papszOptions,
                         GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/hfa/hfaentry.cpp b/frmts/hfa/hfaentry.cpp
index 54bab8e..4a535fd 100644
--- a/frmts/hfa/hfaentry.cpp
+++ b/frmts/hfa/hfaentry.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hfaentry.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hfaentry.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Erdas Imagine (.img) Translator
  * Purpose:  Implementation of the HFAEntry class for reading and relating
@@ -38,7 +38,7 @@
 #include "hfa_p.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: hfaentry.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hfaentry.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                              HFAEntry()                              */
@@ -252,8 +252,8 @@ HFAEntry* HFAEntry::BuildEntryFromMIFObject( HFAEntry *poContainer, const char *
 /*      Create a pseudo-HFAEntry wrapping a MIFObject.                  */
 /************************************************************************/
 
-HFAEntry::HFAEntry( HFAEntry * poContainer,
-                    const char *pszMIFObjectPath,
+HFAEntry::HFAEntry( CPL_UNUSED HFAEntry * poContainer,
+                    CPL_UNUSED const char *pszMIFObjectPath,
                     const char * pszDictionnary, 
                     const char * pszTypeName,
                     int nDataSizeIn,
@@ -710,7 +710,7 @@ int HFAEntry::GetFieldValue( const char * pszFieldPath,
 /*                           GetFieldCount()                            */
 /************************************************************************/
 
-int HFAEntry::GetFieldCount( const char * pszFieldPath, CPLErr *peErr )
+int HFAEntry::GetFieldCount( const char * pszFieldPath, CPL_UNUSED CPLErr *peErr )
 
 {
     HFAEntry	*poEntry = this;
diff --git a/frmts/hfa/hfaopen.cpp b/frmts/hfa/hfaopen.cpp
index 0b2fb9a..ad0ac9d 100644
--- a/frmts/hfa/hfaopen.cpp
+++ b/frmts/hfa/hfaopen.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hfaopen.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hfaopen.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Erdas Imagine (.img) Translator
  * Purpose:  Supporting functions for HFA (.img) ... main (C callable) API
@@ -42,7 +42,7 @@
 #include <limits.h>
 #include <vector>
 
-CPL_CVSID("$Id: hfaopen.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hfaopen.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 
 static const char *apszAuxMetadataItems[] = {
@@ -2041,7 +2041,7 @@ HFACreateLayer( HFAHandle psInfo, HFAEntry *poParent,
                 int bCreateCompressed, int bCreateLargeRaster, 
                 int bDependentLayer,
                 int nXSize, int nYSize, int nDataType, 
-                char **papszOptions,
+                CPL_UNUSED char **papszOptions,
                 
                 // these are only related to external (large) files
                 GIntBig nStackValidFlagsOffset, 
diff --git a/frmts/hfa/hfatype.cpp b/frmts/hfa/hfatype.cpp
index bbcd51f..08a89a5 100644
--- a/frmts/hfa/hfatype.cpp
+++ b/frmts/hfa/hfatype.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hfatype.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hfatype.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Erdas Imagine (.img) Translator
  * Purpose:  Implementation of the HFAType class, for managing one type
@@ -31,7 +31,7 @@
 
 #include "hfa_p.h"
 
-CPL_CVSID("$Id: hfatype.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hfatype.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -285,7 +285,7 @@ HFAType::SetInstValue( const char * pszFieldPath,
 
 int
 HFAType::GetInstCount( const char * pszFieldPath,
-                       GByte *pabyData, GUInt32 nDataOffset, int nDataSize )
+                       GByte *pabyData, CPL_UNUSED GUInt32 nDataOffset, int nDataSize )
 
 {
     int		nArrayIndex = 0, nNameLen, iField, nByteOffset;
diff --git a/frmts/ingr/GNUmakefile b/frmts/ingr/GNUmakefile
index 4b20c83..0f3f061 100644
--- a/frmts/ingr/GNUmakefile
+++ b/frmts/ingr/GNUmakefile
@@ -10,7 +10,7 @@ ifeq ($(TIFF_SETTING),internal)
 ifeq ($(RENAME_INTERNAL_LIBTIFF_SYMBOLS),yes)
 CPPFLAGS 	:=	$(CPPFLAGS) -DRENAME_INTERNAL_LIBTIFF_SYMBOLS
 endif
-CPPFLAGS	:=	$(CPPFLAGS) -I../gtiff/libtiff
+CPPFLAGS	:=	-I../gtiff/libtiff $(CPPFLAGS)
 endif
 
 default:	$(OBJ:.o=.$(OBJ_EXT))
diff --git a/frmts/ingr/JpegHelper.cpp b/frmts/ingr/JpegHelper.cpp
index 0dd0fc2..218321a 100644
--- a/frmts/ingr/JpegHelper.cpp
+++ b/frmts/ingr/JpegHelper.cpp
@@ -145,7 +145,7 @@ int JPGHLP_HeaderMaker( GByte *pabyBuffer,
                         const int nCols, 
                         const int nRows, 
                         const int nComponents, 
-                        const int nRestart,
+                        CPL_UNUSED const int nRestart,
                         const int nQuality )
 {
     int i;
diff --git a/frmts/iris/irisdataset.cpp b/frmts/iris/irisdataset.cpp
index 54e7c5f..e8fa7f2 100644
--- a/frmts/iris/irisdataset.cpp
+++ b/frmts/iris/irisdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: irisdataset.cpp 27141 2014-04-09 09:00:05Z rouault $
+ * $Id: irisdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  IRIS Reader
  * Purpose:  All code for IRIS format Reader
@@ -43,7 +43,7 @@
 #include <sstream>
 
 
-CPL_CVSID("$Id: irisdataset.cpp 27141 2014-04-09 09:00:05Z rouault $");
+CPL_CVSID("$Id: irisdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_IRIS(void);
@@ -189,7 +189,7 @@ IRISRasterBand::~IRISRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr IRISRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr IRISRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                    void * pImage )
 
 {
diff --git a/frmts/jaxapalsar/jaxapalsardataset.cpp b/frmts/jaxapalsar/jaxapalsardataset.cpp
index 96d507e..9a3aaec 100644
--- a/frmts/jaxapalsar/jaxapalsardataset.cpp
+++ b/frmts/jaxapalsar/jaxapalsardataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: jaxapalsardataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: jaxapalsardataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PALSAR JAXA imagery reader
  * Purpose:  Support for PALSAR L1.1/1.5 imagery and appropriate metadata from
@@ -32,7 +32,7 @@
 
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: jaxapalsardataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: jaxapalsardataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_PALSARJaxa(void);
@@ -298,7 +298,7 @@ PALSARJaxaRasterBand::~PALSARJaxaRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr PALSARJaxaRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr PALSARJaxaRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
 	void *pImage )
 {
     int nNumBytes = 0;
diff --git a/frmts/jdem/jdemdataset.cpp b/frmts/jdem/jdemdataset.cpp
index abe0970..dd38799 100644
--- a/frmts/jdem/jdemdataset.cpp
+++ b/frmts/jdem/jdemdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: jdemdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: jdemdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  JDEM Reader
  * Purpose:  All code for Japanese DEM Reader
@@ -30,7 +30,7 @@
 
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: jdemdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: jdemdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_JDEM(void);
@@ -157,12 +157,10 @@ JDEMRasterBand::~JDEMRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr JDEMRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr JDEMRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
-
 {
     JDEMDataset *poGDS = (JDEMDataset *) poDS;
-    int		i;
     
     if (pszRecord == NULL)
     {
@@ -199,7 +197,7 @@ CPLErr JDEMRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
         return CE_Failure;
     }
 
-    for( i = 0; i < nBlockXSize; i++ )
+    for( int i = 0; i < nBlockXSize; i++ )
         ((float *) pImage)[i] = (float)
             (JDEMGetField( pszRecord + 9 + 5 * i, 5) * 0.1);
 
diff --git a/frmts/jp2kak/vsil_target.h b/frmts/jp2kak/vsil_target.h
index 8fb6d70..0ae0daa 100644
--- a/frmts/jp2kak/vsil_target.h
+++ b/frmts/jp2kak/vsil_target.h
@@ -81,7 +81,7 @@ public:
             if( file == NULL )
                 return false;
 
-            if( VSIFSeekL( file, SEEK_END, 0 ) != 0 )
+            if( VSIFSeekL( file, 0, SEEK_END ) != 0 )
                 return false;
             else
                 return true;
diff --git a/frmts/jpeg/jpgdataset.cpp b/frmts/jpeg/jpgdataset.cpp
index b9ecda1..9a2021b 100644
--- a/frmts/jpeg/jpgdataset.cpp
+++ b/frmts/jpeg/jpgdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: jpgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: jpgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  JPEG JFIF Driver
  * Purpose:  Implement GDAL JPEG Support based on IJG libjpeg.
@@ -50,7 +50,7 @@ typedef struct {
         GUInt32  tiff_diroff;    /* byte offset to first directory */
 } TIFFHeader;
 
-CPL_CVSID("$Id: jpgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: jpgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 #ifdef LIBJPEG_12_PATH 
@@ -748,8 +748,7 @@ JPGMaskBand::JPGMaskBand( JPGDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr JPGMaskBand::IReadBlock( int nBlockX, int nBlockY, void *pImage )
-
+CPLErr JPGMaskBand::IReadBlock( CPL_UNUSED int nBlockX, int nBlockY, void *pImage )
 {
     JPGDataset *poJDS = (JPGDataset *) poDS;
 
diff --git a/frmts/jpeg/vsidataio.cpp b/frmts/jpeg/vsidataio.cpp
index b519d56..c95e1e2 100644
--- a/frmts/jpeg/vsidataio.cpp
+++ b/frmts/jpeg/vsidataio.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vsidataio.cpp 24269 2012-04-20 20:52:55Z rouault $
+ * $Id: vsidataio.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  JPEG JFIF Driver
  * Purpose:  Implement JPEG read/write io indirection through VSI.
@@ -30,7 +30,7 @@
 
 #include "vsidataio.h"
 
-CPL_CVSID("$Id: vsidataio.cpp 24269 2012-04-20 20:52:55Z rouault $");
+CPL_CVSID("$Id: vsidataio.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 #include "jerror.h"
@@ -240,7 +240,7 @@ skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  */
 
 METHODDEF(void)
-term_source (j_decompress_ptr cinfo)
+term_source (CPL_UNUSED j_decompress_ptr cinfo)
 {
   /* no work necessary here */
 }
diff --git a/frmts/jpipkak/jpipkakdataset.cpp b/frmts/jpipkak/jpipkakdataset.cpp
index 3823de8..2cce54d 100644
--- a/frmts/jpipkak/jpipkakdataset.cpp
+++ b/frmts/jpipkak/jpipkakdataset.cpp
@@ -56,10 +56,10 @@ static int nPSTTargetOffset = -1;
 /* ==================================================================== */
 /************************************************************************/
 
-class kdu_cpl_error_message : public kdu_message 
+class jpipkak_kdu_cpl_error_message : public kdu_message 
 {
 public: // Member classes
-    kdu_cpl_error_message( CPLErr eErrClass ) 
+    jpipkak_kdu_cpl_error_message( CPLErr eErrClass ) 
     {
         m_eErrClass = eErrClass;
         m_pszError = NULL;
@@ -468,10 +468,10 @@ void JPIPKAKDataset::Deinitialize()
 int JPIPKAKDataset::Initialize(const char* pszDatasetName, int bReinitializing )
 {
     // set up message handlers
-    kdu_cpl_error_message oErrHandler( CE_Failure );
-    kdu_cpl_error_message oWarningHandler( CE_Warning );
-    kdu_customize_warnings(new kdu_cpl_error_message( CE_Warning ) );
-    kdu_customize_errors(new kdu_cpl_error_message( CE_Failure ) );
+    jpipkak_kdu_cpl_error_message oErrHandler( CE_Failure );
+    jpipkak_kdu_cpl_error_message oWarningHandler( CE_Warning );
+    kdu_customize_warnings(new jpipkak_kdu_cpl_error_message( CE_Warning ) );
+    kdu_customize_errors(new jpipkak_kdu_cpl_error_message( CE_Failure ) );
 
     // create necessary http headers
     CPLString osHeaders = "HEADERS=Accept: jpp-stream";
diff --git a/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp b/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp
index d9b69a7..a8d1e86 100644
--- a/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp
+++ b/frmts/kmlsuperoverlay/kmlsuperoverlaydataset.cpp
@@ -52,8 +52,8 @@ using namespace std;
 /*                           GenerateTiles()                            */
 /************************************************************************/
 void GenerateTiles(std::string filename, 
-                   int zoom, int rxsize, 
-                   int rysize, int ix, int iy, 
+                   CPL_UNUSED int zoom, int rxsize, 
+                   int rysize, CPL_UNUSED int ix, CPL_UNUSED int iy, 
                    int rx, int ry, int dxsize, 
                    int dysize, int bands,
                    GDALDataset* poSrcDs,
@@ -508,7 +508,8 @@ class KmlSuperOverlayDummyDataset: public GDALDataset
 
 static
 GDALDataset *KmlSuperOverlayCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-                                        int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData)
+                                        CPL_UNUSED int bStrict, char ** papszOptions,
+                                        GDALProgressFunc pfnProgress, void * pProgressData)
 {
     bool isKmz = false;
     
@@ -991,7 +992,7 @@ CPLErr KmlSuperOverlayReadDataset::GetGeoTransform( double * padfGeoTransform )
 /*                        KmlSuperOverlayRasterBand()                   */
 /************************************************************************/
 
-KmlSuperOverlayRasterBand::KmlSuperOverlayRasterBand(KmlSuperOverlayReadDataset* poDS, int nBand)
+KmlSuperOverlayRasterBand::KmlSuperOverlayRasterBand(KmlSuperOverlayReadDataset* poDS, CPL_UNUSED int nBand)
 {
     nRasterXSize = poDS->nRasterXSize;
     nRasterYSize = poDS->nRasterYSize;
@@ -2427,7 +2428,7 @@ GDALDataset *KmlSuperOverlayReadDataset::Open(const char* pszFilename,
 /*                    KmlSuperOverlayDatasetDelete()                    */
 /************************************************************************/
 
-static CPLErr KmlSuperOverlayDatasetDelete(const char* fileName)
+static CPLErr KmlSuperOverlayDatasetDelete(CPL_UNUSED const char* fileName)
 {
     /* Null implementation, so that people can Delete("MEM:::") */
     return CE_None;
diff --git a/frmts/l1b/l1bdataset.cpp b/frmts/l1b/l1bdataset.cpp
index 52a7c6b..1633e04 100644
--- a/frmts/l1b/l1bdataset.cpp
+++ b/frmts/l1b/l1bdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: l1bdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: l1bdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NOAA Polar Orbiter Level 1b Dataset Reader (AVHRR)
  * Purpose:  Can read NOAA-9(F)-NOAA-17(M) AVHRR datasets
@@ -37,7 +37,7 @@
 #include "gdal_pam.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: l1bdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: l1bdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_L1B(void);
@@ -339,7 +339,7 @@ L1BRasterBand::L1BRasterBand( L1BDataset *poDS, int nBand )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr L1BRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr L1BRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 {
     L1BDataset  *poGDS = (L1BDataset *) poDS;
@@ -2268,7 +2268,7 @@ L1BInterpol(double vals[],
 /*                         IReadBlock()                                 */
 /************************************************************************/
 
-CPLErr L1BGeolocRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void* pData)
+CPLErr L1BGeolocRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff, void* pData)
 {
     L1BGeolocDataset* poGDS = (L1BGeolocDataset*)poDS;
     L1BDataset* poL1BDS = poGDS->poL1BDS;
@@ -2447,7 +2447,7 @@ L1BSolarZenithAnglesRasterBand::L1BSolarZenithAnglesRasterBand(L1BSolarZenithAng
 /*                         IReadBlock()                                 */
 /************************************************************************/
 
-CPLErr L1BSolarZenithAnglesRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void* pData)
+CPLErr L1BSolarZenithAnglesRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff, void* pData)
 {
     L1BSolarZenithAnglesDataset* poGDS = (L1BSolarZenithAnglesDataset*)poDS;
     L1BDataset* poL1BDS = poGDS->poL1BDS;
@@ -2640,7 +2640,7 @@ L1BNOAA15AnglesRasterBand::L1BNOAA15AnglesRasterBand(L1BNOAA15AnglesDataset* poD
 /*                         IReadBlock()                                 */
 /************************************************************************/
 
-CPLErr L1BNOAA15AnglesRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void* pData)
+CPLErr L1BNOAA15AnglesRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff, void* pData)
 {
     L1BNOAA15AnglesDataset* poGDS = (L1BNOAA15AnglesDataset*)poDS;
     L1BDataset* poL1BDS = poGDS->poL1BDS;
@@ -2766,7 +2766,7 @@ L1BCloudsRasterBand::L1BCloudsRasterBand(L1BCloudsDataset* poDS, int nBand)
 /*                         IReadBlock()                                 */
 /************************************************************************/
 
-CPLErr L1BCloudsRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void* pData)
+CPLErr L1BCloudsRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff, void* pData)
 {
     L1BCloudsDataset* poGDS = (L1BCloudsDataset*)poDS;
     L1BDataset* poL1BDS = poGDS->poL1BDS;
diff --git a/frmts/leveller/levellerdataset.cpp b/frmts/leveller/levellerdataset.cpp
index 332851b..620f52f 100644
--- a/frmts/leveller/levellerdataset.cpp
+++ b/frmts/leveller/levellerdataset.cpp
@@ -35,7 +35,7 @@
 #include "gdal_pam.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: levellerdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: levellerdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_Leveller(void);
@@ -454,11 +454,10 @@ LevellerRasterBand::~LevellerRasterBand()
 /*                             IWriteBlock()                            */
 /************************************************************************/
 
-CPLErr LevellerRasterBand::IWriteBlock
-( 
-	int nBlockXOff, 
+CPLErr LevellerRasterBand::IWriteBlock ( 
+	CPL_UNUSED int nBlockXOff, 
 	int nBlockYOff,
-    void* pImage
+        void* pImage
 )
 {
     CPLAssert( nBlockXOff == 0  );
@@ -521,7 +520,7 @@ CPLErr LevellerRasterBand::SetUnitType( const char* psz )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr LevellerRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr LevellerRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                        void* pImage )
 
 {
diff --git a/frmts/map/mapdataset.cpp b/frmts/map/mapdataset.cpp
index 6c2bfa0..f7e2045 100644
--- a/frmts/map/mapdataset.cpp
+++ b/frmts/map/mapdataset.cpp
@@ -32,7 +32,7 @@
 #include "ogr_spatialref.h"
 #include "ogr_geometry.h"
 
-CPL_CVSID("$Id: mapdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: mapdataset.cpp 27560 2014-08-04 17:52:58Z rouault $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -247,12 +247,12 @@ GDALDataset *MAPDataset::Open( GDALOpenInfo * poOpenInfo )
         CPLString osPath = CPLGetPath(poOpenInfo->pszFilename);
         if (CPLIsFilenameRelative(poDS->osImgFilename))
         {
-            poDS->osImgFilename = CPLFormFilename(osPath, poDS->osImgFilename, NULL);
+            poDS->osImgFilename = CPLFormCIFilename(osPath, poDS->osImgFilename, NULL);
         }
         else
         {
             poDS->osImgFilename = CPLGetFilename(poDS->osImgFilename);
-            poDS->osImgFilename = CPLFormFilename(osPath, poDS->osImgFilename, NULL);
+            poDS->osImgFilename = CPLFormCIFilename(osPath, poDS->osImgFilename, NULL);
         }
     }
 
diff --git a/frmts/mbtiles/mbtilesdataset.cpp b/frmts/mbtiles/mbtilesdataset.cpp
index 71aa928..4f82f2c 100644
--- a/frmts/mbtiles/mbtilesdataset.cpp
+++ b/frmts/mbtiles/mbtilesdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: mbtilesdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: mbtilesdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL MBTiles driver
  * Purpose:  Implement GDAL MBTiles support using OGR SQLite driver
@@ -39,7 +39,7 @@
 
 extern "C" void GDALRegister_MBTiles();
 
-CPL_CVSID("$Id: mbtilesdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: mbtilesdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static const char * const apszAllowedDrivers[] = {"JPEG", "PNG", NULL};
 
@@ -198,7 +198,7 @@ CPLErr MBTilesBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage)
             {
                 int iBand;
                 void* pSrcImage = NULL;
-                GByte abyTranslation[256][3];
+                GByte abyTranslation[256][4];
 
                 bGotTile = TRUE;
 
@@ -235,12 +235,14 @@ CPLErr MBTilesBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage)
                         abyTranslation[i][0] = (GByte) psEntry->c1;
                         abyTranslation[i][1] = (GByte) psEntry->c2;
                         abyTranslation[i][2] = (GByte) psEntry->c3;
+                        abyTranslation[i][3] = (GByte) psEntry->c4;
                     }
                     for(; i < 256; i++)
                     {
                         abyTranslation[i][0] = 0;
                         abyTranslation[i][1] = 0;
                         abyTranslation[i][2] = 0;
+                        abyTranslation[i][3] = 0;
                     }
 
                     for(i = 0; i < nBlockXSize * nBlockYSize; i++)
@@ -282,11 +284,7 @@ CPLErr MBTilesBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage)
                     else if (nTileBands == 1 && (poGDS->nBands == 3 || poGDS->nBands == 4))
                     {
                         int i;
-                        if (iOtherBand == 4)
-                        {
-                            memset(pabySrcBlock, 255, nBlockXSize * nBlockYSize);
-                        }
-                        else if (pSrcImage)
+                        if (pSrcImage)
                         {
                             for(i = 0; i < nBlockXSize * nBlockYSize; i++)
                             {
@@ -620,7 +618,7 @@ char* MBTilesDataset::FindKey(int iPixel, int iLine,
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                     "JSON parsing error: %s (at offset %d)",
-                    json_tokener_errors[jstok->err],
+                    json_tokener_error_desc(jstok->err),
                     jstok->char_offset);
         json_tokener_free(jstok);
 
@@ -1277,7 +1275,7 @@ int MBTilesGetMinMaxZoomLevel(OGRDataSourceH hDS, int bHasMap,
 /************************************************************************/
 
 static
-int MBTilesGetBounds(OGRDataSourceH hDS, int nMinLevel, int nMaxLevel,
+int MBTilesGetBounds(OGRDataSourceH hDS, CPL_UNUSED int nMinLevel, int nMaxLevel,
                      int& nMinTileRow, int& nMaxTileRow,
                      int& nMinTileCol, int &nMaxTileCol)
 {
@@ -1376,7 +1374,7 @@ int MBTilesGetBounds(OGRDataSourceH hDS, int nMinLevel, int nMaxLevel,
 /* to get a first tile to see its characteristics. We just need the header */
 /* to determine that, so let's make VSICurl stop reading after we have found it */
 
-static int MBTilesCurlReadCbk(VSILFILE* fp,
+static int MBTilesCurlReadCbk(CPL_UNUSED VSILFILE* fp,
                               void *pabyBuffer, size_t nBufferSize,
                               void* pfnUserData)
 {
@@ -1434,7 +1432,12 @@ static int MBTilesCurlReadCbk(VSILFILE* fp,
                 else if (nColorType == 2)
                     *pnBands = 3; /* RGB */
                 else if (nColorType == 3)
-                    *pnBands = 3; /* palette -> RGB */
+                {
+                    /* This might also be a color table with transparency */
+                    /* but we cannot tell ! */
+                    *pnBands = -1;
+                    return TRUE;
+                }
                 else if (nColorType == 4)
                     *pnBands = 2; /* Gray + alpha */
                 else if (nColorType == 6)
@@ -1477,7 +1480,7 @@ static int MBTilesCurlReadCbk(VSILFILE* fp,
 /************************************************************************/
 
 static
-int MBTilesGetBandCount(OGRDataSourceH &hDS, int nMinLevel, int nMaxLevel,
+int MBTilesGetBandCount(OGRDataSourceH &hDS, CPL_UNUSED int nMinLevel, int nMaxLevel,
                         int nMinTileRow, int nMaxTileRow,
                         int nMinTileCol, int nMaxTileCol)
 {
@@ -1629,10 +1632,17 @@ int MBTilesGetBandCount(OGRDataSourceH &hDS, int nMinLevel, int nMaxLevel,
         return -1;
     }
 
-    if (nBands == 1 &&
-        GDALGetRasterColorTable(GDALGetRasterBand(hDSTile, 1)) != NULL)
+    GDALColorTableH hCT = GDALGetRasterColorTable(GDALGetRasterBand(hDSTile, 1));
+    if (nBands == 1 && hCT != NULL)
     {
         nBands = 3;
+        if( GDALGetColorEntryCount(hCT) > 0 )
+        {
+            /* Typical of paletted PNG with transparency */
+            const GDALColorEntry* psEntry = GDALGetColorEntry( hCT, 0 );
+            if( psEntry->c4 == 0 )
+                nBands = 4;
+        }
     }
 
     GDALClose(hDSTile);
diff --git a/frmts/mem/memdataset.cpp b/frmts/mem/memdataset.cpp
index 3bddd39..9b2d74e 100644
--- a/frmts/mem/memdataset.cpp
+++ b/frmts/mem/memdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: memdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: memdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Memory Array Translator
  * Purpose:  Complete implementation.
@@ -31,7 +31,7 @@
 #include "memdataset.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: memdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: memdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        MEMCreateRasterBand()                         */
@@ -127,7 +127,7 @@ MEMRasterBand::~MEMRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr MEMRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr MEMRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                    void * pImage )
 
 {
@@ -159,7 +159,7 @@ CPLErr MEMRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 /*                            IWriteBlock()                             */
 /************************************************************************/
 
-CPLErr MEMRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff,
+CPLErr MEMRasterBand::IWriteBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                      void * pImage )
 
 {
@@ -848,7 +848,7 @@ GDALDataset *MEMDataset::Open( GDALOpenInfo * poOpenInfo )
 /*                               Create()                               */
 /************************************************************************/
 
-GDALDataset *MEMDataset::Create( const char * pszFilename,
+GDALDataset *MEMDataset::Create( CPL_UNUSED const char * pszFilename,
                                  int nXSize, int nYSize, int nBands,
                                  GDALDataType eType,
                                  char **papszOptions )
@@ -982,7 +982,7 @@ static int MEMDatasetIdentify( GDALOpenInfo * poOpenInfo )
 /*                       MEMDatasetDelete()                             */
 /************************************************************************/
 
-static CPLErr MEMDatasetDelete(const char* fileName)
+static CPLErr MEMDatasetDelete(CPL_UNUSED const char* fileName)
 {
     /* Null implementation, so that people can Delete("MEM:::") */
     return CE_None;
diff --git a/frmts/msg/msgcommand.cpp b/frmts/msg/msgcommand.cpp
index 755a49d..020aaee 100644
--- a/frmts/msg/msgcommand.cpp
+++ b/frmts/msg/msgcommand.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: msgcommand.cpp 15085 2008-07-31 13:41:31Z mloskot $
+ * $Id: msgcommand.cpp 27371 2014-05-21 09:35:42Z rouault $
  *
  * Purpose:  Implementation of MSGCommand class. Parse the src_dataset
  *           string that is meant for the MSG driver.
@@ -29,6 +29,7 @@
 
 #include "msgcommand.h"
 #include <cstdlib>
+#include <cstdio>
 using namespace std;
 
 #ifdef _WIN32
diff --git a/frmts/msgn/msgndataset.cpp b/frmts/msgn/msgndataset.cpp
index f059a21..2f7b731 100644
--- a/frmts/msgn/msgndataset.cpp
+++ b/frmts/msgn/msgndataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: msgndataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: msgndataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  MSG Native Reader
  * Purpose:  All code for EUMETSAT Archive format reader
@@ -34,7 +34,7 @@
 #include "msg_reader_core.h"
 using namespace msg_native_format;
 
-CPL_CVSID("$Id: msgndataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: msgndataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void   GDALRegister_MSGN(void);
@@ -155,9 +155,8 @@ MSGNRasterBand::MSGNRasterBand( MSGNDataset *poDS, int nBand , open_mode_type mo
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr MSGNRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
-                                  void * pImage )
-
+CPLErr MSGNRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
+                                   void * pImage )
 {
     MSGNDataset *poGDS = (MSGNDataset *) poDS;
 
diff --git a/frmts/ngsgeoid/ngsgeoiddataset.cpp b/frmts/ngsgeoid/ngsgeoiddataset.cpp
index ef1e53d..406eef0 100644
--- a/frmts/ngsgeoid/ngsgeoiddataset.cpp
+++ b/frmts/ngsgeoid/ngsgeoiddataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ngsgeoiddataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ngsgeoiddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NGSGEOID driver
  * Purpose:  GDALDataset driver for NGSGEOID dataset.
@@ -32,7 +32,7 @@
 #include "gdal_pam.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ngsgeoiddataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ngsgeoiddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_NGSGEOID(void);
@@ -113,7 +113,7 @@ NGSGEOIDRasterBand::NGSGEOIDRasterBand( NGSGEOIDDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr NGSGEOIDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr NGSGEOIDRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                        void * pImage )
 
 {
diff --git a/frmts/nitf/GNUmakefile b/frmts/nitf/GNUmakefile
index d175844..bfcb993 100644
--- a/frmts/nitf/GNUmakefile
+++ b/frmts/nitf/GNUmakefile
@@ -7,13 +7,13 @@ GDAL_OBJ =	nitfdataset.o rpftocdataset.o nitfwritejpeg.o \
 NITFLIB_OBJ =	nitffile.o nitfimage.o mgrs.o nitfaridpcm.o \
 		nitfbilevel.o rpftocfile.o nitfdes.o nitf_gcprpc.o
 
-CPPFLAGS	:=	-I../vrt $(GDAL_INCLUDE) $(CPPFLAGS)
+CPPFLAGS	:=	-I../vrt -I../gtiff $(GDAL_INCLUDE) $(CPPFLAGS)
 
 ifeq ($(TIFF_SETTING),internal)
 ifeq ($(RENAME_INTERNAL_LIBTIFF_SYMBOLS),yes)
 CPPFLAGS 	:=	$(CPPFLAGS) -DRENAME_INTERNAL_LIBTIFF_SYMBOLS
 endif
-CPPFLAGS	:=	$(CPPFLAGS) -I../gtiff/libtiff
+CPPFLAGS	:=	-I../gtiff/libtiff $(CPPFLAGS)
 endif
 
 ifneq ($(JPEG_SETTING),no)
@@ -21,7 +21,7 @@ CPPFLAGS	:=	$(CPPFLAGS) -DJPEG_SUPPORTED
 endif
 
 ifeq ($(JPEG_SETTING),internal)
-CPPFLAGS	:=	$(CPPFLAGS) -I../jpeg/libjpeg
+CPPFLAGS	:=	-I../jpeg/libjpeg $(CPPFLAGS)
 endif
 
 ifeq ($(JPEG12_ENABLED),yes)
diff --git a/frmts/nitf/nitfaridpcm.cpp b/frmts/nitf/nitfaridpcm.cpp
index 78aacb5..f0d5894 100644
--- a/frmts/nitf/nitfaridpcm.cpp
+++ b/frmts/nitf/nitfaridpcm.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nitfaridpcm.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nitfaridpcm.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NITF Read/Write Library
  * Purpose:  ARIDPCM reading code.
@@ -32,7 +32,7 @@
 #include "nitflib.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: nitfaridpcm.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: nitfaridpcm.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static const int neighbourhood_size_75[4] = { 23, 47, 74, 173 };
 static const int bits_per_level_by_busycode_75[4/*busy code*/][4/*level*/] = { 
@@ -201,8 +201,8 @@ get_bits( unsigned char *buffer, int first_bit, int num_bits )
 static int
 get_delta( unsigned char *srcdata, 
            int nInputBytes,
-           int busy_code, int comrat,
-           int block_offset, int block_size, 
+           int busy_code, CPL_UNUSED int comrat,
+           int block_offset, CPL_UNUSED int block_size, 
            int i, int j, int *pbError )
 
 {
diff --git a/frmts/nitf/nitfdes.c b/frmts/nitf/nitfdes.c
index 5d22098..a0e64f2 100644
--- a/frmts/nitf/nitfdes.c
+++ b/frmts/nitf/nitfdes.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nitfdes.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nitfdes.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NITF Read/Write Library
  * Purpose:  Module responsible for implementation of DE segments.
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: nitfdes.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: nitfdes.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          NITFDESAccess()                             */
@@ -429,7 +429,7 @@ int   NITFDESGetTRE( NITFDES* psDES,
     psSegInfo = psDES->psFile->pasSegmentInfo + psDES->iSegment;
     fp = psDES->psFile->fp;
 
-    if (nOffset >= psSegInfo->nSegmentSize)
+    if ((GUIntBig)nOffset >= psSegInfo->nSegmentSize)
         return FALSE;
 
     VSIFSeekL(fp, psSegInfo->nSegmentStart + nOffset, SEEK_SET);
@@ -460,7 +460,7 @@ int   NITFDESGetTRE( NITFDES* psDES,
                  nTRESize, szTRETempName);
         return FALSE;
     }
-    if (nOffset + 11 + nTRESize > psSegInfo->nSegmentSize)
+    if ((GUIntBig)(nOffset + 11 + nTRESize) > psSegInfo->nSegmentSize)
     {
         CPLError(CE_Failure, CPLE_AppDefined,
                  "Cannot read %s TRE. Not enough bytes : remaining %d, expected %d",
@@ -565,7 +565,7 @@ int NITFDESExtractShapefile(NITFDES* psDES, const char* pszRadixFileName)
         }
 
         VSIFSeekL(psDES->psFile->fp, psSegInfo->nSegmentStart + anOffset[iShpFile], SEEK_SET);
-        if (VSIFReadL(pabyBuffer, 1, nSize, psDES->psFile->fp) != nSize)
+        if (VSIFReadL(pabyBuffer, 1, nSize, psDES->psFile->fp) != (size_t)nSize)
         {
             VSIFree(pabyBuffer);
             VSIFree(pszFilename);
diff --git a/frmts/nitf/nitffile.c b/frmts/nitf/nitffile.c
index 79a5ed9..2909904 100644
--- a/frmts/nitf/nitffile.c
+++ b/frmts/nitf/nitffile.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nitffile.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nitffile.c 27731 2014-09-24 07:58:14Z rouault $
  *
  * Project:  NITF Read/Write Library
  * Purpose:  Module responsible for opening NITF file, populating NITFFile
@@ -34,7 +34,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: nitffile.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: nitffile.c 27731 2014-09-24 07:58:14Z rouault $");
 
 static int NITFWriteBLOCKA( VSILFILE* fp, vsi_l_offset nOffsetUDIDL,
                             int *pnOffset,
@@ -275,7 +275,7 @@ retry_read_header:
             abyDELIM2_L2[2] == 0x14 && abyDELIM2_L2[3] == 0xBF)
         {
             int SFHL2 = atoi((const char*)(abyDELIM2_L2 + 4));
-            if (SFHL2 > 0 && nFileSize > 11 + SFHL2 + 11 )
+            if (SFHL2 > 0 && nFileSize > (GUIntBig)(11 + SFHL2 + 11) )
             {
                 VSIFSeekL( fp, nFileSize - 11 - SFHL2 - 11 , SEEK_SET );
 
@@ -475,11 +475,11 @@ void NITFClose( NITFFile *psFile )
 
 static void NITFGotoOffset(VSILFILE* fp, GUIntBig nLocation)
 {
+    GUIntBig iFill;
     GUIntBig nCurrentLocation = VSIFTellL(fp);
     if (nLocation > nCurrentLocation)
     {
         GUIntBig nFileSize;
-        int iFill;
         char cSpace = ' ';
 
         VSIFSeekL(fp, 0, SEEK_END);
@@ -1643,7 +1643,7 @@ void NITFExtractMetadata( char ***ppapszMetadata, const char *pachHeader,
     char szWork[400];
     char* pszWork;
 
-    if (nLength >= sizeof(szWork) - 1)
+    if ((size_t)nLength >= sizeof(szWork) - 1)
         pszWork = (char*)CPLMalloc(nLength + 1);
     else
         pszWork = szWork;
@@ -1906,7 +1906,7 @@ const NITFSeries* NITFGetSeriesInfo(const char* pszFilename)
             {
                 seriesCode[0] = pszFilename[i+1];
                 seriesCode[1] = pszFilename[i+2];
-                for(i=0;i<sizeof(nitfSeries) / sizeof(nitfSeries[0]); i++)
+                for(i=0;(size_t)i<sizeof(nitfSeries) / sizeof(nitfSeries[0]); i++)
                 {
                     if (EQUAL(seriesCode, nitfSeries[i].code))
                     {
@@ -2076,7 +2076,7 @@ int NITFReconcileAttachments( NITFFile *psFile )
 static const char* NITFFindValFromEnd(char** papszMD,
                                       int nMDSize,
                                       const char* pszVar,
-                                      const char* pszDefault)
+                                      CPL_UNUSED const char* pszDefault)
 {
     int nVarLen = strlen(pszVar);
     int nIter = nMDSize-1;
diff --git a/frmts/nitf/nitfimage.c b/frmts/nitf/nitfimage.c
index c903e4e..c1bef04 100644
--- a/frmts/nitf/nitfimage.c
+++ b/frmts/nitf/nitfimage.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nitfimage.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nitfimage.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NITF Read/Write Library
  * Purpose:  Module responsible for implementation of most NITFImage 
@@ -36,7 +36,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: nitfimage.c 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: nitfimage.c 27729 2014-09-24 00:40:16Z goatbar $");
 
 static int NITFReadIMRFCA( NITFImage *psImage, NITFRPC00BInfo *psRPC );
 static char *NITFTrimWhite( char * );
@@ -1255,8 +1255,8 @@ int NITFReadImageBlock( NITFImage *psImage, int nBlockX, int nBlockY,
 /* -------------------------------------------------------------------- */
 /*      Can we do a direct read into our buffer?                        */
 /* -------------------------------------------------------------------- */
-    if( psImage->nWordSize == psImage->nPixelOffset
-        && (psImage->nBitsPerSample * psImage->nBlockWidth + 7) / 8
+    if( (GUIntBig)psImage->nWordSize == psImage->nPixelOffset
+        && (GUIntBig)((psImage->nBitsPerSample * psImage->nBlockWidth + 7) / 8)
            == psImage->nLineOffset 
         && psImage->szIC[0] != 'C' && psImage->szIC[0] != 'M'
         && psImage->chIMODE != 'P' )
@@ -1558,8 +1558,8 @@ int NITFWriteImageBlock( NITFImage *psImage, int nBlockX, int nBlockY,
 /* -------------------------------------------------------------------- */
 /*      Can we do a direct read into our buffer?                        */
 /* -------------------------------------------------------------------- */
-    if( psImage->nWordSize == psImage->nPixelOffset
-        && psImage->nWordSize * psImage->nBlockWidth == psImage->nLineOffset 
+    if( (GUIntBig)psImage->nWordSize == psImage->nPixelOffset
+        && (GUIntBig)(psImage->nWordSize * psImage->nBlockWidth) == psImage->nLineOffset 
         && psImage->szIC[0] != 'C' && psImage->szIC[0] != 'M' )
     {
 #ifdef CPL_LSB
@@ -1653,8 +1653,8 @@ int NITFReadImageLine( NITFImage *psImage, int nLine, int nBand, void *pData )
 /*      Can we do a direct read into our buffer.                        */
 /* -------------------------------------------------------------------- */
     if( (psImage->nBitsPerSample % 8) != 0 ||
-        (psImage->nWordSize == psImage->nPixelOffset
-        && psImage->nWordSize * psImage->nBlockWidth == psImage->nLineOffset) )
+        ((GUIntBig)psImage->nWordSize == psImage->nPixelOffset
+         && (GUIntBig)(psImage->nWordSize * psImage->nBlockWidth) == psImage->nLineOffset) )
     {
         if( VSIFReadL( pData, 1, nLineSize, psImage->psFile->fp ) !=  
             nLineSize )
@@ -1769,8 +1769,8 @@ int NITFWriteImageLine( NITFImage *psImage, int nLine, int nBand, void *pData )
 /* -------------------------------------------------------------------- */
 /*      Can we do a direct write into our buffer.                       */
 /* -------------------------------------------------------------------- */
-    if( psImage->nWordSize == psImage->nPixelOffset
-        && psImage->nWordSize * psImage->nBlockWidth == psImage->nLineOffset )
+    if( (GUIntBig)psImage->nWordSize == psImage->nPixelOffset
+        && (GUIntBig)(psImage->nWordSize * psImage->nBlockWidth) == psImage->nLineOffset )
     {
 #ifdef CPL_LSB
         NITFSwapWords( psImage, pData, psImage->nBlockWidth );
@@ -2819,7 +2819,7 @@ static void NITFLoadAttributeSection( NITFImage *psImage )
 /*      hold the offset table (otherwise NITFFetchAttribute coud        */
 /*      read out of the buffer)                                         */
 /* -------------------------------------------------------------------- */
-    if (nASSSize < 8 * nAttrCount)
+    if (nASSSize < (GUIntBig)(8 * nAttrCount))
     {
         CPLError( CE_Warning, CPLE_AppDefined,
                   "Attribute subsection not large enough (%d bytes) to contain %d attributes.",
@@ -3388,7 +3388,7 @@ static int NITFLoadVQTables( NITFImage *psImage, int bTryGuessingOffset )
         if (!bTryGuessingOffset)
             return FALSE;
 
-        for( i = 0; i < sizeof(abyTestChunk) - sizeof(abySignature); i++ )
+        for( i = 0; (size_t)i < sizeof(abyTestChunk) - sizeof(abySignature); i++ )
         {
             if( memcmp(abyTestChunk+i,abySignature,sizeof(abySignature)) == 0 )
             {
diff --git a/frmts/nitf/nitfrasterband.cpp b/frmts/nitf/nitfrasterband.cpp
index 8b8c53f..b580826 100644
--- a/frmts/nitf/nitfrasterband.cpp
+++ b/frmts/nitf/nitfrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nitfrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nitfrasterband.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NITF Read/Write Translator
  * Purpose:  NITFRasterBand (and related proxy band) implementations.
@@ -35,7 +35,7 @@
 #include "cpl_string.h"
 #include "cpl_csv.h"
 
-CPL_CVSID("$Id: nitfrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: nitfrasterband.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                       NITFMakeColorTable()                           */
@@ -352,7 +352,7 @@ RB_PROXY_METHOD_WITH_RET(CPLErr, CE_Failure, CreateMaskBand, ( int nFlags ), (nF
 /*                 UnrefUnderlyingRasterBand()                        */
 /************************************************************************/
 
-void NITFProxyPamRasterBand::UnrefUnderlyingRasterBand(GDALRasterBand* poUnderlyingRasterBand)
+void NITFProxyPamRasterBand::UnrefUnderlyingRasterBand(CPL_UNUSED GDALRasterBand* poUnderlyingRasterBand)
 {
 }
 
diff --git a/frmts/northwood/grcdataset.cpp b/frmts/northwood/grcdataset.cpp
index eabb552..e012e37 100644
--- a/frmts/northwood/grcdataset.cpp
+++ b/frmts/northwood/grcdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: grcdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: grcdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GRC Reader
  * Purpose:  GDAL driver for Northwood Classified Format
@@ -228,7 +228,7 @@ GDALColorInterp NWT_GRCRasterBand::GetColorInterpretation()
 /************************************************************************/
 /*                             IReadBlock()                             */
 /************************************************************************/
-CPLErr NWT_GRCRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr NWT_GRCRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                         void *pImage )
 {
     NWT_GRCDataset *poGDS =(NWT_GRCDataset *) poDS;
diff --git a/frmts/northwood/grddataset.cpp b/frmts/northwood/grddataset.cpp
index 806ec51..6ba9d88 100644
--- a/frmts/northwood/grddataset.cpp
+++ b/frmts/northwood/grddataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: grddataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: grddataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GRD Reader
  * Purpose:  GDAL driver for Northwood Grid Format
@@ -173,7 +173,7 @@ GDALColorInterp NWT_GRDRasterBand::GetColorInterpretation()
 /************************************************************************/
 /*                             IReadBlock()                             */
 /************************************************************************/
-CPLErr NWT_GRDRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void *pImage )
+CPLErr NWT_GRDRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff, void *pImage )
 {
     NWT_GRDDataset *poGDS = (NWT_GRDDataset *) poDS;
     char *pszRecord;
diff --git a/frmts/northwood/northwood.cpp b/frmts/northwood/northwood.cpp
index 0ba2989..71fed3e 100644
--- a/frmts/northwood/northwood.cpp
+++ b/frmts/northwood/northwood.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: northwood.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: northwood.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GRC/GRD Reader
  * Purpose:  Northwood Format basic implementation
@@ -480,9 +480,8 @@ void nwtCloseGrid( NWT_GRID * pGrd )
         return;
 }
 
-void nwtGetRow( NWT_GRID * pGrd )
+void nwtGetRow( CPL_UNUSED NWT_GRID * pGrd )
 {
-
 }
 
 void nwtPrintGridHeader( NWT_GRID * pGrd )
diff --git a/frmts/openjpeg/openjpegdataset.cpp b/frmts/openjpeg/openjpegdataset.cpp
index 1a3a119..98ec8c0 100644
--- a/frmts/openjpeg/openjpegdataset.cpp
+++ b/frmts/openjpeg/openjpegdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: openjpegdataset.cpp 27182 2014-04-14 20:03:08Z rouault $
+ * $Id: openjpegdataset.cpp 27373 2014-05-21 12:14:37Z rouault $
  *
  * Project:  JPEG2000 driver based on OpenJPEG library
  * Purpose:  JPEG2000 driver based on OpenJPEG library
@@ -39,7 +39,7 @@
 #include "cpl_multiproc.h"
 #include "cpl_atomic_ops.h"
 
-CPL_CVSID("$Id: openjpegdataset.cpp 27182 2014-04-14 20:03:08Z rouault $");
+CPL_CVSID("$Id: openjpegdataset.cpp 27373 2014-05-21 12:14:37Z rouault $");
 
 /************************************************************************/
 /*                  JP2OpenJPEGDataset_ErrorCallback()                  */
@@ -630,8 +630,10 @@ CPLErr JP2OpenJPEGDataset::ReadBlock( int nBand, VSILFILE* fp,
     if (bUseSetDecodeArea)
     {
         if (!opj_set_decode_area(pCodec,psImage,
-                                nBlockXOff*nBlockXSize,nBlockYOff*nBlockYSize,
-                                (nBlockXOff+1)*nBlockXSize,(nBlockYOff+1)*nBlockYSize))
+                                 nBlockXOff*nBlockXSize,
+                                 nBlockYOff*nBlockYSize,
+                                 nBlockXOff*nBlockXSize+nWidthToRead,
+                                 nBlockYOff*nBlockYSize+nHeightToRead))
         {
             CPLError(CE_Failure, CPLE_AppDefined, "opj_set_decode_area() failed");
             eErr = CE_Failure;
diff --git a/frmts/pcidsk/sdk/channel/cbandinterleavedchannel.cpp b/frmts/pcidsk/sdk/channel/cbandinterleavedchannel.cpp
index 049c482..6c3ce52 100644
--- a/frmts/pcidsk/sdk/channel/cbandinterleavedchannel.cpp
+++ b/frmts/pcidsk/sdk/channel/cbandinterleavedchannel.cpp
@@ -44,6 +44,8 @@
 #include <cstdio>
 #include <cstdlib>
 
+#include "cpl_port.h"
+
 using namespace PCIDSK;
 
 /************************************************************************/
@@ -52,7 +54,7 @@ using namespace PCIDSK;
 
 CBandInterleavedChannel::CBandInterleavedChannel( PCIDSKBuffer &image_header, 
                                                   uint64 ih_offset, 
-                                                  PCIDSKBuffer &file_header,
+                                                  CPL_UNUSED PCIDSKBuffer &file_header,
                                                   int channelnum,
                                                   CPCIDSKFile *file,
                                                   uint64 image_offset,
diff --git a/frmts/pcidsk/sdk/channel/cexternalchannel.cpp b/frmts/pcidsk/sdk/channel/cexternalchannel.cpp
index 32654af..6e70b1d 100644
--- a/frmts/pcidsk/sdk/channel/cexternalchannel.cpp
+++ b/frmts/pcidsk/sdk/channel/cexternalchannel.cpp
@@ -44,6 +44,8 @@
 #include <cstdio>
 #include <cstdlib>
 
+#include "cpl_port.h"
+
 using namespace PCIDSK;
 
 /************************************************************************/
@@ -52,7 +54,7 @@ using namespace PCIDSK;
 
 CExternalChannel::CExternalChannel( PCIDSKBuffer &image_header, 
                                     uint64 ih_offset, 
-                                    PCIDSKBuffer &file_header,
+                                    CPL_UNUSED PCIDSKBuffer &file_header,
                                     std::string filename,
                                     int channelnum,
                                     CPCIDSKFile *file,
diff --git a/frmts/pcidsk/sdk/channel/cpcidskchannel.cpp b/frmts/pcidsk/sdk/channel/cpcidskchannel.cpp
index 30e3f6c..b8e4f53 100644
--- a/frmts/pcidsk/sdk/channel/cpcidskchannel.cpp
+++ b/frmts/pcidsk/sdk/channel/cpcidskchannel.cpp
@@ -39,6 +39,8 @@
 #include <cstring>
 #include <cstdio>
 
+#include "cpl_port.h"
+
 using namespace PCIDSK;
 
 /************************************************************************/
@@ -480,9 +482,9 @@ void CPCIDSKChannel::GetChanInfo( std::string &filename, uint64 &image_offset,
 /*                            SetChanInfo()                             */
 /************************************************************************/
 
-void CPCIDSKChannel::SetChanInfo( std::string filename, uint64 image_offset, 
-                                  uint64 pixel_offset, uint64 line_offset, 
-                                  bool little_endian )
+void CPCIDSKChannel::SetChanInfo( CPL_UNUSED std::string filename, CPL_UNUSED uint64 image_offset, 
+                                  CPL_UNUSED uint64 pixel_offset, CPL_UNUSED uint64 line_offset, 
+                                  CPL_UNUSED bool little_endian )
 
 {
     ThrowPCIDSKException( "Attempt to SetChanInfo() on a channel that is not FILE interleaved." );
@@ -508,9 +510,9 @@ void CPCIDSKChannel::GetEChanInfo( std::string &filename, int &echannel,
 /*                            SetEChanInfo()                            */
 /************************************************************************/
 
-void CPCIDSKChannel::SetEChanInfo( std::string filename, int echannel,
-                                   int exoff, int eyoff, 
-                                   int exsize, int eysize )
+void CPCIDSKChannel::SetEChanInfo( CPL_UNUSED std::string filename, CPL_UNUSED int echannel,
+                                   CPL_UNUSED int exoff, CPL_UNUSED int eyoff, 
+                                   CPL_UNUSED int exsize, CPL_UNUSED int eysize )
 
 {
     ThrowPCIDSKException( "Attempt to SetEChanInfo() on a channel that is not FILE interleaved." );
diff --git a/frmts/pcidsk/sdk/channel/cpixelinterleavedchannel.cpp b/frmts/pcidsk/sdk/channel/cpixelinterleavedchannel.cpp
index df9344c..60e24b0 100644
--- a/frmts/pcidsk/sdk/channel/cpixelinterleavedchannel.cpp
+++ b/frmts/pcidsk/sdk/channel/cpixelinterleavedchannel.cpp
@@ -32,6 +32,8 @@
 #include <cassert>
 #include <cstring>
 
+#include "cpl_port.h"
+
 using namespace PCIDSK;
 
 /************************************************************************/
@@ -40,7 +42,7 @@ using namespace PCIDSK;
 
 CPixelInterleavedChannel::CPixelInterleavedChannel( PCIDSKBuffer &image_header, 
                                                     uint64 ih_offset,
-                                                    PCIDSKBuffer &file_header,
+                                                    CPL_UNUSED PCIDSKBuffer &file_header,
                                                     int channelnum,
                                                     CPCIDSKFile *file,
                                                     int image_offset,
diff --git a/frmts/pcidsk/sdk/channel/ctiledchannel.cpp b/frmts/pcidsk/sdk/channel/ctiledchannel.cpp
index 4bd0c31..4c090e7 100644
--- a/frmts/pcidsk/sdk/channel/ctiledchannel.cpp
+++ b/frmts/pcidsk/sdk/channel/ctiledchannel.cpp
@@ -41,6 +41,8 @@
 #include <cstdlib>
 #include <cstring>
 
+#include "cpl_port.h"
+
 using namespace PCIDSK;
 
 /************************************************************************/
@@ -49,7 +51,7 @@ using namespace PCIDSK;
 
 CTiledChannel::CTiledChannel( PCIDSKBuffer &image_header, 
                               uint64 ih_offset,
-                              PCIDSKBuffer &file_header,
+                              CPL_UNUSED PCIDSKBuffer &file_header,
                               int channelnum,
                               CPCIDSKFile *file,
                               eChanType pixel_type )
diff --git a/frmts/pcidsk/sdk/segment/cpcidsktoutinmodel.cpp b/frmts/pcidsk/sdk/segment/cpcidsktoutinmodel.cpp
index 8d9eba7..7ce2f5d 100644
--- a/frmts/pcidsk/sdk/segment/cpcidsktoutinmodel.cpp
+++ b/frmts/pcidsk/sdk/segment/cpcidsktoutinmodel.cpp
@@ -48,10 +48,12 @@ namespace
      * 
      * @return The minimum value of the two specified values.
      */
-    int MinFunction(int a,int b) 
+#if 0  /* Unused */
+    int MinFunction(int a,int b)
     {
         return (a<b)?a:b;
     }
+#endif
 }
 
 CPCIDSKToutinModelSegment::CPCIDSKToutinModelSegment(PCIDSKFile *file, 
diff --git a/frmts/pcraster/libcsf/dumconv.c b/frmts/pcraster/libcsf/dumconv.c
index e6462bd..08aa63c 100644
--- a/frmts/pcraster/libcsf/dumconv.c
+++ b/frmts/pcraster/libcsf/dumconv.c
@@ -63,8 +63,8 @@
  * does nothing
  */
 void CsfDummyConversion(
-	size_t  nrCells,  
-	void   *buf )
+                        CPL_UNUSED size_t nrCells,  
+                        CPL_UNUSED void *buf )
 {
 	/* nothing */
 }
diff --git a/frmts/pcraster/libcsf/putattr.c b/frmts/pcraster/libcsf/putattr.c
index 45fb576..cbb8211 100644
--- a/frmts/pcraster/libcsf/putattr.c
+++ b/frmts/pcraster/libcsf/putattr.c
@@ -179,7 +179,7 @@ CSF_FADDR CsfSeekAttrSpace(
 						endBlock = b.next;
 					else
 						endBlock = b.attrs[i+1].attrOffset;
-					if (( endBlock - b.attrs[i].attrOffset)
+					if ((size_t)(endBlock - b.attrs[i].attrOffset)
 						>= size)
 						/* this position can
 							hold the attr */
diff --git a/frmts/pcraster/libcsf/swapio.c b/frmts/pcraster/libcsf/swapio.c
index 93067f8..b0c6506 100644
--- a/frmts/pcraster/libcsf/swapio.c
+++ b/frmts/pcraster/libcsf/swapio.c
@@ -52,7 +52,7 @@ int CsfValidSize(size_t size)
 #endif
 
 /* ARGSUSED */
-static void Swap1(unsigned char * buf,  size_t n)
+static void Swap1(CPL_UNUSED unsigned char * buf,  CPL_UNUSED size_t n)
 {
 	/* do nothing */
 }
diff --git a/frmts/pcraster/pcrasterdataset.cpp b/frmts/pcraster/pcrasterdataset.cpp
index f88a0fb..682582c 100644
--- a/frmts/pcraster/pcrasterdataset.cpp
+++ b/frmts/pcraster/pcrasterdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: pcrasterdataset.cpp 22609 2011-06-28 21:01:48Z rouault $
+ * $Id: pcrasterdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PCRaster Integration
  * Purpose:  PCRaster CSF 2.0 raster file driver
@@ -30,7 +30,7 @@
 #include "gdal_pam.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: pcrasterdataset.cpp 22609 2011-06-28 21:01:48Z rouault $");
+CPL_CVSID("$Id: pcrasterdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #ifndef INCLUDED_PCRASTERDATASET
 #include "pcrasterdataset.h"
@@ -125,8 +125,8 @@ GDALDataset* PCRasterDataset::open(
 GDALDataset* PCRasterDataset::createCopy(
          char const* filename,
          GDALDataset* source,
-         int strict,
-         char** options,
+         CPL_UNUSED int strict,
+         CPL_UNUSED char** options,
          GDALProgressFunc progress,
          void* progressData)
 {
diff --git a/frmts/pcraster/pcrasterrasterband.cpp b/frmts/pcraster/pcrasterrasterband.cpp
index 8e0ab80..3657d78 100644
--- a/frmts/pcraster/pcrasterrasterband.cpp
+++ b/frmts/pcraster/pcrasterrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: pcrasterrasterband.cpp 15453 2008-10-03 11:00:02Z kdejong $
+ * $Id: pcrasterrasterband.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PCRaster Integration
  * Purpose:  PCRaster raster band implementation.
@@ -248,9 +248,9 @@ double PCRasterRasterBand::GetMaximum(
 
 
 CPLErr PCRasterRasterBand::IReadBlock(
-         int nBlockXoff,
-         int nBlockYoff,
-         void* buffer)
+                                      CPL_UNUSED int nBlockXoff,
+                                      int nBlockYoff,
+                                      void* buffer)
 {
   size_t nrCellsRead = RgetRow(d_dataset->map(), nBlockYoff, buffer);
 
diff --git a/frmts/pdf/pdfdataset.cpp b/frmts/pdf/pdfdataset.cpp
index 8db8999..03d41aa 100644
--- a/frmts/pdf/pdfdataset.cpp
+++ b/frmts/pdf/pdfdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: pdfdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: pdfdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PDF driver
  * Purpose:  GDALDataset driver for PDF dataset.
@@ -55,7 +55,7 @@
 
 /* g++ -fPIC -g -Wall frmts/pdf/pdfdataset.cpp -shared -o gdal_PDF.so -Iport -Igcore -Iogr -L. -lgdal -lpoppler -I/usr/include/poppler */
 
-CPL_CVSID("$Id: pdfdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: pdfdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_PDF(void);
@@ -5167,7 +5167,16 @@ CPLErr PDFDataset::SetGCPs( int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
 /*                          GDALPDFOpen()                               */
 /************************************************************************/
 
-GDALDataset* GDALPDFOpen(const char* pszFilename, GDALAccess eAccess)
+GDALDataset* GDALPDFOpen(
+#if !defined(HAVE_POPPLER) && !defined(HAVE_PODOFO)
+CPL_UNUSED
+#endif
+                         const char* pszFilename,
+#if !defined(HAVE_POPPLER) && !defined(HAVE_PODOFO)
+CPL_UNUSED
+#endif
+                         GDALAccess eAccess
+                         )
 {
 #if defined(HAVE_POPPLER) || defined(HAVE_PODOFO)
     GDALOpenInfo oOpenInfo(pszFilename, eAccess);
@@ -5181,7 +5190,12 @@ GDALDataset* GDALPDFOpen(const char* pszFilename, GDALAccess eAccess)
 /*                       GDALPDFUnloadDriver()                          */
 /************************************************************************/
 
-static void GDALPDFUnloadDriver(GDALDriver * poDriver)
+static void GDALPDFUnloadDriver(
+#ifndef HAVE_POPPLER
+CPL_UNUSED
+#endif
+                                GDALDriver * poDriver
+)
 {
 #ifdef HAVE_POPPLER
     if( hGlobalParamsMutex != NULL )
diff --git a/frmts/pdf/pdfobject.h b/frmts/pdf/pdfobject.h
index a1efe83..66da72a 100644
--- a/frmts/pdf/pdfobject.h
+++ b/frmts/pdf/pdfobject.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: pdfobject.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: pdfobject.h 27331 2014-05-14 16:25:25Z rouault $
  *
  * Project:  PDF driver
  * Purpose:  GDALDataset driver for PDF dataset.
@@ -66,6 +66,15 @@
 #endif // HAVE_POPPLER
 
 #ifdef HAVE_PODOFO
+/*
+ * Some Windows header defines a GetObject macro that
+ * shadows a GetObject() method in PoDoFo. This
+ * workaround is documented in the PoDoFo source.
+ */ 
+#ifdef GetObject
+#undef GetObject
+#endif
+
 #include "podofo.h"
 #endif // HAVE_PODOFO
 
diff --git a/frmts/pds/isis2dataset.cpp b/frmts/pds/isis2dataset.cpp
index 25a0ffc..2133035 100644
--- a/frmts/pds/isis2dataset.cpp
+++ b/frmts/pds/isis2dataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: isis2dataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: isis2dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ISIS Version 2 Driver
  * Purpose:  Implementation of ISIS2Dataset
@@ -50,7 +50,7 @@
 #include "cpl_string.h" 
 #include "nasakeywordhandler.h"
 
-CPL_CVSID("$Id: isis2dataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: isis2dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_ISIS2(void);
@@ -962,7 +962,11 @@ GDALDataset *ISIS2Dataset::Create(const char* pszFilename,
 /*                            WriteRaster()                             */
 /************************************************************************/
 
-int ISIS2Dataset::WriteRaster(CPLString osFilename, bool includeLabel, GUIntBig iRecords, GUIntBig iLabelRecords, GDALDataType eType, const char * pszInterleaving) {
+int ISIS2Dataset::WriteRaster(CPLString osFilename,
+                              bool includeLabel,
+                              GUIntBig iRecords,
+                              GUIntBig iLabelRecords,
+                              CPL_UNUSED GDALDataType eType, CPL_UNUSED const char * pszInterleaving) {
     GUIntBig nSize;
     GByte byZero(0);
     CPLString pszAccess("wb");
@@ -1092,7 +1096,7 @@ int ISIS2Dataset::WriteLabel(
     unsigned int nXSize, unsigned int nYSize, unsigned int nBands, 
     GDALDataType eType,
     GUIntBig iRecords, const char * pszInterleaving, 
-    GUIntBig &iLabelRecords, bool bRelaunch)
+    GUIntBig &iLabelRecords, CPL_UNUSED bool bRelaunch)
 
 {
     CPLDebug("ISIS2", "Write Label filename = %s, rasterfile = %s",osFilename.c_str(),osRasterFile.c_str());
diff --git a/frmts/png/pngdataset.cpp b/frmts/png/pngdataset.cpp
index 67e3a82..c36190e 100644
--- a/frmts/png/pngdataset.cpp
+++ b/frmts/png/pngdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: pngdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: pngdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PNG Driver
  * Purpose:  Implement GDAL PNG Support
@@ -50,7 +50,7 @@
 #include "cpl_string.h"
 #include <setjmp.h>
 
-CPL_CVSID("$Id: pngdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: pngdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_PNG(void);
@@ -1816,7 +1816,7 @@ static void png_gdal_error( png_structp png_ptr, const char *error_message )
 /*                          png_gdal_warning()                          */
 /************************************************************************/
 
-static void png_gdal_warning( png_structp png_ptr, const char *error_message )
+static void png_gdal_warning( CPL_UNUSED png_structp png_ptr, const char *error_message )
 {
     CPLError( CE_Warning, CPLE_AppDefined, 
               "libpng: %s", error_message );
diff --git a/frmts/postgisraster/postgisrasterdataset.cpp b/frmts/postgisraster/postgisrasterdataset.cpp
index 696984f..98d1cd7 100644
--- a/frmts/postgisraster/postgisrasterdataset.cpp
+++ b/frmts/postgisraster/postgisrasterdataset.cpp
@@ -2040,7 +2040,8 @@ GBool PostGISRasterDataset::SetRasterProperties
             "from (select srid, extent geom, num_bands nbband, "
             "scale_x, scale_y, blocksize_x, blocksize_y, same_alignment, regular_blocking from "
             "raster_columns where r_table_schema = '%s' and "
-            "r_table_name = '%s') foo", pszSchema, pszTable);
+            "r_table_name = '%s' and r_raster_column = '%s' ) foo",
+            pszSchema, pszTable, pszColumn);
             
 #ifdef DEBUG_QUERY
         CPLDebug("PostGIS_Raster", 
diff --git a/frmts/r/rcreatecopy.cpp b/frmts/r/rcreatecopy.cpp
index c7926bf..a04d42b 100644
--- a/frmts/r/rcreatecopy.cpp
+++ b/frmts/r/rcreatecopy.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: rcreatecopy.cpp 20996 2010-10-28 18:38:15Z rouault $
+ * $Id: rcreatecopy.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  R Format Driver
  * Purpose:  CreateCopy() implementation for R stats package object format.
@@ -30,7 +30,7 @@
 #include "gdal_pam.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: rcreatecopy.cpp 20996 2010-10-28 18:38:15Z rouault $");
+CPL_CVSID("$Id: rcreatecopy.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -85,7 +85,7 @@ static void RWriteString( VSILFILE *fp, int bASCII, const char *pszValue )
 
 GDALDataset *
 RCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-             int bStrict, char ** papszOptions, 
+             CPL_UNUSED int bStrict, char ** papszOptions, 
              GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/r/rdataset.cpp b/frmts/r/rdataset.cpp
index 44af32f..4e16240 100644
--- a/frmts/r/rdataset.cpp
+++ b/frmts/r/rdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: rdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: rdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  R Format Driver
  * Purpose:  Read/write R stats package object format.
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "../raw/rawdataset.h"
 
-CPL_CVSID("$Id: rdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: rdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_R(void);
@@ -130,7 +130,7 @@ RRasterBand::~RRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr RRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr RRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                 void * pImage )
 {
     memcpy( pImage, padfMatrixValues + nBlockYOff * nBlockXSize,
diff --git a/frmts/rasterlite/rasterlitecreatecopy.cpp b/frmts/rasterlite/rasterlitecreatecopy.cpp
index d26c7e3..f1502ac 100644
--- a/frmts/rasterlite/rasterlitecreatecopy.cpp
+++ b/frmts/rasterlite/rasterlitecreatecopy.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: rasterlitecreatecopy.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: rasterlitecreatecopy.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GDAL Rasterlite driver
  * Purpose:  Implement GDAL Rasterlite support using OGR SQLite driver
@@ -33,7 +33,7 @@
 
 #include "rasterlitedataset.h"
 
-CPL_CVSID("$Id: rasterlitecreatecopy.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: rasterlitecreatecopy.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                  RasterliteGetTileDriverOptions ()                   */
@@ -323,7 +323,7 @@ OGRDataSourceH RasterliteCreateTables(OGRDataSourceH hDS, const char* pszTableNa
 
 GDALDataset *
 RasterliteCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-                       int bStrict, char ** papszOptions, 
+                       CPL_UNUSED int bStrict, CPL_UNUSED char ** papszOptions, 
                        GDALProgressFunc pfnProgress, void * pProgressData )
 {
     int nBands = poSrcDS->GetRasterCount();
@@ -727,7 +727,7 @@ RasterliteCreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
 /*                         RasterliteDelete ()                          */
 /************************************************************************/
 
-CPLErr RasterliteDelete(const char* pszFilename)
+CPLErr RasterliteDelete(CPL_UNUSED const char* pszFilename)
 {
     return CE_None;
 }
diff --git a/frmts/raw/btdataset.cpp b/frmts/raw/btdataset.cpp
index 114c5d9..13041bb 100644
--- a/frmts/raw/btdataset.cpp
+++ b/frmts/raw/btdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: btdataset.cpp 27192 2014-04-16 09:59:42Z rouault $
+ * $Id: btdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  VTP .bt Driver
  * Purpose:  Implementation of VTP .bt elevation format read/write support.
@@ -32,7 +32,7 @@
 #include "rawdataset.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: btdataset.cpp 27192 2014-04-16 09:59:42Z rouault $");
+CPL_CVSID("$Id: btdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_BT(void);
@@ -125,9 +125,9 @@ BTRasterBand::BTRasterBand( GDALDataset *poDS, VSILFILE *fp, GDALDataType eType
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr BTRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
-                                  void * pImage )
-
+CPLErr BTRasterBand::IReadBlock( int nBlockXOff,
+                                 CPL_UNUSED int nBlockYOff,
+                                 void * pImage )
 {
     int nDataSize = GDALGetDataTypeSize( eDataType ) / 8;
     int i;
@@ -187,9 +187,9 @@ CPLErr BTRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 /*                            IWriteBlock()                             */
 /************************************************************************/
 
-CPLErr BTRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff,
+CPLErr BTRasterBand::IWriteBlock( int nBlockXOff, 
+                                  CPL_UNUSED int nBlockYOff,
                                   void * pImage )
-
 {
     int nDataSize = GDALGetDataTypeSize( eDataType ) / 8;
     GByte *pabyWrkBlock;
@@ -807,9 +807,9 @@ GDALDataset *BTDataset::Open( GDALOpenInfo * poOpenInfo )
 /************************************************************************/
 
 GDALDataset *BTDataset::Create( const char * pszFilename,
-                                 int nXSize, int nYSize, int nBands,
-                                 GDALDataType eType,
-                                 char ** papszOptions )
+                                int nXSize, int nYSize, int nBands,
+                                GDALDataType eType,
+                                CPL_UNUSED char ** papszOptions )
 
 {
 
diff --git a/frmts/raw/cpgdataset.cpp b/frmts/raw/cpgdataset.cpp
index 6f050cc..563d635 100644
--- a/frmts/raw/cpgdataset.cpp
+++ b/frmts/raw/cpgdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Polarimetric Workstation
  * Purpose:  Convair PolGASP data (.img/.hdr format). 
@@ -32,7 +32,7 @@
 #include "ogr_spatialref.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: cpgdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpgdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_CPG(void);
@@ -1264,7 +1264,7 @@ Im(SVV) = byte(10) ysca/127
 
 */
 
-CPLErr SIRC_QSLCRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr SIRC_QSLCRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -1417,7 +1417,7 @@ CPG_STOKESRasterBand::~CPG_STOKESRasterBand()
 
 /* Convert from Stokes to Covariance representation */
 
-CPLErr CPG_STOKESRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr CPG_STOKESRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
diff --git a/frmts/raw/ctable2dataset.cpp b/frmts/raw/ctable2dataset.cpp
index 37e60c4..7a6472e 100644
--- a/frmts/raw/ctable2dataset.cpp
+++ b/frmts/raw/ctable2dataset.cpp
@@ -326,7 +326,7 @@ const char *CTable2Dataset::GetProjectionRef()
 /************************************************************************/
 
 GDALDataset *CTable2Dataset::Create( const char * pszFilename,
-                                     int nXSize, int nYSize, int nBands,
+                                     int nXSize, int nYSize, CPL_UNUSED int nBands,
                                      GDALDataType eType,
                                      char ** papszOptions )
 
diff --git a/frmts/raw/envidataset.cpp b/frmts/raw/envidataset.cpp
index 02fd840..6de8f2c 100644
--- a/frmts/raw/envidataset.cpp
+++ b/frmts/raw/envidataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: envidataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: envidataset.cpp 27366 2014-05-19 18:27:40Z rouault $
  *
  * Project:  ENVI .hdr Driver
  * Purpose:  Implementation of ENVI .hdr labelled raw raster support.
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include <algorithm>
 
-CPL_CVSID("$Id: envidataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: envidataset.cpp 27366 2014-05-19 18:27:40Z rouault $");
 
 CPL_C_START
 void GDALRegister_ENVI(void);
@@ -370,6 +370,11 @@ void ENVIDataset::FlushCache()
 
     CPLLocaleC  oLocaleEnforcer;
 
+    // If opening an existing file in Update mode (i.e. "r+") we need to make
+    // sure any existing content is cleared, otherwise the file may contain
+    // trailing content from the previous write.
+    VSIFTruncateL( fp, 0 ); 
+
     VSIFSeekL( fp, 0, SEEK_SET );
 /* -------------------------------------------------------------------- */
 /*      Rewrite out the header.                                           */
@@ -668,14 +673,15 @@ void ENVIDataset::WriteProjectionInfo()
 /*      Minimal case - write out simple geotransform if we have a       */
 /*      non-default geotransform.                                       */
 /* -------------------------------------------------------------------- */
-    if( pszProjection == NULL || strlen(pszProjection) == 0 )
+    if( pszProjection == NULL || strlen(pszProjection) == 0  ||
+        (strlen(pszProjection) >= 8 && strncmp(pszProjection, "LOCAL_CS", 8) == 0 ) )
     {
         if( adfGeoTransform[0] != 0.0 || adfGeoTransform[1] != 1.0
             || adfGeoTransform[2] != 0.0 || adfGeoTransform[3] != 0.0
             || adfGeoTransform[4] != 0.0 || adfGeoTransform[5] != 1.0 )
         {
             const char* pszHemisphere = "North";
-            VSIFPrintfL( fp, "map info = {Unknown, %s, %d, %s}\n",
+            VSIFPrintfL( fp, "map info = {Arbitrary, %s, %d, %s}\n",
                          osLocation.c_str(), 0, pszHemisphere);
         }
         return;
@@ -2504,6 +2510,10 @@ GDALDataset *ENVIDataset::Open( GDALOpenInfo * poOpenInfo )
 /* -------------------------------------------------------------------- */
     poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename );
 
+    // SetMetadata() calls in Open() makes the header dirty. 
+    // Don't re-write the header if nothing external has changed the metadata 
+    poDS->bHeaderDirty = FALSE; 
+
     return( poDS );
 }
 
diff --git a/frmts/raw/genbindataset.cpp b/frmts/raw/genbindataset.cpp
index 683780f..8f6a7b9 100644
--- a/frmts/raw/genbindataset.cpp
+++ b/frmts/raw/genbindataset.cpp
@@ -257,7 +257,7 @@ GenBinBitRasterBand::GenBinBitRasterBand( GenBinDataset *poDS, int nBitsIn )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GenBinBitRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr GenBinBitRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                         void * pImage )
 
 {
diff --git a/frmts/raw/gtxdataset.cpp b/frmts/raw/gtxdataset.cpp
index cd19cd5..f9410f9 100644
--- a/frmts/raw/gtxdataset.cpp
+++ b/frmts/raw/gtxdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gtxdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gtxdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Vertical Datum Transformation
  * Purpose:  Implementation of NOAA .gtx vertical datum shift file format.
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: gtxdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gtxdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /**
 
@@ -314,9 +314,9 @@ const char *GTXDataset::GetProjectionRef()
 /************************************************************************/
 
 GDALDataset *GTXDataset::Create( const char * pszFilename,
-                                 int nXSize, int nYSize, int nBands,
+                                 int nXSize, int nYSize, CPL_UNUSED int nBands,
                                  GDALDataType eType,
-                                 char ** papszOptions )
+                                 CPL_UNUSED char ** papszOptions )
 
 {
     if( eType != GDT_Float32 )
diff --git a/frmts/raw/hkvdataset.cpp b/frmts/raw/hkvdataset.cpp
index d7489bf..38e9cc2 100644
--- a/frmts/raw/hkvdataset.cpp
+++ b/frmts/raw/hkvdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hkvdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hkvdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GView
  * Purpose:  Implementation of Atlantis HKV labelled blob support
@@ -34,7 +34,7 @@
 #include "ogr_spatialref.h"
 #include "atlsci_spheroid.h"
 
-CPL_CVSID("$Id: hkvdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hkvdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_HKV(void);
@@ -1713,7 +1713,7 @@ CPLErr HKVDataset::Delete( const char * pszName )
 
 GDALDataset *
 HKVDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-                        int bStrict, char ** papszOptions, 
+                        CPL_UNUSED int bStrict, char ** papszOptions, 
                         GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/raw/krodataset.cpp b/frmts/raw/krodataset.cpp
index f9fb7be..5a7e4d8 100644
--- a/frmts/raw/krodataset.cpp
+++ b/frmts/raw/krodataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: krodataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: krodataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  KRO format reader/writer
  * Purpose:  Implementation of KOLOR Raw Format
@@ -31,7 +31,7 @@
 #include "rawdataset.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: krodataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: krodataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /* http://www.autopano.net/wiki-en/Format_KRO */
 
@@ -220,10 +220,9 @@ GDALDataset *KRODataset::Open( GDALOpenInfo * poOpenInfo )
 /************************************************************************/
 
 GDALDataset *KRODataset::Create( const char * pszFilename,
-                                  int nXSize, int nYSize, int nBands,
-                                  GDALDataType eType,
-                                  char ** papszOptions )
-
+                                 int nXSize, int nYSize, int nBands,
+                                 GDALDataType eType,
+                                 CPL_UNUSED char ** papszOptions )
 {
     if( eType != GDT_Byte && eType != GDT_UInt16 && eType != GDT_Float32 )
     {
diff --git a/frmts/raw/landataset.cpp b/frmts/raw/landataset.cpp
index ea8c77e..1f3f906 100644
--- a/frmts/raw/landataset.cpp
+++ b/frmts/raw/landataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: landataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: landataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  eCognition
  * Purpose:  Implementation of Erdas .LAN / .GIS format.
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: landataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: landataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_LAN(void);
@@ -200,7 +200,7 @@ LAN4BitRasterBand::~LAN4BitRasterBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr LAN4BitRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr LAN4BitRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                       void * pImage )
 
 {
@@ -850,7 +850,7 @@ void LANDataset::CheckForStatistics()
 GDALDataset *LANDataset::Create( const char * pszFilename,
                                  int nXSize, int nYSize, int nBands,
                                  GDALDataType eType,
-                                 char ** papszOptions )
+                                 CPL_UNUSED char ** papszOptions )
 
 {
     if( eType != GDT_Byte && eType != GDT_Int16 )
diff --git a/frmts/raw/mffdataset.cpp b/frmts/raw/mffdataset.cpp
index d725857..4725d75 100644
--- a/frmts/raw/mffdataset.cpp
+++ b/frmts/raw/mffdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: mffdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: mffdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GView
  * Purpose:  Implementation of Atlantis MFF Support
@@ -34,7 +34,7 @@
 #include "ogr_spatialref.h"
 #include "atlsci_spheroid.h"
 
-CPL_CVSID("$Id: mffdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: mffdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_MFF(void);
@@ -1221,7 +1221,7 @@ GDALDataset *MFFDataset::Create( const char * pszFilenameIn,
 
 GDALDataset *
 MFFDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-                        int bStrict, char ** papszOptions, 
+                        CPL_UNUSED int bStrict, char ** papszOptions, 
                         GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/raw/ntv2dataset.cpp b/frmts/raw/ntv2dataset.cpp
index b922974..3f57b57 100644
--- a/frmts/raw/ntv2dataset.cpp
+++ b/frmts/raw/ntv2dataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ntv2dataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ntv2dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Horizontal Datum Formats
  * Purpose:  Implementation of NTv2 datum shift format used in Canada, France, 
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ntv2dataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ntv2dataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /** 
  * The header for the file, and each grid consists of 11 16byte records.
@@ -658,7 +658,7 @@ const char *NTv2Dataset::GetProjectionRef()
 /************************************************************************/
 
 GDALDataset *NTv2Dataset::Create( const char * pszFilename,
-                                  int nXSize, int nYSize, int nBands,
+                                  int nXSize, int nYSize, CPL_UNUSED int nBands,
                                   GDALDataType eType,
                                   char ** papszOptions )
 
diff --git a/frmts/raw/rawdataset.cpp b/frmts/raw/rawdataset.cpp
index 6c0ec1c..b1b1fa0 100644
--- a/frmts/raw/rawdataset.cpp
+++ b/frmts/raw/rawdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: rawdataset.cpp 27194 2014-04-16 10:07:21Z rouault $
+ * $Id: rawdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Generic Raw Binary Driver
  * Purpose:  Implementation of RawDataset and RawRasterBand classes.
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: rawdataset.cpp 27194 2014-04-16 10:07:21Z rouault $");
+CPL_CVSID("$Id: rawdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           RawRasterBand()                            */
@@ -348,7 +348,7 @@ CPLErr RawRasterBand::AccessLine( int iLine )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr RawRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr RawRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -375,7 +375,7 @@ CPLErr RawRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 /*                            IWriteBlock()                             */
 /************************************************************************/
 
-CPLErr RawRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff,
+CPLErr RawRasterBand::IWriteBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                    void * pImage )
 
 {
@@ -574,8 +574,8 @@ int RawRasterBand::IsSignificantNumberOfLinesLoaded( int nLineOff, int nLines )
 /*                           CanUseDirectIO()                           */
 /************************************************************************/
 
-int RawRasterBand::CanUseDirectIO(int nXOff, int nYOff, int nXSize, int nYSize,
-                                  GDALDataType eBufType)
+int RawRasterBand::CanUseDirectIO(CPL_UNUSED int nXOff, int nYOff, int nXSize, int nYSize,
+                                  CPL_UNUSED GDALDataType eBufType)
 {
 
 /* -------------------------------------------------------------------- */
diff --git a/frmts/sdts/sdtsrasterreader.cpp b/frmts/sdts/sdtsrasterreader.cpp
index c484a19..41ac301 100644
--- a/frmts/sdts/sdtsrasterreader.cpp
+++ b/frmts/sdts/sdtsrasterreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: sdtsrasterreader.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: sdtsrasterreader.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SDTS Translator
  * Purpose:  Implementation of SDTSRasterReader class.
@@ -30,7 +30,7 @@
 
 #include "sdts_al.h"
 
-CPL_CVSID("$Id: sdtsrasterreader.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: sdtsrasterreader.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          SDTSRasterReader()                          */
@@ -363,8 +363,7 @@ int SDTSRasterReader::Open( SDTS_CATD * poCATD, SDTS_IREF * poIREF,
 
   */
 
-int SDTSRasterReader::GetBlock( int nXOffset, int nYOffset, void * pData )
-
+int SDTSRasterReader::GetBlock( CPL_UNUSED int nXOffset, int nYOffset, void * pData )
 {
     DDFRecord   *poRecord = NULL;
     int         nBytesPerValue;
diff --git a/frmts/sgi/sgidataset.cpp b/frmts/sgi/sgidataset.cpp
index 208d5ef..198291d 100644
--- a/frmts/sgi/sgidataset.cpp
+++ b/frmts/sgi/sgidataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: sgidataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: sgidataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SGI Image Driver
  * Purpose:  Implement SGI Image Support based on Paul Bourke's SGI Image code.
@@ -36,7 +36,7 @@
 #include "cpl_port.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: sgidataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: sgidataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_SGI(void);
@@ -266,7 +266,7 @@ SGIRasterBand::SGIRasterBand(SGIDataset* poDS, int nBand)
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr SGIRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
+CPLErr SGIRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
 				 void*  pImage)
 
 {
@@ -284,7 +284,7 @@ CPLErr SGIRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
 /*                             IWritelock()                             */
 /************************************************************************/
 
-CPLErr SGIRasterBand::IWriteBlock(int nBlockXOff, int nBlockYOff,
+CPLErr SGIRasterBand::IWriteBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void*  pImage)
 
 {
@@ -686,7 +686,7 @@ GDALDataset* SGIDataset::Open(GDALOpenInfo* poOpenInfo)
 
 GDALDataset *SGIDataset::Create( const char * pszFilename,
                                  int nXSize, int nYSize, int nBands,
-                                 GDALDataType eType, char **papszOptions )
+                                 GDALDataType eType, CPL_UNUSED char **papszOptions )
 
 {
     if( eType != GDT_Byte )
diff --git a/frmts/srtmhgt/srtmhgtdataset.cpp b/frmts/srtmhgt/srtmhgtdataset.cpp
index aefdb82..03b2570 100644
--- a/frmts/srtmhgt/srtmhgtdataset.cpp
+++ b/frmts/srtmhgt/srtmhgtdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: srtmhgtdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: srtmhgtdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SRTM HGT Driver
  * Purpose:  SRTM HGT File Read Support.
@@ -38,7 +38,7 @@
 
 #define SRTMHG_NODATA_VALUE -32768
 
-CPL_CVSID("$Id: srtmhgtdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: srtmhgtdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_SRTMHGT(void);
@@ -386,7 +386,7 @@ GDALDataset* SRTMHGTDataset::Open(GDALOpenInfo* poOpenInfo)
 /************************************************************************/
 
 GDALDataset * SRTMHGTDataset::CreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-                                          int bStrict, char ** papszOptions, 
+                                          int bStrict, CPL_UNUSED char ** papszOptions, 
                                           GDALProgressFunc pfnProgress, void * pProgressData )
 
 {
diff --git a/frmts/terragen/terragendataset.cpp b/frmts/terragen/terragendataset.cpp
index 9887057..d1c7a52 100644
--- a/frmts/terragen/terragendataset.cpp
+++ b/frmts/terragen/terragendataset.cpp
@@ -106,7 +106,7 @@
 #include "gdal_pam.h"
 #include "ogr_spatialref.h"
 
-// CPL_CVSID("$Id: terragendataset.cpp 21680 2011-02-11 21:12:07Z warmerdam $");
+// CPL_CVSID("$Id: terragendataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_Terragen(void);
@@ -270,7 +270,7 @@ TerragenRasterBand::TerragenRasterBand( TerragenDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr TerragenRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr TerragenRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                        void* pImage )
 
 {
@@ -367,7 +367,7 @@ double TerragenRasterBand::GetOffset(int* pbSuccess)
 
 CPLErr TerragenRasterBand::IWriteBlock
 ( 
-	int nBlockXOff, 
+	CPL_UNUSED int nBlockXOff, 
 	int nBlockYOff,
     void* pImage
 )
diff --git a/frmts/usgsdem/usgsdem_create.cpp b/frmts/usgsdem/usgsdem_create.cpp
index 12c7c8b..202aafa 100644
--- a/frmts/usgsdem/usgsdem_create.cpp
+++ b/frmts/usgsdem/usgsdem_create.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: usgsdem_create.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: usgsdem_create.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  USGS DEM Driver
  * Purpose:  CreateCopy() implementation.
@@ -37,7 +37,7 @@
 #include "gdalwarper.h"
 #include "cpl_csv.h"
 
-CPL_CVSID("$Id: usgsdem_create.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: usgsdem_create.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 typedef struct 
 {
@@ -1269,8 +1269,7 @@ static int USGSDEMProductSetup_DEFAULT( USGSDEMWriteInfo *psWInfo )
 /************************************************************************/
 
 static int USGSDEMLoadRaster( USGSDEMWriteInfo *psWInfo,
-                              GDALRasterBand *poSrcBand )
-
+                              CPL_UNUSED GDALRasterBand *poSrcBand )
 {
     CPLErr eErr;
     int i;
@@ -1397,8 +1396,7 @@ static int USGSDEMLoadRaster( USGSDEMWriteInfo *psWInfo,
 GDALDataset *
 USGSDEMCreateCopy( const char *pszFilename, GDALDataset *poSrcDS, 
                    int bStrict, char **papszOptions,
-                   GDALProgressFunc pfnProgress, void * pProgressData )
-
+                   CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void * pProgressData )
 {
     USGSDEMWriteInfo sWInfo;
 
diff --git a/frmts/usgsdem/usgsdemdataset.cpp b/frmts/usgsdem/usgsdemdataset.cpp
index 86bd73c..1d08d79 100644
--- a/frmts/usgsdem/usgsdemdataset.cpp
+++ b/frmts/usgsdem/usgsdemdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: usgsdemdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: usgsdemdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  USGS DEM Driver
  * Purpose:  All reader for USGS DEM Reader
@@ -34,7 +34,7 @@
 #include "gdal_pam.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: usgsdemdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: usgsdemdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void	GDALRegister_USGSDEM(void);
@@ -327,7 +327,7 @@ USGSDEMRasterBand::USGSDEMRasterBand( USGSDEMDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr USGSDEMRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr USGSDEMRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, CPL_UNUSED int nBlockYOff,
                                       void * pImage )
 
 {
diff --git a/frmts/vrt/vrt_tutorial.dox b/frmts/vrt/vrt_tutorial.dox
index 3cd84b8..20060fc 100644
--- a/frmts/vrt/vrt_tutorial.dox
+++ b/frmts/vrt/vrt_tutorial.dox
@@ -1,5 +1,5 @@
 #ifndef DOXYGEN_SKIP
-/* $Id: vrt_tutorial.dox 27110 2014-03-28 21:29:20Z rouault $ */
+/* $Id: vrt_tutorial.dox 27700 2014-09-20 13:42:12Z goatbar $ */
 #endif /* DOXYGEN_SKIP */
 
 /*!
@@ -642,7 +642,7 @@ should be specified with the above SetMetadata() / SetMetadataItem() examples.
   papszOptions = CSLAddNameValue(papszOptions, "PixelOffset", "2"); // optionnal. default = size of band type 
   papszOptions = CSLAddNameValue(papszOptions, "LineOffset", "1024"); // optionnal. default = size of band type * width 
   papszOptions = CSLAddNameValue(papszOptions, "ByteOrder", "LSB"); // optionnal. default = machine order
-  papszOptions = CSLAddNameValue(papszOptions, "RelativeToVRT", "true"); // optionnal. default = false
+  papszOptions = CSLAddNameValue(papszOptions, "relativeToVRT", "true"); // optionnal. default = false
   poVRTDS->AddBand(GDT_Byte, papszOptions);
   CSLDestroy(papszOptions);
 
diff --git a/frmts/vrt/vrtdataset.cpp b/frmts/vrt/vrtdataset.cpp
index 0906c39..a1e3c0e 100644
--- a/frmts/vrt/vrtdataset.cpp
+++ b/frmts/vrt/vrtdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTDataset
@@ -33,7 +33,7 @@
 #include "cpl_minixml.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: vrtdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: vrtdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            VRTDataset()                             */
@@ -865,7 +865,7 @@ CPLErr VRTDataset::AddBand( GDALDataType eType, char **papszOptions )
         }
         
         bRelativeToVRT = 
-            CSLFetchBoolean( papszOptions, "RelativeToVRT", FALSE );
+            CSLFetchBoolean( papszOptions, "relativeToVRT", FALSE );
 
 /* -------------------------------------------------------------------- */
 /*      Create and initialize the band.                                 */
@@ -1106,7 +1106,7 @@ CPLErr VRTDataset::Delete( const char * pszFilename )
 /*                          CreateMaskBand()                            */
 /************************************************************************/
 
-CPLErr VRTDataset::CreateMaskBand( int nFlags )
+CPLErr VRTDataset::CreateMaskBand( CPL_UNUSED int nFlags )
 {
     if (poMaskBand != NULL)
     {
diff --git a/frmts/vrt/vrtdataset.h b/frmts/vrt/vrtdataset.h
index 766fb13..a4e050a 100644
--- a/frmts/vrt/vrtdataset.h
+++ b/frmts/vrt/vrtdataset.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtdataset.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtdataset.h 27542 2014-07-22 21:25:37Z rouault $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Declaration of virtual gdal dataset classes.
@@ -354,12 +354,14 @@ class VRTSimpleSource;
 class CPL_DLL VRTSourcedRasterBand : public VRTRasterBand
 {
   private:
-    int            bAntiRecursionFlag;
+    int            nRecursionCounter;
     CPLString      osLastLocationInfo;
     char         **papszSourceList;
 
     void           Initialize( int nXSize, int nYSize );
 
+    int            CanUseSourcesMinMaxImplementations();
+
   public:
     int            nSources;
     VRTSource    **papoSources;
diff --git a/frmts/vrt/vrtdriver.cpp b/frmts/vrt/vrtdriver.cpp
index 07d4bc2..8dabe76 100644
--- a/frmts/vrt/vrtdriver.cpp
+++ b/frmts/vrt/vrtdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTDriver
@@ -33,7 +33,7 @@
 #include "cpl_string.h"
 #include "gdal_alg_priv.h"
 
-CPL_CVSID("$Id: vrtdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: vrtdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                             VRTDriver()                              */
@@ -156,8 +156,7 @@ VRTSource *VRTDriver::ParseSource( CPLXMLNode *psSrc, const char *pszVRTPath )
 static GDALDataset *
 VRTCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
                int bStrict, char ** papszOptions, 
-               GDALProgressFunc pfnProgress, void * pProgressData )
-
+               CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void * pProgressData )
 {
     VRTDataset *poVRTDS = NULL;
 
diff --git a/frmts/vrt/vrtrawrasterband.cpp b/frmts/vrt/vrtrawrasterband.cpp
index e6136d1..6d9af68 100644
--- a/frmts/vrt/vrtrawrasterband.cpp
+++ b/frmts/vrt/vrtrawrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtrawrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtrawrasterband.cpp 27502 2014-07-06 15:18:51Z rouault $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTRawRasterBand
@@ -33,7 +33,7 @@
 #include "cpl_string.h"
 #include "rawdataset.h"
 
-CPL_CVSID("$Id: vrtrawrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: vrtrawrasterband.cpp 27502 2014-07-06 15:18:51Z rouault $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -362,6 +362,17 @@ CPLErr VRTRawRasterBand::XMLInit( CPLXMLNode * psTree,
 }
 
 /************************************************************************/
+/*                           VRTRawStripSpace()                         */
+/************************************************************************/
+
+static const char* VRTRawStripSpace(const char* pszStr)
+{
+    while( *pszStr == ' ' )
+        pszStr ++;
+    return pszStr;
+}
+
+/************************************************************************/
 /*                           SerializeToXML()                           */
 /************************************************************************/
 
@@ -408,13 +419,16 @@ CPLXMLNode *VRTRawRasterBand::SerializeToXML( const char *pszVRTPath )
     char szOffset[22];
     
     CPLPrintUIntBig(szOffset, poRawRaster->GetImgOffset(), sizeof(szOffset)-1);
-    CPLCreateXMLElementAndValue(psTree, "ImageOffset", szOffset);
+    szOffset[sizeof(szOffset)-1] = '\0';
+    CPLCreateXMLElementAndValue(psTree, "ImageOffset", VRTRawStripSpace(szOffset));
     
     CPLPrintUIntBig(szOffset, poRawRaster->GetPixelOffset(),sizeof(szOffset)-1);
-    CPLCreateXMLElementAndValue(psTree, "PixelOffset", szOffset);
+    szOffset[sizeof(szOffset)-1] = '\0';
+    CPLCreateXMLElementAndValue(psTree, "PixelOffset", VRTRawStripSpace(szOffset));
     
     CPLPrintUIntBig(szOffset, poRawRaster->GetLineOffset(), sizeof(szOffset)-1);
-    CPLCreateXMLElementAndValue(psTree, "LineOffset", szOffset);
+    szOffset[sizeof(szOffset)-1] = '\0';
+    CPLCreateXMLElementAndValue(psTree, "LineOffset", VRTRawStripSpace(szOffset));
 
 #if CPL_IS_LSB == 1
     if( poRawRaster->GetNativeOrder() )
diff --git a/frmts/vrt/vrtsourcedrasterband.cpp b/frmts/vrt/vrtsourcedrasterband.cpp
index 4ccbb2c..529aab2 100644
--- a/frmts/vrt/vrtsourcedrasterband.cpp
+++ b/frmts/vrt/vrtsourcedrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtsourcedrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtsourcedrasterband.cpp 27542 2014-07-22 21:25:37Z rouault $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTSourcedRasterBand
@@ -32,7 +32,7 @@
 #include "cpl_minixml.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: vrtsourcedrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: vrtsourcedrasterband.cpp 27542 2014-07-22 21:25:37Z rouault $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -95,7 +95,7 @@ void VRTSourcedRasterBand::Initialize( int nXSize, int nYSize )
     nSources = 0;
     papoSources = NULL;
     bEqualAreas = FALSE;
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter = 0;
     papszSourceList = NULL;
 }
 
@@ -134,7 +134,9 @@ CPLErr VRTSourcedRasterBand::IRasterIO( GDALRWFlag eRWFlag,
     /* When using GDALProxyPoolDataset for sources, the recusion will not be */
     /* detected at VRT opening but when doing RasterIO. As the proxy pool will */
     /* return the already opened dataset, we can just test a member variable. */
-    if ( bAntiRecursionFlag )
+    /* We allow 1, since IRasterIO() can be called from ComputeStatistics(), which */
+    /* itselfs increments the recursion counter */
+    if ( nRecursionCounter > 1 )
     {
         CPLError( CE_Failure, CPLE_AppDefined, 
                   "VRTSourcedRasterBand::IRasterIO() called recursively on the same band. "
@@ -191,7 +193,7 @@ CPLErr VRTSourcedRasterBand::IRasterIO( GDALRWFlag eRWFlag,
         }
     }
     
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
 
 /* -------------------------------------------------------------------- */
 /*      Overlay each source in turn over top this.                      */
@@ -204,7 +206,7 @@ CPLErr VRTSourcedRasterBand::IRasterIO( GDALRWFlag eRWFlag,
                                             eBufType, nPixelSpace, nLineSpace);
     }
     
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
     
     return eErr;
 }
@@ -237,6 +239,64 @@ CPLErr VRTSourcedRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
                       nPixelSize, nPixelSize * nBlockXSize );
 }
 
+
+/************************************************************************/
+/*                    CanUseSourcesMinMaxImplementations()              */
+/************************************************************************/
+
+int VRTSourcedRasterBand::CanUseSourcesMinMaxImplementations()
+{
+    const char* pszUseSources = CPLGetConfigOption("VRT_MIN_MAX_FROM_SOURCES", NULL);
+    if( pszUseSources )
+        return CSLTestBoolean(pszUseSources);
+
+    // Use heuristics to determine if we are going to use the source GetMinimum()
+    // or GetMaximum() implementation: all the sources must be "simple" sources
+    // with a dataset description that match a "regular" file on the filesystem,
+    // whose open time and GetMinimum()/GetMaximum() implementations we hope to
+    // be fast enough.
+    // In case of doubt return FALSE
+    for( int iSource = 0; iSource < nSources; iSource++ )
+    {
+        if( !(papoSources[iSource]->IsSimpleSource()) )
+            return FALSE;
+        VRTSimpleSource* poSimpleSource = (VRTSimpleSource*) papoSources[iSource];
+        GDALRasterBand* poBand = poSimpleSource->GetBand();
+        if( poBand == NULL )
+            return FALSE;
+        if( poBand->GetDataset() == NULL )
+            return FALSE;
+        const char* pszFilename = poBand->GetDataset()->GetDescription();
+        if( pszFilename == NULL )
+            return FALSE;
+        /* /vsimem/ should be fast */
+        if( strncmp(pszFilename, "/vsimem/", 8) == 0 )
+            continue;
+        /* but not other /vsi filesystems */
+        if( strncmp(pszFilename, "/vsi", 4) == 0 )
+            return FALSE;
+        int i = 0;
+        char ch;
+        /* We will assume that filenames that are only with ascii characters */
+        /* are real filenames and so we will not try to 'stat' them */
+        for( i = 0; (ch = pszFilename[i]) != '\0'; i++ )
+        {
+            if( !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+                  (ch >= '0' && ch <= '9') || ch == ':' || ch == '/' || ch == '\\' ||
+                  ch == ' ' || ch == '.') )
+                break;
+        }
+        if( ch != '\0' )
+        {
+            /* Otherwise do a real filesystem check */
+            VSIStatBuf sStat;
+            if( VSIStat(pszFilename, &sStat) != 0 )
+                return FALSE;
+        }
+    }
+    return TRUE;
+}
+
 /************************************************************************/
 /*                             GetMinimum()                             */
 /************************************************************************/
@@ -245,6 +305,9 @@ double VRTSourcedRasterBand::GetMinimum( int *pbSuccess )
 {
     const char *pszValue = NULL;
 
+    if( !CanUseSourcesMinMaxImplementations() )
+        return GDALRasterBand::GetMinimum(pbSuccess);
+
     if( (pszValue = GetMetadataItem("STATISTICS_MINIMUM")) != NULL )
     {
         if( pbSuccess != NULL )
@@ -253,7 +316,7 @@ double VRTSourcedRasterBand::GetMinimum( int *pbSuccess )
         return CPLAtofM(pszValue);
     }
 
-    if ( bAntiRecursionFlag )
+    if ( nRecursionCounter > 0 )
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "VRTSourcedRasterBand::GetMinimum() called recursively on the same band. "
@@ -262,7 +325,7 @@ double VRTSourcedRasterBand::GetMinimum( int *pbSuccess )
             *pbSuccess = FALSE;
         return 0.0;
     }
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
 
     double dfMin = 0;
     for( int iSource = 0; iSource < nSources; iSource++ )
@@ -272,7 +335,7 @@ double VRTSourcedRasterBand::GetMinimum( int *pbSuccess )
         if (!bSuccess)
         {
             dfMin = GDALRasterBand::GetMinimum(pbSuccess);
-            bAntiRecursionFlag = FALSE;
+            nRecursionCounter --;
             return dfMin;
         }
 
@@ -280,7 +343,7 @@ double VRTSourcedRasterBand::GetMinimum( int *pbSuccess )
             dfMin = dfSourceMin;
     }
 
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
 
     if( pbSuccess != NULL )
         *pbSuccess = TRUE;
@@ -296,6 +359,9 @@ double VRTSourcedRasterBand::GetMaximum(int *pbSuccess )
 {
     const char *pszValue = NULL;
 
+    if( !CanUseSourcesMinMaxImplementations() )
+        return GDALRasterBand::GetMaximum(pbSuccess);
+
     if( (pszValue = GetMetadataItem("STATISTICS_MAXIMUM")) != NULL )
     {
         if( pbSuccess != NULL )
@@ -304,7 +370,7 @@ double VRTSourcedRasterBand::GetMaximum(int *pbSuccess )
         return CPLAtofM(pszValue);
     }
 
-    if ( bAntiRecursionFlag )
+    if ( nRecursionCounter > 0 )
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "VRTSourcedRasterBand::GetMaximum() called recursively on the same band. "
@@ -313,7 +379,7 @@ double VRTSourcedRasterBand::GetMaximum(int *pbSuccess )
             *pbSuccess = FALSE;
         return 0.0;
     }
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
 
     double dfMax = 0;
     for( int iSource = 0; iSource < nSources; iSource++ )
@@ -323,7 +389,7 @@ double VRTSourcedRasterBand::GetMaximum(int *pbSuccess )
         if (!bSuccess)
         {
             dfMax = GDALRasterBand::GetMaximum(pbSuccess);
-            bAntiRecursionFlag = FALSE;
+            nRecursionCounter --;
             return dfMax;
         }
 
@@ -331,7 +397,7 @@ double VRTSourcedRasterBand::GetMaximum(int *pbSuccess )
             dfMax = dfSourceMax;
     }
 
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
 
     if( pbSuccess != NULL )
         *pbSuccess = TRUE;
@@ -382,14 +448,14 @@ CPLErr VRTSourcedRasterBand::ComputeRasterMinMax( int bApproxOK, double* adfMinM
 /* -------------------------------------------------------------------- */
 /*      Try with source bands.                                          */
 /* -------------------------------------------------------------------- */
-    if ( bAntiRecursionFlag )
+    if ( nRecursionCounter > 0 )
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "VRTSourcedRasterBand::ComputeRasterMinMax() called recursively on the same band. "
                   "It looks like the VRT is referencing itself." );
         return CE_Failure;
     }
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
 
     adfMinMax[0] = 0.0;
     adfMinMax[1] = 0.0;
@@ -400,7 +466,7 @@ CPLErr VRTSourcedRasterBand::ComputeRasterMinMax( int bApproxOK, double* adfMinM
         if (eErr != CE_None)
         {
             eErr = GDALRasterBand::ComputeRasterMinMax(bApproxOK, adfMinMax);
-            bAntiRecursionFlag = FALSE;
+            nRecursionCounter --;
             return eErr;
         }
 
@@ -410,7 +476,7 @@ CPLErr VRTSourcedRasterBand::ComputeRasterMinMax( int bApproxOK, double* adfMinM
             adfMinMax[1] = adfSourceMinMax[1];
     }
 
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
 
     return CE_None;
 }
@@ -427,7 +493,7 @@ VRTSourcedRasterBand::ComputeStatistics( int bApproxOK,
                                    void *pProgressData )
 
 {
-    if( nSources != 1 )
+    if( nSources != 1 || bNoDataValueSet )
         return GDALRasterBand::ComputeStatistics(  bApproxOK,  
                                               pdfMin, pdfMax, 
                                               pdfMean, pdfStdDev,
@@ -455,14 +521,14 @@ VRTSourcedRasterBand::ComputeStatistics( int bApproxOK,
 /* -------------------------------------------------------------------- */
 /*      Try with source bands.                                          */
 /* -------------------------------------------------------------------- */
-    if ( bAntiRecursionFlag )
+    if ( nRecursionCounter > 0 )
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "VRTSourcedRasterBand::ComputeStatistics() called recursively on the same band. "
                   "It looks like the VRT is referencing itself." );
         return CE_Failure;
     }
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
     
     double dfMin = 0.0, dfMax = 0.0, dfMean = 0.0, dfStdDev = 0.0;
 
@@ -476,11 +542,11 @@ VRTSourcedRasterBand::ComputeStatistics( int bApproxOK,
                                                  pdfMin, pdfMax, 
                                                  pdfMean, pdfStdDev,
                                                  pfnProgress, pProgressData);
-        bAntiRecursionFlag = FALSE;
+        nRecursionCounter --;
         return eErr;
     }
 
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
 
     SetStatistics( dfMin, dfMax, dfMean, dfStdDev );
 
@@ -543,14 +609,14 @@ CPLErr VRTSourcedRasterBand::GetHistogram( double dfMin, double dfMax,
 /* -------------------------------------------------------------------- */
 /*      Try with source bands.                                          */
 /* -------------------------------------------------------------------- */
-    if ( bAntiRecursionFlag )
+    if ( nRecursionCounter > 0 )
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "VRTSourcedRasterBand::GetHistogram() called recursively on the same band. "
                   "It looks like the VRT is referencing itself." );
         return CE_Failure;
     }
-    bAntiRecursionFlag = TRUE;
+    nRecursionCounter ++;
 
     CPLErr eErr = papoSources[0]->GetHistogram(GetXSize(), GetYSize(), dfMin, dfMax, nBuckets,
                                                panHistogram,
@@ -562,11 +628,11 @@ CPLErr VRTSourcedRasterBand::GetHistogram( double dfMin, double dfMax,
                                                   nBuckets, panHistogram,
                                                   bIncludeOutOfRange, bApproxOK,
                                                   pfnProgress, pProgressData );
-        bAntiRecursionFlag = FALSE;
+        nRecursionCounter --;
         return eErr;
     }
 
-    bAntiRecursionFlag = FALSE;
+    nRecursionCounter --;
 
     return CE_None;
 }
diff --git a/frmts/vrt/vrtsources.cpp b/frmts/vrt/vrtsources.cpp
index 460c089..c335108 100644
--- a/frmts/vrt/vrtsources.cpp
+++ b/frmts/vrt/vrtsources.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtsources.cpp 27080 2014-03-23 00:26:43Z rouault $
+ * $Id: vrtsources.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTSimpleSource, VRTFuncSource and 
@@ -36,7 +36,7 @@
 
 #include <algorithm>
 
-CPL_CVSID("$Id: vrtsources.cpp 27080 2014-03-23 00:26:43Z rouault $");
+CPL_CVSID("$Id: vrtsources.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -52,8 +52,8 @@ VRTSource::~VRTSource()
 /*                             GetFileList()                            */
 /************************************************************************/
 
-void VRTSource::GetFileList(char*** ppapszFileList, int *pnSize,
-                            int *pnMaxSize, CPLHashSet* hSetFiles)
+void VRTSource::GetFileList(CPL_UNUSED char*** ppapszFileList, CPL_UNUSED int *pnSize,
+                            CPL_UNUSED int *pnMaxSize, CPL_UNUSED CPLHashSet* hSetFiles)
 {
 }
 
@@ -1293,7 +1293,7 @@ VRTAveragedSource::RasterIO( int nXOff, int nYOff, int nXSize, int nYSize,
 /*                             GetMinimum()                             */
 /************************************************************************/
 
-double VRTAveragedSource::GetMinimum( int nXSize, int nYSize, int *pbSuccess )
+double VRTAveragedSource::GetMinimum( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize, int *pbSuccess )
 {
     *pbSuccess = FALSE;
     return 0;
@@ -1303,7 +1303,9 @@ double VRTAveragedSource::GetMinimum( int nXSize, int nYSize, int *pbSuccess )
 /*                             GetMaximum()                             */
 /************************************************************************/
 
-double VRTAveragedSource::GetMaximum( int nXSize, int nYSize, int *pbSuccess )
+double VRTAveragedSource::GetMaximum( CPL_UNUSED int nXSize,
+                                      CPL_UNUSED int nYSize,
+                                      int *pbSuccess )
 {
     *pbSuccess = FALSE;
     return 0;
@@ -1313,7 +1315,10 @@ double VRTAveragedSource::GetMaximum( int nXSize, int nYSize, int *pbSuccess )
 /*                       ComputeRasterMinMax()                          */
 /************************************************************************/
 
-CPLErr VRTAveragedSource::ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax )
+CPLErr VRTAveragedSource::ComputeRasterMinMax( CPL_UNUSED int nXSize,
+                                               CPL_UNUSED int nYSize,
+                                               CPL_UNUSED int bApproxOK,
+                                               CPL_UNUSED double* adfMinMax )
 {
     return CE_Failure;
 }
@@ -1322,11 +1327,11 @@ CPLErr VRTAveragedSource::ComputeRasterMinMax( int nXSize, int nYSize, int bAppr
 /*                         ComputeStatistics()                          */
 /************************************************************************/
 
-CPLErr VRTAveragedSource::ComputeStatistics( int nXSize, int nYSize,
-                                      int bApproxOK, 
-                                      double *pdfMin, double *pdfMax, 
-                                      double *pdfMean, double *pdfStdDev,
-                                      GDALProgressFunc pfnProgress, void *pProgressData )
+CPLErr VRTAveragedSource::ComputeStatistics( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+                                             CPL_UNUSED int bApproxOK, 
+                                             CPL_UNUSED double *pdfMin, CPL_UNUSED double *pdfMax, 
+                                             CPL_UNUSED double *pdfMean, CPL_UNUSED double *pdfStdDev,
+                                             CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void *pProgressData )
 {
     return CE_Failure;
 }
@@ -1335,11 +1340,11 @@ CPLErr VRTAveragedSource::ComputeStatistics( int nXSize, int nYSize,
 /*                            GetHistogram()                            */
 /************************************************************************/
 
-CPLErr VRTAveragedSource::GetHistogram( int nXSize, int nYSize,
-                                  double dfMin, double dfMax,
-                                  int nBuckets, int * panHistogram,
-                                  int bIncludeOutOfRange, int bApproxOK,
-                                  GDALProgressFunc pfnProgress, void *pProgressData )
+CPLErr VRTAveragedSource::GetHistogram( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+                                        CPL_UNUSED double dfMin, CPL_UNUSED double dfMax,
+                                        CPL_UNUSED int nBuckets, CPL_UNUSED int * panHistogram,
+                                        CPL_UNUSED int bIncludeOutOfRange, CPL_UNUSED int bApproxOK,
+                                        CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void *pProgressData )
 {
     return CE_Failure;
 }
@@ -1997,8 +2002,7 @@ VRTFuncSource::~VRTFuncSource()
 /*                           SerializeToXML()                           */
 /************************************************************************/
 
-CPLXMLNode *VRTFuncSource::SerializeToXML( const char * pszVRTPath )
-
+CPLXMLNode *VRTFuncSource::SerializeToXML( CPL_UNUSED const char * pszVRTPath )
 {
     return NULL;
 }
@@ -2041,7 +2045,7 @@ VRTFuncSource::RasterIO( int nXOff, int nYOff, int nXSize, int nYSize,
 /*                             GetMinimum()                             */
 /************************************************************************/
 
-double VRTFuncSource::GetMinimum( int nXSize, int nYSize, int *pbSuccess )
+double VRTFuncSource::GetMinimum( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize, int *pbSuccess )
 {
     *pbSuccess = FALSE;
     return 0;
@@ -2051,7 +2055,7 @@ double VRTFuncSource::GetMinimum( int nXSize, int nYSize, int *pbSuccess )
 /*                             GetMaximum()                             */
 /************************************************************************/
 
-double VRTFuncSource::GetMaximum( int nXSize, int nYSize, int *pbSuccess )
+double VRTFuncSource::GetMaximum( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize, int *pbSuccess )
 {
     *pbSuccess = FALSE;
     return 0;
@@ -2061,7 +2065,10 @@ double VRTFuncSource::GetMaximum( int nXSize, int nYSize, int *pbSuccess )
 /*                       ComputeRasterMinMax()                          */
 /************************************************************************/
 
-CPLErr VRTFuncSource::ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK, double* adfMinMax )
+CPLErr VRTFuncSource::ComputeRasterMinMax( CPL_UNUSED int nXSize,
+                                           CPL_UNUSED int nYSize,
+                                           CPL_UNUSED int bApproxOK,
+                                           CPL_UNUSED double* adfMinMax )
 {
     return CE_Failure;
 }
@@ -2070,11 +2077,11 @@ CPLErr VRTFuncSource::ComputeRasterMinMax( int nXSize, int nYSize, int bApproxOK
 /*                         ComputeStatistics()                          */
 /************************************************************************/
 
-CPLErr VRTFuncSource::ComputeStatistics( int nXSize, int nYSize,
-                                      int bApproxOK, 
-                                      double *pdfMin, double *pdfMax, 
-                                      double *pdfMean, double *pdfStdDev,
-                                      GDALProgressFunc pfnProgress, void *pProgressData )
+CPLErr VRTFuncSource::ComputeStatistics( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+                                         CPL_UNUSED int bApproxOK, 
+                                         CPL_UNUSED double *pdfMin, CPL_UNUSED double *pdfMax, 
+                                         CPL_UNUSED double *pdfMean, CPL_UNUSED double *pdfStdDev,
+                                         CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void *pProgressData )
 {
     return CE_Failure;
 }
@@ -2083,11 +2090,11 @@ CPLErr VRTFuncSource::ComputeStatistics( int nXSize, int nYSize,
 /*                            GetHistogram()                            */
 /************************************************************************/
 
-CPLErr VRTFuncSource::GetHistogram( int nXSize, int nYSize,
-                                  double dfMin, double dfMax,
-                                  int nBuckets, int * panHistogram,
-                                  int bIncludeOutOfRange, int bApproxOK,
-                                  GDALProgressFunc pfnProgress, void *pProgressData )
+CPLErr VRTFuncSource::GetHistogram( CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+                                    CPL_UNUSED double dfMin, CPL_UNUSED double dfMax,
+                                    CPL_UNUSED int nBuckets, CPL_UNUSED int * panHistogram,
+                                    CPL_UNUSED int bIncludeOutOfRange, CPL_UNUSED int bApproxOK,
+                                    CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void *pProgressData )
 {
     return CE_Failure;
 }
diff --git a/frmts/vrt/vrtwarped.cpp b/frmts/vrt/vrtwarped.cpp
index d20b77e..6b3c5b0 100644
--- a/frmts/vrt/vrtwarped.cpp
+++ b/frmts/vrt/vrtwarped.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vrtwarped.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vrtwarped.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Virtual GDAL Datasets
  * Purpose:  Implementation of VRTWarpedRasterBand *and VRTWarpedDataset.
@@ -35,7 +35,7 @@
 #include "gdal_alg_priv.h"
 #include <cassert>
 
-CPL_CVSID("$Id: vrtwarped.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: vrtwarped.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                      GDALAutoCreateWarpedVRT()                       */
@@ -653,9 +653,9 @@ int VRTWarpedOverviewTransform( void *pTransformArg, int bDstToSrc,
 /************************************************************************/
 
 CPLErr 
-VRTWarpedDataset::IBuildOverviews( const char *pszResampling, 
+VRTWarpedDataset::IBuildOverviews( CPL_UNUSED const char *pszResampling, 
                                    int nOverviews, int *panOverviewList, 
-                                   int nListBands, int *panBandList,
+                                   CPL_UNUSED int nListBands, CPL_UNUSED int *panBandList,
                                    GDALProgressFunc pfnProgress, 
                                    void * pProgressData )
     
diff --git a/frmts/wcs/wcsdataset.cpp b/frmts/wcs/wcsdataset.cpp
index 9f2bf08..1e31b4c 100644
--- a/frmts/wcs/wcsdataset.cpp
+++ b/frmts/wcs/wcsdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: wcsdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: wcsdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WCS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WCS.
@@ -34,7 +34,7 @@
 #include "cpl_http.h"
 #include "ogr_spatialref.h"
 
-CPL_CVSID("$Id: wcsdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: wcsdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -500,7 +500,7 @@ WCSDataset::~WCSDataset()
 /*      (FALSE) for a given request configuration and environment.      */
 /************************************************************************/
 
-int WCSDataset::TestUseBlockIO( int nXOff, int nYOff, int nXSize, int nYSize,
+int WCSDataset::TestUseBlockIO( CPL_UNUSED int nXOff, CPL_UNUSED int nYOff, int nXSize, int nYSize,
                                 int nBufXSize, int nBufYSize )
 
 {
@@ -557,7 +557,7 @@ CPLErr WCSDataset::IRasterIO( GDALRWFlag eRWFlag,
 /************************************************************************/
 
 CPLErr 
-WCSDataset::DirectRasterIO( GDALRWFlag eRWFlag,
+WCSDataset::DirectRasterIO( CPL_UNUSED GDALRWFlag eRWFlag,
                             int nXOff, int nYOff, int nXSize, int nYSize,
                             void * pData, int nBufXSize, int nBufYSize,
                             GDALDataType eBufType, 
diff --git a/frmts/wms/gdalwmscache.cpp b/frmts/wms/gdalwmscache.cpp
index 23c7858..0074fbb 100644
--- a/frmts/wms/gdalwmscache.cpp
+++ b/frmts/wms/gdalwmscache.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwmscache.cpp 26900 2014-01-29 21:55:45Z rouault $
+ * $Id: gdalwmscache.cpp 27555 2014-08-02 17:47:11Z rouault $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -58,9 +58,6 @@ CPLErr GDALWMSCache::Initialize(CPLXMLNode *config) {
         }
     }
 
-    const char *cache_path = CPLGetXMLValue(config, "Path", "./gdalwmscache");
-    m_cache_path = cache_path;
-
     const char *cache_depth = CPLGetXMLValue(config, "Depth", "2");
     m_cache_depth = atoi(cache_depth);
 
diff --git a/frmts/wms/gdalwmsdataset.cpp b/frmts/wms/gdalwmsdataset.cpp
index a7f0a5a..03e9ec1 100644
--- a/frmts/wms/gdalwmsdataset.cpp
+++ b/frmts/wms/gdalwmsdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwmsdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalwmsdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -571,7 +571,7 @@ const char *GDALWMSDataset::GetProjectionRef() {
 /************************************************************************/
 /*                           SetProjection()                            */
 /************************************************************************/
-CPLErr GDALWMSDataset::SetProjection(const char *proj) {
+CPLErr GDALWMSDataset::SetProjection(CPL_UNUSED const char *proj) {
     return CE_Failure;
 }
 
@@ -591,15 +591,18 @@ CPLErr GDALWMSDataset::GetGeoTransform(double *gt) {
 /************************************************************************/
 /*                          SetGeoTransform()                           */
 /************************************************************************/
-CPLErr GDALWMSDataset::SetGeoTransform(double *gt) {
+CPLErr GDALWMSDataset::SetGeoTransform(CPL_UNUSED double *gt) {
     return CE_Failure;
 }
 
 /************************************************************************/
 /*                             AdviseRead()                             */
 /************************************************************************/
-CPLErr GDALWMSDataset::AdviseRead(int x0, int y0, int sx, int sy, int bsx, int bsy, GDALDataType bdt, int band_count, int *band_map, char **options) {
-//    printf("AdviseRead(%d, %d, %d, %d)\n", x0, y0, sx, sy);
+CPLErr GDALWMSDataset::AdviseRead(int x0, int y0,
+                                  int sx, int sy,
+                                  int bsx, int bsy,
+                                  GDALDataType bdt, CPL_UNUSED int band_count, CPL_UNUSED int *band_map,
+                                  char **options) {
     if (m_offline_mode || !m_use_advise_read) return CE_None;
     if (m_cache == NULL) return CE_Failure;
 
diff --git a/frmts/wms/gdalwmsrasterband.cpp b/frmts/wms/gdalwmsrasterband.cpp
index 159ba63..2e977a8 100644
--- a/frmts/wms/gdalwmsrasterband.cpp
+++ b/frmts/wms/gdalwmsrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalwmsrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalwmsrasterband.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  GDALWMSRasterBand implementation.
@@ -802,8 +802,10 @@ CPLErr GDALWMSRasterBand::ReportWMSException(const char *file_name) {
 }
 
 
-CPLErr GDALWMSRasterBand::AdviseRead(int x0, int y0, int sx, int sy, int bsx, int bsy, GDALDataType bdt, char **options) {
-//    printf("AdviseRead(%d, %d, %d, %d)\n", x0, y0, sx, sy);
+CPLErr GDALWMSRasterBand::AdviseRead(int x0, int y0,
+                                     int sx, int sy,
+                                     CPL_UNUSED int bsx, CPL_UNUSED int bsy,
+                                     CPL_UNUSED GDALDataType bdt, CPL_UNUSED char **options) {
     if (m_parent_dataset->m_offline_mode || !m_parent_dataset->m_use_advise_read) return CE_None;
     if (m_parent_dataset->m_cache == NULL) return CE_Failure;
 
diff --git a/frmts/wms/minidriver.cpp b/frmts/wms/minidriver.cpp
index aa79f6c..ee2189b 100644
--- a/frmts/wms/minidriver.cpp
+++ b/frmts/wms/minidriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver.cpp 26079 2013-06-13 01:31:48Z warmerdam $
+ * $Id: minidriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  GDALWMSMiniDriver base class implementation.
@@ -39,24 +39,27 @@ GDALWMSMiniDriver::GDALWMSMiniDriver() {
 GDALWMSMiniDriver::~GDALWMSMiniDriver() {
 }
 
-CPLErr GDALWMSMiniDriver::Initialize(CPLXMLNode *config) {
+CPLErr GDALWMSMiniDriver::Initialize(CPL_UNUSED CPLXMLNode *config) {
     return CE_None;
 }
 
-void GDALWMSMiniDriver::GetCapabilities(GDALWMSMiniDriverCapabilities *caps) {
+void GDALWMSMiniDriver::GetCapabilities(CPL_UNUSED GDALWMSMiniDriverCapabilities *caps) {
 }
 
-void GDALWMSMiniDriver::ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri) {
+void GDALWMSMiniDriver::ImageRequest(CPL_UNUSED CPLString *url,
+                                     CPL_UNUSED const GDALWMSImageRequestInfo &iri) {
 }
 
-void GDALWMSMiniDriver::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
+void GDALWMSMiniDriver::TiledImageRequest(CPL_UNUSED CPLString *url,
+                                          CPL_UNUSED const GDALWMSImageRequestInfo &iri,
+                                          CPL_UNUSED const GDALWMSTiledImageRequestInfo &tiri) {
 }
 
-void GDALWMSMiniDriver::GetTiledImageInfo(CPLString *url,
-                                              const GDALWMSImageRequestInfo &iri,
-                                              const GDALWMSTiledImageRequestInfo &tiri,
-                                              int nXInBlock,
-                                              int nYInBlock)
+void GDALWMSMiniDriver::GetTiledImageInfo(CPL_UNUSED CPLString *url,
+                                          CPL_UNUSED const GDALWMSImageRequestInfo &iri,
+                                          CPL_UNUSED const GDALWMSTiledImageRequestInfo &tiri,
+                                          CPL_UNUSED int nXInBlock,
+                                          CPL_UNUSED int nYInBlock)
 {
 }
 
diff --git a/frmts/wms/minidriver_tiled_wms.cpp b/frmts/wms/minidriver_tiled_wms.cpp
index 13500ce..12fd0d0 100644
--- a/frmts/wms/minidriver_tiled_wms.cpp
+++ b/frmts/wms/minidriver_tiled_wms.cpp
@@ -681,7 +681,8 @@ void GDALWMSMiniDriver_TiledWMS::GetCapabilities(GDALWMSMiniDriverCapabilities *
 
 
 // not called
-void GDALWMSMiniDriver_TiledWMS::ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri) {
+void GDALWMSMiniDriver_TiledWMS::ImageRequest(CPL_UNUSED CPLString *url,
+                                              CPL_UNUSED const GDALWMSImageRequestInfo &iri) {
 }
 
 void GDALWMSMiniDriver_TiledWMS::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
diff --git a/frmts/wms/minidriver_tileservice.cpp b/frmts/wms/minidriver_tileservice.cpp
index da342aa..5ea3349 100644
--- a/frmts/wms/minidriver_tileservice.cpp
+++ b/frmts/wms/minidriver_tileservice.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver_tileservice.cpp 26079 2013-06-13 01:31:48Z warmerdam $
+ * $Id: minidriver_tileservice.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -76,10 +76,13 @@ void GDALWMSMiniDriver_TileService::GetCapabilities(GDALWMSMiniDriverCapabilitie
     caps->m_max_overview_count = 32;
 }
 
-void GDALWMSMiniDriver_TileService::ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri) {
+void GDALWMSMiniDriver_TileService::ImageRequest(CPL_UNUSED CPLString *url,
+                                                 CPL_UNUSED const GDALWMSImageRequestInfo &iri) {
 }
 
-void GDALWMSMiniDriver_TileService::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
+void GDALWMSMiniDriver_TileService::TiledImageRequest(CPLString *url,
+                                                      CPL_UNUSED const GDALWMSImageRequestInfo &iri,
+                                                      const GDALWMSTiledImageRequestInfo &tiri) {
     // http://s0.tileservice.worldwindcentral.com/getTile?interface=map&version=1&dataset=bmng.topo.bathy.200401&level=5&x=18&y=6
     *url = m_base_url;
     URLAppend(url, "&interface=map");
diff --git a/frmts/wms/minidriver_tms.cpp b/frmts/wms/minidriver_tms.cpp
index 13105d1..d8e0c39 100644
--- a/frmts/wms/minidriver_tms.cpp
+++ b/frmts/wms/minidriver_tms.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver_tms.cpp 26079 2013-06-13 01:31:48Z warmerdam $
+ * $Id: minidriver_tms.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -74,7 +74,8 @@ void GDALWMSMiniDriver_TMS::GetCapabilities(GDALWMSMiniDriverCapabilities *caps)
     caps->m_max_overview_count = 32;
 }
 
-void GDALWMSMiniDriver_TMS::ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri) {
+void GDALWMSMiniDriver_TMS::ImageRequest(CPL_UNUSED CPLString *url,
+                                         CPL_UNUSED const GDALWMSImageRequestInfo &iri) {
 }
 
 void GDALWMSMiniDriver_TMS::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
diff --git a/frmts/wms/minidriver_virtualearth.cpp b/frmts/wms/minidriver_virtualearth.cpp
index ff86064..9d57f3a 100644
--- a/frmts/wms/minidriver_virtualearth.cpp
+++ b/frmts/wms/minidriver_virtualearth.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver_virtualearth.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: minidriver_virtualearth.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -83,7 +83,7 @@ void GDALWMSMiniDriver_VirtualEarth::GetCapabilities(GDALWMSMiniDriverCapabiliti
 }
 
 void GDALWMSMiniDriver_VirtualEarth::TiledImageRequest(CPLString *url,
-                                                       const GDALWMSImageRequestInfo &iri,
+                                                       CPL_UNUSED const GDALWMSImageRequestInfo &iri,
                                                        const GDALWMSTiledImageRequestInfo &tiri)
 {
 
diff --git a/frmts/wms/minidriver_wms.cpp b/frmts/wms/minidriver_wms.cpp
index 9b670b4..b7ef8ce 100644
--- a/frmts/wms/minidriver_wms.cpp
+++ b/frmts/wms/minidriver_wms.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver_wms.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: minidriver_wms.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -176,14 +176,16 @@ void GDALWMSMiniDriver_WMS::ImageRequest(CPLString *url, const GDALWMSImageReque
     CPLDebug("WMS", "URL = %s", url->c_str());
 }
 
-void GDALWMSMiniDriver_WMS::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
+void GDALWMSMiniDriver_WMS::TiledImageRequest(CPLString *url,
+                                              const GDALWMSImageRequestInfo &iri,
+                                              CPL_UNUSED const GDALWMSTiledImageRequestInfo &tiri) {
     ImageRequest(url, iri);
 }
 
 
 void GDALWMSMiniDriver_WMS::GetTiledImageInfo(CPLString *url,
                                               const GDALWMSImageRequestInfo &iri,
-                                              const GDALWMSTiledImageRequestInfo &tiri,
+                                              CPL_UNUSED const GDALWMSTiledImageRequestInfo &tiri,
                                               int nXInBlock,
                                               int nYInBlock)
 {
diff --git a/frmts/wms/minidriver_worldwind.cpp b/frmts/wms/minidriver_worldwind.cpp
index 86a468f..4be8c32 100644
--- a/frmts/wms/minidriver_worldwind.cpp
+++ b/frmts/wms/minidriver_worldwind.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: minidriver_worldwind.cpp 26079 2013-06-13 01:31:48Z warmerdam $
+ * $Id: minidriver_worldwind.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -70,7 +70,8 @@ void GDALWMSMiniDriver_WorldWind::GetCapabilities(GDALWMSMiniDriverCapabilities
     caps->m_max_overview_count = 32;
 }
 
-void GDALWMSMiniDriver_WorldWind::ImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri) {
+void GDALWMSMiniDriver_WorldWind::ImageRequest(CPL_UNUSED CPLString *url,
+                                               CPL_UNUSED const GDALWMSImageRequestInfo &iri) {
 }
 
 void GDALWMSMiniDriver_WorldWind::TiledImageRequest(CPLString *url, const GDALWMSImageRequestInfo &iri, const GDALWMSTiledImageRequestInfo &tiri) {
diff --git a/frmts/wms/wmsdriver.cpp b/frmts/wms/wmsdriver.cpp
index b8a3fa0..2462398 100644
--- a/frmts/wms/wmsdriver.cpp
+++ b/frmts/wms/wmsdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: wmsdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: wmsdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Implementation of Dataset and RasterBand classes for WMS
@@ -843,9 +843,9 @@ GDALDataset *GDALWMSDataset::Open(GDALOpenInfo *poOpenInfo)
 
 GDALDataset *GDALWMSDataset::CreateCopy( const char * pszFilename,
                                          GDALDataset *poSrcDS,
-                                         int bStrict, char ** papszOptions,
-                                         GDALProgressFunc pfnProgress,
-                                         void * pProgressData )
+                                         CPL_UNUSED int bStrict, CPL_UNUSED char ** papszOptions,
+                                         CPL_UNUSED GDALProgressFunc pfnProgress,
+                                         CPL_UNUSED void * pProgressData )
 {
     if (poSrcDS->GetDriver() == NULL ||
         !EQUAL(poSrcDS->GetDriver()->GetDescription(), "WMS"))
diff --git a/frmts/wms/wmsmetadataset.cpp b/frmts/wms/wmsmetadataset.cpp
index b35c8e9..47ad08a 100644
--- a/frmts/wms/wmsmetadataset.cpp
+++ b/frmts/wms/wmsmetadataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: wmsmetadataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: wmsmetadataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WMS Client Driver
  * Purpose:  Definition of GDALWMSMetaDataset class
@@ -235,15 +235,15 @@ char **GDALWMSMetaDataset::GetMetadata( const char *pszDomain )
 /************************************************************************/
 
 void GDALWMSMetaDataset::AddSubDataset( const char* pszLayerName,
-                                          const char* pszTitle,
-                                          const char* pszAbstract,
-                                          const char* pszSRS,
-                                          const char* pszMinX,
-                                          const char* pszMinY,
-                                          const char* pszMaxX,
-                                          const char* pszMaxY,
-                                          CPLString osFormat,
-                                          CPLString osTransparent)
+                                        const char* pszTitle,
+                                        CPL_UNUSED const char* pszAbstract,
+                                        const char* pszSRS,
+                                        const char* pszMinX,
+                                        const char* pszMinY,
+                                        const char* pszMaxX,
+                                        const char* pszMaxY,
+                                        CPLString osFormat,
+                                        CPLString osTransparent)
 
 {
     CPLString osSubdatasetName = "WMS:";
diff --git a/frmts/xpm/xpmdataset.cpp b/frmts/xpm/xpmdataset.cpp
index 9c06d36..36332a3 100644
--- a/frmts/xpm/xpmdataset.cpp
+++ b/frmts/xpm/xpmdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: xpmdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: xpmdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  XPM Driver
  * Purpose:  Implement GDAL XPM Support
@@ -34,7 +34,7 @@
 #include "gdal_frmts.h"						      
 
 
-CPL_CVSID("$Id: xpmdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: xpmdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static unsigned char *ParseXPM( const char *pszInput,
                                 int *pnXSize, int *pnYSize, 
@@ -201,13 +201,12 @@ GDALDataset *XPMDataset::Open( GDALOpenInfo * poOpenInfo )
 
 static GDALDataset *
 XPMCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
-               int bStrict, char ** papszOptions, 
-               GDALProgressFunc pfnProgress, void * pProgressData )
-
+               int bStrict, CPL_UNUSED char ** papszOptions, 
+               CPL_UNUSED GDALProgressFunc pfnProgress, CPL_UNUSED void * pProgressData )
 {
-    int  nBands = poSrcDS->GetRasterCount();
-    int  nXSize = poSrcDS->GetRasterXSize();
-    int  nYSize = poSrcDS->GetRasterYSize();
+    const int  nBands = poSrcDS->GetRasterCount();
+    const int  nXSize = poSrcDS->GetRasterXSize();
+    const int  nYSize = poSrcDS->GetRasterYSize();
     GDALColorTable *poCT;
 
 /* -------------------------------------------------------------------- */
diff --git a/frmts/xyz/xyzdataset.cpp b/frmts/xyz/xyzdataset.cpp
index b823be8..6b924a9 100644
--- a/frmts/xyz/xyzdataset.cpp
+++ b/frmts/xyz/xyzdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: xyzdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: xyzdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  XYZ driver
  * Purpose:  GDALDataset driver for XYZ dataset.
@@ -31,7 +31,7 @@
 #include "cpl_string.h"
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: xyzdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: xyzdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_XYZ(void);
@@ -124,7 +124,7 @@ XYZRasterBand::XYZRasterBand( XYZDataset *poDS, int nBand, GDALDataType eDT )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr XYZRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr XYZRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                   void * pImage )
 
 {
@@ -146,13 +146,17 @@ CPLErr XYZRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
 
     int nLineInFile = nBlockYOff * nBlockXSize; // only valid if bSameNumberOfValuesPerLine
     if ( (poGDS->bSameNumberOfValuesPerLine && poGDS->nDataLineNum > nLineInFile) ||
-         (!poGDS->bSameNumberOfValuesPerLine && (nLastYOff == -1 || nBlockYOff != nLastYOff + 1)) )
+         (!poGDS->bSameNumberOfValuesPerLine && (nLastYOff == -1 || nBlockYOff == 0)) )
     {
         poGDS->nDataLineNum = 0;
+        poGDS->nLineNum = 0;
         VSIFSeekL(poGDS->fp, 0, SEEK_SET);
 
         for(int i=0;i<poGDS->nCommentLineCount;i++)
+        {
             CPLReadLine2L(poGDS->fp, 100, NULL);
+            poGDS->nLineNum ++;
+        }
 
         if (poGDS->bHasHeaderLine)
         {
@@ -783,7 +787,7 @@ GDALDataset *XYZDataset::Open( GDALOpenInfo * poOpenInfo )
                         dfX = CPLAtofDelim(pszPtr, chLocalDecimalSep);
                     else if (nCol == nYIndex)
                         dfY = CPLAtofDelim(pszPtr, chLocalDecimalSep);
-                    else if (nCol == nZIndex && eDT != GDT_Float32)
+                    else if (nCol == nZIndex)
                     {
                         dfZ = CPLAtofDelim(pszPtr, chLocalDecimalSep);
                         if( nDataLineNum == 0 )
diff --git a/frmts/zmap/zmapdataset.cpp b/frmts/zmap/zmapdataset.cpp
index a82fc32..e6c9d5b 100644
--- a/frmts/zmap/zmapdataset.cpp
+++ b/frmts/zmap/zmapdataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: zmapdataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: zmapdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ZMap driver
  * Purpose:  GDALDataset driver for ZMap dataset.
@@ -31,7 +31,7 @@
 #include "cpl_string.h"
 #include "gdal_pam.h"
 
-CPL_CVSID("$Id: zmapdataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: zmapdataset.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void    GDALRegister_ZMap(void);
@@ -111,7 +111,7 @@ ZMapRasterBand::ZMapRasterBand( ZMapDataset *poDS )
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr ZMapRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff,
+CPLErr ZMapRasterBand::IReadBlock( int nBlockXOff, CPL_UNUSED int nBlockYOff,
                                   void * pImage )
 
 {
@@ -520,7 +520,7 @@ static void WriteRightJustified(VSILFILE* fp, double dfValue, int nWidth,
 
 GDALDataset* ZMapDataset::CreateCopy( const char * pszFilename,
                                      GDALDataset *poSrcDS,
-                                     int bStrict, char ** papszOptions,
+                                     int bStrict, CPL_UNUSED char ** papszOptions,
                                      GDALProgressFunc pfnProgress,
                                      void * pProgressData )
 {
diff --git a/gcore/gdal_priv.h b/gcore/gdal_priv.h
index 2802e92..3474688 100644
--- a/gcore/gdal_priv.h
+++ b/gcore/gdal_priv.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_priv.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdal_priv.h 27657 2014-09-10 07:21:17Z rouault $
  *
  * Name:     gdal_priv.h
  * Project:  GDAL Core
@@ -508,9 +508,12 @@ class CPL_DLL GDALRasterBand : public GDALMajorObject
     GDALRasterBand *poMask;
     bool        bOwnMask;
     int         nMaskFlags;
+    
+    void        InvalidateMaskBand();
 
     friend class GDALDataset;
     friend class GDALProxyRasterBand;
+    friend class GDALDefaultOverviews;
 
   protected:
     virtual CPLErr IReadBlock( int, int, void * ) = 0;
diff --git a/gcore/gdal_rat.cpp b/gcore/gdal_rat.cpp
index 1846e88..def5d2a 100644
--- a/gcore/gdal_rat.cpp
+++ b/gcore/gdal_rat.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_rat.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdal_rat.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Implementation of GDALRasterAttributeTable and related classes.
@@ -31,7 +31,7 @@
 #include "gdal_priv.h"
 #include "gdal_rat.h"
 
-CPL_CVSID("$Id: gdal_rat.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdal_rat.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /**
  * \class GDALRasterAttributeTable
@@ -277,7 +277,7 @@ CPLErr CPL_STDCALL GDALRATValuesIOAsString( GDALRasterAttributeTableH hRAT, GDAL
  * @param nNewCount the new number of rows.
  */
 
-void GDALRasterAttributeTable::SetRowCount( int nNewCount )
+void GDALRasterAttributeTable::SetRowCount( CPL_UNUSED int nNewCount )
 {
 }
 
@@ -317,7 +317,7 @@ GDALRATSetRowCount( GDALRasterAttributeTableH hRAT, int nNewCount )
  * @return the row index or -1 if no row is appropriate. 
  */
 
-int GDALRasterAttributeTable::GetRowOfValue( double dfValue ) const
+int GDALRasterAttributeTable::GetRowOfValue( CPL_UNUSED double dfValue ) const
 {
     return -1;
 }
@@ -374,10 +374,9 @@ int GDALRasterAttributeTable::GetRowOfValue( int nValue ) const
  * @return CE_None on success or CE_Failure if something goes wrong.
  */
 
-CPLErr GDALRasterAttributeTable::CreateColumn( const char *pszFieldName, 
-                                               GDALRATFieldType eFieldType,
-                                               GDALRATFieldUsage eFieldUsage )
-
+CPLErr GDALRasterAttributeTable::CreateColumn( CPL_UNUSED const char *pszFieldName, 
+                                               CPL_UNUSED GDALRATFieldType eFieldType,
+                                               CPL_UNUSED GDALRATFieldUsage eFieldUsage )
 {
     return CE_Failure;
 }
@@ -423,9 +422,8 @@ CPLErr CPL_STDCALL GDALRATCreateColumn( GDALRasterAttributeTableH hRAT,
  * @return CE_None on success or CE_Failure on failure.
  */
 
-CPLErr GDALRasterAttributeTable::SetLinearBinning( double dfRow0MinIn, 
-                                                   double dfBinSizeIn )
-
+CPLErr GDALRasterAttributeTable::SetLinearBinning( CPL_UNUSED double dfRow0MinIn, 
+                                                   CPL_UNUSED double dfBinSizeIn )
 {
     return CE_Failure;
 }
@@ -467,8 +465,8 @@ GDALRATSetLinearBinning( GDALRasterAttributeTableH hRAT,
  * @return TRUE if linear binning information exists or FALSE if there is none.
  */
 
-int GDALRasterAttributeTable::GetLinearBinning( double *pdfRow0Min,
-                                                double *pdfBinSize ) const
+int GDALRasterAttributeTable::GetLinearBinning( CPL_UNUSED double *pdfRow0Min,
+                                                CPL_UNUSED double *pdfBinSize ) const
 {
     return FALSE;
 }
diff --git a/gcore/gdal_version.h b/gcore/gdal_version.h
index 2fae310..199c51b 100644
--- a/gcore/gdal_version.h
+++ b/gcore/gdal_version.h
@@ -6,7 +6,7 @@
 #ifndef GDAL_VERSION_MAJOR
 #  define GDAL_VERSION_MAJOR    1
 #  define GDAL_VERSION_MINOR    11
-#  define GDAL_VERSION_REV      0
+#  define GDAL_VERSION_REV      1
 #  define GDAL_VERSION_BUILD    0
 #endif
 
@@ -22,8 +22,8 @@
 #endif
 
 #ifndef GDAL_RELEASE_DATE
-#  define GDAL_RELEASE_DATE     20140416
+#  define GDAL_RELEASE_DATE     20140924
 #endif
 #ifndef GDAL_RELEASE_NAME
-#  define GDAL_RELEASE_NAME     "1.11.0"
+#  define GDAL_RELEASE_NAME     "1.11.1"
 #endif
diff --git a/gcore/gdalallvalidmaskband.cpp b/gcore/gdalallvalidmaskband.cpp
index b340d28..1daaeb2 100644
--- a/gcore/gdalallvalidmaskband.cpp
+++ b/gcore/gdalallvalidmaskband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalallvalidmaskband.cpp 15044 2008-07-26 12:04:05Z rouault $
+ * $Id: gdalallvalidmaskband.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Implementation of GDALAllValidMaskBand, a class implementing all
@@ -30,7 +30,7 @@
 
 #include "gdal_priv.h"
 
-CPL_CVSID("$Id: gdalallvalidmaskband.cpp 15044 2008-07-26 12:04:05Z rouault $");
+CPL_CVSID("$Id: gdalallvalidmaskband.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /************************************************************************/
 /*                        GDALAllValidMaskBand()                        */
@@ -62,10 +62,10 @@ GDALAllValidMaskBand::~GDALAllValidMaskBand()
 /*                             IReadBlock()                             */
 /************************************************************************/
 
-CPLErr GDALAllValidMaskBand::IReadBlock( int nXBlockOff, int nYBlockOff,
+CPLErr GDALAllValidMaskBand::IReadBlock( CPL_UNUSED int nXBlockOff, CPL_UNUSED int nYBlockOff,
                                          void * pImage )
-
 {
+    // TODO: Suspicious that the offsets are not uses.
     memset( pImage, 255, nBlockXSize * nBlockYSize );
 
     return CE_None;
diff --git a/gcore/gdalclientserver.cpp b/gcore/gdalclientserver.cpp
index 93949a9..35018ab 100644
--- a/gcore/gdalclientserver.cpp
+++ b/gcore/gdalclientserver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalclientserver.cpp 27142 2014-04-09 11:14:35Z rouault $
+ * $Id: gdalclientserver.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  GDAL Client/server dataset mechanism.
@@ -368,7 +368,12 @@ class EnterObject
 /*                            MyChdir()                                 */
 /************************************************************************/
 
-static void MyChdir(const char* pszCWD)
+static void MyChdir(
+#ifndef WIN32
+CPL_UNUSED
+#endif
+                    const char* pszCWD
+                    )
 {
 #ifdef WIN32
     SetCurrentDirectory(pszCWD);
@@ -5988,7 +5993,7 @@ CPLErr GDALClientDataset::Delete( const char * pszFilename )
 /************************************************************************/
 static GDALDriver* poAPIPROXYDriver = NULL;
 
-static void GDALUnloadAPIPROXYDriver(GDALDriver* poDriver)
+static void GDALUnloadAPIPROXYDriver(CPL_UNUSED GDALDriver* poDriver)
 {
     if( bRecycleChild )
     {
diff --git a/gcore/gdaldataset.cpp b/gcore/gdaldataset.cpp
index f5ed651..d656254 100644
--- a/gcore/gdaldataset.cpp
+++ b/gcore/gdaldataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdaldataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdaldataset.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Base class for raster file formats.  
@@ -34,7 +34,7 @@
 #include "cpl_multiproc.h"
 #include <map>
 
-CPL_CVSID("$Id: gdaldataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdaldataset.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 CPL_C_START
 GDALAsyncReader *
@@ -789,8 +789,7 @@ const char * CPL_STDCALL GDALGetProjectionRef( GDALDatasetH hDS )
  * @return CE_Failure if an error occurs, otherwise CE_None.
  */
 
-CPLErr GDALDataset::SetProjection( const char * pszProjection )
-
+CPLErr GDALDataset::SetProjection( CPL_UNUSED const char * pszProjection )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -900,8 +899,7 @@ CPLErr CPL_STDCALL GDALGetGeoTransform( GDALDatasetH hDS, double * padfTransform
  * written.
  */
 
-CPLErr GDALDataset::SetGeoTransform( double * padfTransform )
-
+CPLErr GDALDataset::SetGeoTransform( CPL_UNUSED double * padfTransform )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -921,8 +919,7 @@ CPLErr GDALDataset::SetGeoTransform( double * padfTransform )
  */
 
 CPLErr CPL_STDCALL 
-GDALSetGeoTransform( GDALDatasetH hDS, double * padfTransform )
-
+GDALSetGeoTransform( GDALDatasetH hDS, CPL_UNUSED double * padfTransform )
 {
     VALIDATE_POINTER1( hDS, "GDALSetGeoTransform", CE_Failure );
 
@@ -944,8 +941,7 @@ GDALSetGeoTransform( GDALDatasetH hDS, double * padfTransform )
  * @return the desired handle value, or NULL if not recognised/supported.
  */
 
-void *GDALDataset::GetInternalHandle( const char * pszHandleName )
-
+void *GDALDataset::GetInternalHandle( CPL_UNUSED const char * pszHandleName )
 {
     return( NULL );
 }
diff --git a/gcore/gdaldefaultasync.cpp b/gcore/gdaldefaultasync.cpp
index bf72e8d..29d2770 100644
--- a/gcore/gdaldefaultasync.cpp
+++ b/gcore/gdaldefaultasync.cpp
@@ -140,8 +140,7 @@ GDALARGetNextUpdatedRegion(GDALAsyncReaderH hARIO, double timeout,
  * @return TRUE if successful, or FALSE on an error.
  */
 
-int GDALAsyncReader::LockBuffer( double dfTimeout )
-
+int GDALAsyncReader::LockBuffer( CPL_UNUSED double dfTimeout )
 {
     return TRUE;
 }
@@ -293,7 +292,7 @@ GDALDefaultAsyncReader::~GDALDefaultAsyncReader()
 /************************************************************************/
 
 GDALAsyncStatusType
-GDALDefaultAsyncReader::GetNextUpdatedRegion(double dfTimeout,
+GDALDefaultAsyncReader::GetNextUpdatedRegion(CPL_UNUSED double dfTimeout,
                                              int* pnBufXOff,
                                              int* pnBufYOff,
                                              int* pnBufXSize,
diff --git a/gcore/gdaldefaultoverviews.cpp b/gcore/gdaldefaultoverviews.cpp
index e164b5d..68b6a83 100644
--- a/gcore/gdaldefaultoverviews.cpp
+++ b/gcore/gdaldefaultoverviews.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdaldefaultoverviews.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdaldefaultoverviews.cpp 27657 2014-09-10 07:21:17Z rouault $
  *
  * Project:  GDAL Core
  * Purpose:  Helper code to implement overview and mask support for many 
@@ -32,7 +32,7 @@
 #include "gdal_priv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: gdaldefaultoverviews.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdaldefaultoverviews.cpp 27657 2014-09-10 07:21:17Z rouault $");
 
 /************************************************************************/
 /*                        GDALDefaultOverviews()                        */
@@ -768,7 +768,18 @@ GDALDefaultOverviews::BuildOverviews(
             CPLSetThreadLocalConfigOption("PHOTOMETRIC_OVERVIEW", "YCBCR");
 
         if( bOwnMaskDS )
+        {
+            /* Reset the poMask member of main dataset bands, since it */
+            /* will become invalid after poMaskDS closing */
+            for( int iBand = 1; iBand <= poDS->GetRasterCount(); iBand ++ )
+            {
+                GDALRasterBand *poBand = poDS->GetRasterBand(iBand);
+                if( poBand != NULL )
+                    poBand->InvalidateMaskBand();
+            }
+
             GDALClose( poMaskDS );
+        }
 
         // force next request to reread mask file.
         poMaskDS = NULL;
diff --git a/gcore/gdalexif.cpp b/gcore/gdalexif.cpp
index c46e210..4739ea4 100644
--- a/gcore/gdalexif.cpp
+++ b/gcore/gdalexif.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalexif.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalexif.cpp 27255 2014-04-26 19:39:48Z rouault $
  *
  * Project:  GDAL
  * Purpose:  Implements a EXIF directory reader
@@ -39,7 +39,7 @@
 
 #include "gdalexif.h"
 
-CPL_CVSID("$Id: gdalexif.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalexif.cpp 27255 2014-04-26 19:39:48Z rouault $");
 
 /************************************************************************/
 /*                         EXIFPrintData()                              */
@@ -95,8 +95,12 @@ static void EXIFPrintData(char* pszData, GUInt16 type,
   case TIFF_SSHORT: {
     register GInt16 *wp = (GInt16*)data;
     for(;count>0;count--) {
-      sprintf(pszTemp, "%s%d", sep, *wp++), sep = " ";
-      strcat(pszData,pszTemp);
+      sprintf(pszTemp, "%s%d", sep, *wp++);
+      sep = " ";
+      if (strlen(pszTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH)
+          break;
+      strcat(pszDataEnd,pszTemp);
+      pszDataEnd += strlen(pszDataEnd);
     }
     break;
   }
@@ -124,10 +128,10 @@ static void EXIFPrintData(char* pszData, GUInt16 type,
     break;
   }
   case TIFF_RATIONAL: {
-      register GUInt32 *lp = (GUInt32*)data;
+    register GUInt32 *lp = (GUInt32*)data;
       //      if(bSwabflag)
       //      TIFFSwabArrayOfLong((GUInt32*) data, 2*count);
-      for(;count>0;count--) {
+    for(;count>0;count--) {
       if( (lp[0]==0) && (lp[1] == 0) ) {
           sprintf(pszTemp,"%s(0)",sep);
       }
@@ -137,9 +141,12 @@ static void EXIFPrintData(char* pszData, GUInt16 type,
       }
       sep = " ";
       lp += 2;
-      strcat(pszData,pszTemp);
-      }
-      break;
+      if (strlen(pszTemp) + pszDataEnd - pszData >= MAXSTRINGLENGTH)
+          break;
+      strcat(pszDataEnd,pszTemp);
+      pszDataEnd += strlen(pszDataEnd);
+    }
+    break;
   }
   case TIFF_SRATIONAL: {
     register GInt32 *lp = (GInt32*)data;
@@ -251,6 +258,7 @@ CPLErr EXIFExtractMetadata(char**& papszMetadata,
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                   "Could not read all directories");
+        CPLFree(poTIFFDir);
         return CE_Failure;
     }
 
diff --git a/gcore/gdalmultidomainmetadata.cpp b/gcore/gdalmultidomainmetadata.cpp
index 5483bdc..60620e5 100644
--- a/gcore/gdalmultidomainmetadata.cpp
+++ b/gcore/gdalmultidomainmetadata.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalmultidomainmetadata.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalmultidomainmetadata.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Implementation of GDALMultiDomainMetadata class.  This class
@@ -33,7 +33,7 @@
 #include "cpl_string.h"
 #include <map>
 
-CPL_CVSID("$Id: gdalmultidomainmetadata.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalmultidomainmetadata.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /************************************************************************/
 /*                      GDALMultiDomainMetadata()                       */
@@ -190,8 +190,7 @@ CPLErr GDALMultiDomainMetadata::SetMetadataItem( const char *pszName,
 /*      <Metadata> elements.                                            */
 /************************************************************************/
 
-int GDALMultiDomainMetadata::XMLInit( CPLXMLNode *psTree, int bMerge )
-
+int GDALMultiDomainMetadata::XMLInit( CPLXMLNode *psTree, CPL_UNUSED int bMerge )
 {
     CPLXMLNode *psMetadata;
 
diff --git a/gcore/gdalpamrasterband.cpp b/gcore/gdalpamrasterband.cpp
index a28da5d..e83d9cf 100644
--- a/gcore/gdalpamrasterband.cpp
+++ b/gcore/gdalpamrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalpamrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalpamrasterband.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Implementation of GDALPamRasterBand, a raster band base class
@@ -34,7 +34,7 @@
 #include "gdal_rat.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: gdalpamrasterband.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalpamrasterband.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /************************************************************************/
 /*                         GDALPamRasterBand()                          */
@@ -61,7 +61,7 @@ GDALPamRasterBand::~GDALPamRasterBand()
 /*                           SerializeToXML()                           */
 /************************************************************************/
 
-CPLXMLNode *GDALPamRasterBand::SerializeToXML( const char *pszUnused )
+CPLXMLNode *GDALPamRasterBand::SerializeToXML( CPL_UNUSED const char *pszUnused )
 
 {
     if( psPam == NULL )
@@ -207,7 +207,11 @@ CPLXMLNode *GDALPamRasterBand::SerializeToXML( const char *pszUnused )
 /*      Raster Attribute Table                                          */
 /* -------------------------------------------------------------------- */
     if( psPam->poDefaultRAT != NULL )
-        CPLAddXMLChild( psTree, psPam->poDefaultRAT->Serialize() );
+    {
+        CPLXMLNode* psSerializedRAT = psPam->poDefaultRAT->Serialize();
+        if( psSerializedRAT != NULL )
+            CPLAddXMLChild( psTree, psSerializedRAT );
+    }
 
 /* -------------------------------------------------------------------- */
 /*      Metadata.                                                       */
@@ -305,7 +309,7 @@ void GDALPamRasterBand::PamClear()
 /*                              XMLInit()                               */
 /************************************************************************/
 
-CPLErr GDALPamRasterBand::XMLInit( CPLXMLNode *psTree, const char *pszUnused )
+CPLErr GDALPamRasterBand::XMLInit( CPLXMLNode *psTree, CPL_UNUSED const char *pszUnused )
 
 {
     PamInitialize();
@@ -975,8 +979,7 @@ int
 PamParseHistogram( CPLXMLNode *psHistItem, 
                    double *pdfMin, double *pdfMax, 
                    int *pnBuckets, int **ppanHistogram, 
-                   int *pbIncludeOutOfRange, int *pbApproxOK )
-
+                   CPL_UNUSED int *pbIncludeOutOfRange, CPL_UNUSED int *pbApproxOK )
 {
     if( psHistItem == NULL )
         return FALSE;
diff --git a/gcore/gdalproxydataset.cpp b/gcore/gdalproxydataset.cpp
index 700aab2..4552032 100644
--- a/gcore/gdalproxydataset.cpp
+++ b/gcore/gdalproxydataset.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalproxydataset.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalproxydataset.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  A dataset and raster band classes that act as proxy for underlying
@@ -30,7 +30,7 @@
 
 #include "gdal_proxy.h"
 
-CPL_CVSID("$Id: gdalproxydataset.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalproxydataset.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /* ******************************************************************** */
 /*                        GDALProxyDataset                              */
@@ -126,7 +126,7 @@ D_PROXY_METHOD_WITH_RET(CPLErr, CE_Failure, CreateMaskBand, ( int nFlags ), (nFl
 /*                    UnrefUnderlyingDataset()                        */
 /************************************************************************/
 
-void GDALProxyDataset::UnrefUnderlyingDataset(GDALDataset* poUnderlyingDataset)
+void GDALProxyDataset::UnrefUnderlyingDataset(CPL_UNUSED GDALDataset* poUnderlyingDataset)
 {
 }
 
@@ -298,6 +298,6 @@ RB_PROXY_METHOD_WITH_RET(CPLVirtualMem*, NULL, GetVirtualMemAuto,
 /*                 UnrefUnderlyingRasterBand()                        */
 /************************************************************************/
 
-void GDALProxyRasterBand::UnrefUnderlyingRasterBand(GDALRasterBand* poUnderlyingRasterBand)
+void GDALProxyRasterBand::UnrefUnderlyingRasterBand(CPL_UNUSED GDALRasterBand* poUnderlyingRasterBand)
 {
 }
diff --git a/gcore/gdalproxypool.cpp b/gcore/gdalproxypool.cpp
index c6cb12a..e9d2421 100644
--- a/gcore/gdalproxypool.cpp
+++ b/gcore/gdalproxypool.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalproxypool.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gdalproxypool.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  A dataset and raster band classes that differ the opening of the
@@ -31,7 +31,7 @@
 #include "gdal_proxy.h"
 #include "cpl_multiproc.h"
 
-CPL_CVSID("$Id: gdalproxypool.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: gdalproxypool.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /* We *must* share the same mutex as the gdaldataset.cpp file, as we are */
 /* doing GDALOpen() calls that can indirectly call GDALOpenShared() on */
@@ -600,7 +600,7 @@ GDALDataset* GDALProxyPoolDataset::RefUnderlyingDataset()
 /*                    UnrefUnderlyingDataset()                        */
 /************************************************************************/
 
-void GDALProxyPoolDataset::UnrefUnderlyingDataset(GDALDataset* poUnderlyingDataset)
+void GDALProxyPoolDataset::UnrefUnderlyingDataset(CPL_UNUSED GDALDataset* poUnderlyingDataset)
 {
     if (cacheEntry != NULL)
     {
@@ -1109,7 +1109,7 @@ GDALRasterBand *GDALProxyPoolRasterBand::GetOverview(int nOverviewBand)
 /*                     GetRasterSampleOverview()                        */
 /* ******************************************************************** */
 
-GDALRasterBand *GDALProxyPoolRasterBand::GetRasterSampleOverview( int nDesiredSamples)
+GDALRasterBand *GDALProxyPoolRasterBand::GetRasterSampleOverview( CPL_UNUSED int nDesiredSamples)
 {
     CPLError(CE_Failure, CPLE_AppDefined,
              "GDALProxyPoolRasterBand::GetRasterSampleOverview : not implemented yet");
@@ -1185,7 +1185,7 @@ GDALRasterBand* GDALProxyPoolOverviewRasterBand::RefUnderlyingRasterBand()
 /*                  UnrefUnderlyingRasterBand()                         */
 /* ******************************************************************** */
 
-void GDALProxyPoolOverviewRasterBand::UnrefUnderlyingRasterBand(GDALRasterBand* poUnderlyingRasterBand)
+void GDALProxyPoolOverviewRasterBand::UnrefUnderlyingRasterBand(CPL_UNUSED GDALRasterBand* poUnderlyingRasterBand)
 {
     poMainBand->UnrefUnderlyingRasterBand(poUnderlyingMainRasterBand);
     nRefCountUnderlyingMainRasterBand --;
@@ -1250,7 +1250,7 @@ GDALRasterBand* GDALProxyPoolMaskBand::RefUnderlyingRasterBand()
 /*                  UnrefUnderlyingRasterBand()                         */
 /* ******************************************************************** */
 
-void GDALProxyPoolMaskBand::UnrefUnderlyingRasterBand(GDALRasterBand* poUnderlyingRasterBand)
+void GDALProxyPoolMaskBand::UnrefUnderlyingRasterBand(CPL_UNUSED GDALRasterBand* poUnderlyingRasterBand)
 {
     poMainBand->UnrefUnderlyingRasterBand(poUnderlyingMainRasterBand);
     nRefCountUnderlyingMainRasterBand --;
diff --git a/gcore/gdalrasterband.cpp b/gcore/gdalrasterband.cpp
index c68d3a6..be758ef 100644
--- a/gcore/gdalrasterband.cpp
+++ b/gcore/gdalrasterband.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdalrasterband.cpp 27110 2014-03-28 21:29:20Z rouault $
+ * $Id: gdalrasterband.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Base class for format specific band class implementation.  This
@@ -37,7 +37,7 @@
 #define TO_SUBBLOCK(x) ((x) >> 6)
 #define WITHIN_SUBBLOCK(x) ((x) & 0x3f)
 
-CPL_CVSID("$Id: gdalrasterband.cpp 27110 2014-03-28 21:29:20Z rouault $");
+CPL_CVSID("$Id: gdalrasterband.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 /************************************************************************/
 /*                           GDALRasterBand()                           */
@@ -95,13 +95,7 @@ GDALRasterBand::~GDALRasterBand()
                   poDS->GetDescription() );
     }
 
-    if( bOwnMask )
-    {
-        delete poMask;
-        poMask = NULL;
-        nMaskFlags = 0;
-        bOwnMask = false;
-    }
+    InvalidateMaskBand();
 }
 
 /************************************************************************/
@@ -1488,8 +1482,7 @@ char ** CPL_STDCALL GDALGetRasterCategoryNames( GDALRasterBandH hBand )
  * by the driver CE_Failure is returned, but no error message is reported.
  */
 
-CPLErr GDALRasterBand::SetCategoryNames( char ** papszNames )
-
+CPLErr GDALRasterBand::SetCategoryNames( CPL_UNUSED char ** papszNames )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -1586,8 +1579,7 @@ GDALGetRasterNoDataValue( GDALRasterBandH hBand, int *pbSuccess )
  * been emitted.
  */
 
-CPLErr GDALRasterBand::SetNoDataValue( double dfNoData )
-
+CPLErr GDALRasterBand::SetNoDataValue( CPL_UNUSED double dfNoData )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -2288,8 +2280,7 @@ double CPL_STDCALL GDALGetRasterOffset( GDALRasterBandH hBand, int *pbSuccess )
  * @return CE_None or success or CE_Failure on failure. 
  */
 
-CPLErr GDALRasterBand::SetOffset( double dfNewOffset )
-
+CPLErr GDALRasterBand::SetOffset( CPL_UNUSED double dfNewOffset )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -2388,8 +2379,7 @@ double CPL_STDCALL GDALGetRasterScale( GDALRasterBandH hBand, int *pbSuccess )
  * @return CE_None or success or CE_Failure on failure. 
  */
 
-CPLErr GDALRasterBand::SetScale( double dfNewScale )
-
+CPLErr GDALRasterBand::SetScale( CPL_UNUSED double dfNewScale )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -2479,7 +2469,7 @@ const char * CPL_STDCALL GDALGetRasterUnitType( GDALRasterBandH hBand )
  * unsupported.
  */
 
-CPLErr GDALRasterBand::SetUnitType( const char *pszNewValue )
+CPLErr GDALRasterBand::SetUnitType( CPL_UNUSED const char *pszNewValue )
 
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
@@ -3288,9 +3278,8 @@ CPLErr CPL_STDCALL GDALGetDefaultHistogram( GDALRasterBandH hBand,
  */
 
 CPLErr GDALRasterBand::AdviseRead( 
-    int nXOff, int nYOff, int nXSize, int nYSize,
-    int nBufXSize, int nBufYSize, GDALDataType eBufType, char **papszOptions )
-
+    CPL_UNUSED int nXOff, CPL_UNUSED int nYOff, CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+    CPL_UNUSED int nBufXSize, CPL_UNUSED int nBufYSize, CPL_UNUSED GDALDataType eBufType, CPL_UNUSED char **papszOptions )
 {
     return CE_None;
 }
@@ -4298,9 +4287,8 @@ GDALComputeRasterMinMax( GDALRasterBandH hBand, int bApproxOK,
  *
  * This method is the same as the C function GDALSetDefaultHistogram().
  */
-CPLErr GDALRasterBand::SetDefaultHistogram( double dfMin, double dfMax, 
-                                            int nBuckets, int *panHistogram )
-
+CPLErr GDALRasterBand::SetDefaultHistogram( CPL_UNUSED double dfMin, CPL_UNUSED double dfMax, 
+                                            CPL_UNUSED int nBuckets, CPL_UNUSED int *panHistogram )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -4390,8 +4378,7 @@ GDALRasterAttributeTableH CPL_STDCALL GDALGetDefaultRAT( GDALRasterBandH hBand)
  * failing.
  */
 
-CPLErr GDALRasterBand::SetDefaultRAT( const GDALRasterAttributeTable *poRAT )
-
+CPLErr GDALRasterBand::SetDefaultRAT( CPL_UNUSED const GDALRasterAttributeTable *poRAT )
 {
     if( !(GetMOFlags() & GMO_IGNORE_UNIMPLEMENTED) )
         ReportError( CE_Failure, CPLE_NotSupported,
@@ -4683,6 +4670,19 @@ int CPL_STDCALL GDALGetMaskFlags( GDALRasterBandH hBand )
 }
 
 /************************************************************************/
+/*                         InvalidateMaskBand()                         */
+/************************************************************************/
+
+void GDALRasterBand::InvalidateMaskBand()
+{
+    if (bOwnMask)
+        delete poMask;
+    bOwnMask = false;
+    nMaskFlags = 0;
+    poMask = NULL;
+}
+
+/************************************************************************/
 /*                           CreateMaskBand()                           */
 /************************************************************************/
 
@@ -4720,11 +4720,7 @@ CPLErr GDALRasterBand::CreateMaskBand( int nFlags )
         if (eErr != CE_None)
             return eErr;
 
-        /* Invalidate existing raster band mask */
-        if (bOwnMask)
-            delete poMask;
-        bOwnMask = false;
-        poMask = NULL;
+        InvalidateMaskBand();
 
         return CE_None;
     }
diff --git a/gcore/gdalvirtualmem.cpp b/gcore/gdalvirtualmem.cpp
index d8aff4b..3e5484c 100644
--- a/gcore/gdalvirtualmem.cpp
+++ b/gcore/gdalvirtualmem.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: gdalvirtualmem.cpp 27110 2014-03-28 21:29:20Z rouault $
+ * $Id: gdalvirtualmem.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Name:     gdalvirtualmem.cpp
  * Project:  GDAL
@@ -104,14 +104,14 @@ public:
 
 GDALVirtualMem::GDALVirtualMem( GDALDatasetH hDS,
                                 GDALRasterBandH hBand,
-                          int nXOff, int nYOff,
-                          int nXSize, int nYSize,
-                          int nBufXSize, int nBufYSize,
-                          GDALDataType eBufType,
-                          int nBandCount, const int* panBandMapIn,
-                          int nPixelSpace,
-                          GIntBig nLineSpace,
-                          GIntBig nBandSpace ) :
+                                int nXOff, int nYOff,
+                                CPL_UNUSED int nXSize, CPL_UNUSED int nYSize,
+                                int nBufXSize, int nBufYSize,
+                                GDALDataType eBufType,
+                                int nBandCount, const int* panBandMapIn,
+                                int nPixelSpace,
+                                GIntBig nLineSpace,
+                                GIntBig nBandSpace ) :
     hDS(hDS), hBand(hBand), nXOff(nXOff), nYOff(nYOff), /*nXSize(nXSize), nYSize(nYSize),*/
     nBufXSize(nBufXSize), nBufYSize(nBufYSize), eBufType(eBufType),
     nBandCount(nBandCount), nPixelSpace(nPixelSpace), nLineSpace(nLineSpace),
diff --git a/gcore/overview.cpp b/gcore/overview.cpp
index 4a419c8..623c268 100644
--- a/gcore/overview.cpp
+++ b/gcore/overview.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: overview.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: overview.cpp 27723 2014-09-22 18:21:08Z goatbar $
  *
  * Project:  GDAL Core
  * Purpose:  Helper code to implement overview support in different drivers.
@@ -30,7 +30,7 @@
 
 #include "gdal_priv.h"
 
-CPL_CVSID("$Id: overview.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: overview.cpp 27723 2014-09-22 18:21:08Z goatbar $");
 
 typedef CPLErr (*GDALDownsampleFunction)
                       ( int nSrcWidth, int nSrcHeight,
@@ -52,16 +52,16 @@ typedef CPLErr (*GDALDownsampleFunction)
 template <class T>
 static CPLErr
 GDALDownsampleChunk32R_NearT( int nSrcWidth, int nSrcHeight,
-                        GDALDataType eWrkDataType,
-                        T * pChunk,
-                        GByte * pabyChunkNodataMask_unused,
-                        int nChunkXOff, int nChunkXSize,
-                        int nChunkYOff, int nChunkYSize,
-                        GDALRasterBand * poOverview,
-                        const char * pszResampling_unused,
-                        int bHasNoData_unused, float fNoDataValue_unused,
-                        GDALColorTable* poColorTable_unused,
-                        GDALDataType eSrcDataType)
+                              GDALDataType eWrkDataType,
+                              T * pChunk,
+                              CPL_UNUSED GByte * pabyChunkNodataMask_unused,
+                              int nChunkXOff, int nChunkXSize,
+                              int nChunkYOff, int nChunkYSize,
+                              GDALRasterBand * poOverview,
+                              CPL_UNUSED const char * pszResampling_unused,
+                              CPL_UNUSED int bHasNoData_unused, CPL_UNUSED float fNoDataValue_unused,
+                              CPL_UNUSED GDALColorTable* poColorTable_unused,
+                              CPL_UNUSED GDALDataType eSrcDataType)
 
 {
     CPLErr eErr = CE_None;
@@ -211,16 +211,16 @@ GDALDownsampleChunk32R_Near( int nSrcWidth, int nSrcHeight,
 template <class T, class Tsum>
 static CPLErr
 GDALDownsampleChunk32R_AverageT( int nSrcWidth, int nSrcHeight,
-                        GDALDataType eWrkDataType,
-                        T* pChunk,
-                        GByte * pabyChunkNodataMask,
-                        int nChunkXOff, int nChunkXSize,
-                        int nChunkYOff, int nChunkYSize,
-                        GDALRasterBand * poOverview,
-                        const char * pszResampling,
-                        int bHasNoData, float fNoDataValue,
-                        GDALColorTable* poColorTable,
-                        GDALDataType eSrcDataType)
+                                 GDALDataType eWrkDataType,
+                                 T* pChunk,
+                                 GByte * pabyChunkNodataMask,
+                                 int nChunkXOff, int nChunkXSize,
+                                 int nChunkYOff, int nChunkYSize,
+                                 GDALRasterBand * poOverview,
+                                 const char * pszResampling,
+                                 int bHasNoData, float fNoDataValue,
+                                 GDALColorTable* poColorTable,
+                                 CPL_UNUSED GDALDataType eSrcDataType)
 
 {
     CPLErr eErr = CE_None;
@@ -517,16 +517,16 @@ GDALDownsampleChunk32R_Average( int nSrcWidth, int nSrcHeight,
 
 static CPLErr
 GDALDownsampleChunk32R_Gauss( int nSrcWidth, int nSrcHeight,
-                        GDALDataType eWrkDataType,
-                        void * pChunk,
-                        GByte * pabyChunkNodataMask,
-                        int nChunkXOff, int nChunkXSize,
-                        int nChunkYOff, int nChunkYSize,
-                        GDALRasterBand * poOverview,
-                        const char * pszResampling,
-                        int bHasNoData, float fNoDataValue,
-                        GDALColorTable* poColorTable,
-                        GDALDataType eSrcDataType)
+                              CPL_UNUSED GDALDataType eWrkDataType,
+                              void * pChunk,
+                              GByte * pabyChunkNodataMask,
+                              int nChunkXOff, int nChunkXSize,
+                              int nChunkYOff, int nChunkYSize,
+                              GDALRasterBand * poOverview,
+                              CPL_UNUSED const char * pszResampling,
+                              int bHasNoData, float fNoDataValue,
+                              GDALColorTable* poColorTable,
+                              CPL_UNUSED GDALDataType eSrcDataType)
 
 {
     CPLErr eErr = CE_None;
@@ -799,17 +799,16 @@ GDALDownsampleChunk32R_Gauss( int nSrcWidth, int nSrcHeight,
 
 static CPLErr
 GDALDownsampleChunk32R_Mode( int nSrcWidth, int nSrcHeight,
-                        GDALDataType eWrkDataType,
-                        void * pChunk,
-                        GByte * pabyChunkNodataMask,
-                        int nChunkXOff, int nChunkXSize,
-                        int nChunkYOff, int nChunkYSize,
-                        GDALRasterBand * poOverview,
-                        const char * pszResampling,
-                        int bHasNoData, float fNoDataValue,
-                        GDALColorTable* poColorTable,
-                        GDALDataType eSrcDataType)
-
+                             CPL_UNUSED GDALDataType eWrkDataType,
+                             void * pChunk,
+                             GByte * pabyChunkNodataMask,
+                             int nChunkXOff, int nChunkXSize,
+                             int nChunkYOff, int nChunkYSize,
+                             GDALRasterBand * poOverview,
+                             CPL_UNUSED const char * pszResampling,
+                             int bHasNoData, float fNoDataValue,
+                             GDALColorTable* poColorTable,
+                             GDALDataType eSrcDataType)
 {
     CPLErr eErr = CE_None;
 
@@ -1031,17 +1030,16 @@ GDALDownsampleChunk32R_Mode( int nSrcWidth, int nSrcHeight,
 
 static CPLErr
 GDALDownsampleChunk32R_Cubic( int nSrcWidth, int nSrcHeight,
-                        GDALDataType eWrkDataType,
-                        void * pChunk,
-                        GByte * pabyChunkNodataMask,
-                        int nChunkXOff, int nChunkXSize,
-                        int nChunkYOff, int nChunkYSize,
-                        GDALRasterBand * poOverview,
-                        const char * pszResampling,
-                        int bHasNoData, float fNoDataValue,
-                        GDALColorTable* poColorTable,
-                        GDALDataType eSrcDataType)
-
+                              CPL_UNUSED GDALDataType eWrkDataType,
+                              void * pChunk,
+                              GByte * pabyChunkNodataMask,
+                              int nChunkXOff, int nChunkXSize,
+                              int nChunkYOff, int nChunkYSize,
+                              GDALRasterBand * poOverview,
+                              CPL_UNUSED const char * pszResampling,
+                              CPL_UNUSED int bHasNoData, CPL_UNUSED float fNoDataValue,
+                              GDALColorTable* poColorTable,
+                              CPL_UNUSED GDALDataType eSrcDataType)
 {
 
     CPLErr eErr = CE_None;
@@ -1600,8 +1598,28 @@ GDALRegenerateOverviews( GDALRasterBandH hSrcBand,
 
     /* If we have a nodata mask and we are doing something more complicated */
     /* than nearest neighbouring, we have to fetch to nodata mask */ 
-    int bUseNoDataMask = (!EQUALN(pszResampling,"NEAR",4) &&
-                          (poSrcBand->GetMaskFlags() & GMF_ALL_VALID) == 0);
+
+    GDALRasterBand* poMaskBand = NULL;
+    int nMaskFlags = 0;
+    int bUseNoDataMask = FALSE;
+    if( !EQUALN(pszResampling,"NEAR",4) )
+    {
+        /* Special case if we are the alpha band. We want it to be considered */
+        /* as the mask band to avoid alpha=0 to be taken into account in average */
+        /* computation */
+        if( poSrcBand->GetColorInterpretation() == GCI_AlphaBand )
+        {
+            poMaskBand = poSrcBand;
+            nMaskFlags = GMF_ALPHA | GMF_PER_DATASET;
+        }
+        else
+        {
+            poMaskBand = poSrcBand->GetMaskBand();
+            nMaskFlags = poSrcBand->GetMaskFlags();
+        }
+
+        bUseNoDataMask = ((nMaskFlags & GMF_ALL_VALID) == 0);
+    }
 
 /* -------------------------------------------------------------------- */
 /*      If we are operating on multiple overviews, and using            */
@@ -1613,7 +1631,7 @@ GDALRegenerateOverviews( GDALRasterBandH hSrcBand,
     /* we can't use cascaded generation, as the computation of the overviews */
     /* of the band used for the mask band may not have yet occured (#3033) */
     if( (EQUALN(pszResampling,"AVER",4) || EQUALN(pszResampling,"GAUSS",5)) && nOverviewCount > 1
-         && !(bUseNoDataMask && poSrcBand->GetMaskFlags() != GMF_NODATA))
+         && !(bUseNoDataMask && nMaskFlags != GMF_NODATA))
         return GDALRegenerateCascadingOverviews( poSrcBand, 
                                                  nOverviewCount, papoOvrBands,
                                                  pszResampling, 
@@ -1685,7 +1703,7 @@ GDALRegenerateOverviews( GDALRasterBandH hSrcBand,
                                 pChunk, nWidth, nFullResYChunk, eType,
                                 0, 0 );
         if (eErr == CE_None && bUseNoDataMask)
-            eErr = poSrcBand->GetMaskBand()->RasterIO( GF_Read, 0, nChunkYOff, nWidth, nFullResYChunk, 
+            eErr = poMaskBand->RasterIO( GF_Read, 0, nChunkYOff, nWidth, nFullResYChunk, 
                                 pabyChunkNodataMask, nWidth, nFullResYChunk, GDT_Byte,
                                 0, 0 );
 
diff --git a/man/man1/gdal-config.1 b/man/man1/gdal-config.1
index 96d3f1d..2ff10fa 100644
--- a/man/man1/gdal-config.1
+++ b/man/man1/gdal-config.1
@@ -1,8 +1,8 @@
-.TH "gdal-config" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal-config" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal-config \- .TH "gdal-config" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal-config \- .TH "gdal-config" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal2tiles.1 b/man/man1/gdal2tiles.1
index f6b804e..49905ea 100644
--- a/man/man1/gdal2tiles.1
+++ b/man/man1/gdal2tiles.1
@@ -1,8 +1,8 @@
-.TH "gdal2tiles" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal2tiles" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal2tiles \- .TH "gdal2tiles" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal2tiles \- .TH "gdal2tiles" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_calc.1 b/man/man1/gdal_calc.1
index c11e578..991655e 100644
--- a/man/man1/gdal_calc.1
+++ b/man/man1/gdal_calc.1
@@ -1,8 +1,8 @@
-.TH "gdal_calc" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_calc" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_calc \- .TH "gdal_calc" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_calc \- .TH "gdal_calc" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_contour.1 b/man/man1/gdal_contour.1
index 9d792ab..5da197a 100644
--- a/man/man1/gdal_contour.1
+++ b/man/man1/gdal_contour.1
@@ -1,8 +1,8 @@
-.TH "gdal_contour" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_contour" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_contour \- .TH "gdal_contour" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_contour \- .TH "gdal_contour" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_edit.1 b/man/man1/gdal_edit.1
index c8e4ae9..db9ac05 100644
--- a/man/man1/gdal_edit.1
+++ b/man/man1/gdal_edit.1
@@ -1,8 +1,8 @@
-.TH "gdal_edit" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_edit" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_edit \- .TH "gdal_edit" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_edit \- .TH "gdal_edit" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_fillnodata.1 b/man/man1/gdal_fillnodata.1
index 64832ba..b95706c 100644
--- a/man/man1/gdal_fillnodata.1
+++ b/man/man1/gdal_fillnodata.1
@@ -1,8 +1,8 @@
-.TH "gdal_fillnodata" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_fillnodata" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_fillnodata \- .TH "gdal_fillnodata" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_fillnodata \- .TH "gdal_fillnodata" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_grid.1 b/man/man1/gdal_grid.1
index 6e98eb7..3660469 100644
--- a/man/man1/gdal_grid.1
+++ b/man/man1/gdal_grid.1
@@ -1,8 +1,8 @@
-.TH "gdal_grid" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_grid" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_grid \- .TH "gdal_grid" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_grid \- .TH "gdal_grid" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_merge.1 b/man/man1/gdal_merge.1
index 7e9f288..2311d41 100644
--- a/man/man1/gdal_merge.1
+++ b/man/man1/gdal_merge.1
@@ -1,8 +1,8 @@
-.TH "gdal_merge" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_merge" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_merge \- .TH "gdal_merge" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_merge \- .TH "gdal_merge" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_polygonize.1 b/man/man1/gdal_polygonize.1
index 0d494b0..5f83663 100644
--- a/man/man1/gdal_polygonize.1
+++ b/man/man1/gdal_polygonize.1
@@ -1,8 +1,8 @@
-.TH "gdal_polygonize" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_polygonize" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_polygonize \- .TH "gdal_polygonize" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_polygonize \- .TH "gdal_polygonize" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_proximity.1 b/man/man1/gdal_proximity.1
index 87f0c68..80201d1 100644
--- a/man/man1/gdal_proximity.1
+++ b/man/man1/gdal_proximity.1
@@ -1,8 +1,8 @@
-.TH "gdal_proximity" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_proximity" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_proximity \- .TH "gdal_proximity" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_proximity \- .TH "gdal_proximity" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_rasterize.1 b/man/man1/gdal_rasterize.1
index b0f3b7a..3ff9410 100644
--- a/man/man1/gdal_rasterize.1
+++ b/man/man1/gdal_rasterize.1
@@ -1,8 +1,8 @@
-.TH "gdal_rasterize" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_rasterize" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_rasterize \- .TH "gdal_rasterize" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_rasterize \- .TH "gdal_rasterize" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_retile.1 b/man/man1/gdal_retile.1
index 9bdebf1..85b6947 100644
--- a/man/man1/gdal_retile.1
+++ b/man/man1/gdal_retile.1
@@ -1,8 +1,8 @@
-.TH "gdal_retile" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_retile" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_retile \- .TH "gdal_retile" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_retile \- .TH "gdal_retile" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_sieve.1 b/man/man1/gdal_sieve.1
index 508d010..ac86f6c 100644
--- a/man/man1/gdal_sieve.1
+++ b/man/man1/gdal_sieve.1
@@ -1,8 +1,8 @@
-.TH "gdal_sieve" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_sieve" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_sieve \- .TH "gdal_sieve" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_sieve \- .TH "gdal_sieve" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_translate.1 b/man/man1/gdal_translate.1
index dfc039f..449d92e 100644
--- a/man/man1/gdal_translate.1
+++ b/man/man1/gdal_translate.1
@@ -1,8 +1,8 @@
-.TH "gdal_translate" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_translate" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_translate \- .TH "gdal_translate" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_translate \- .TH "gdal_translate" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdal_utilities.1 b/man/man1/gdal_utilities.1
index b2101a3..6734492 100644
--- a/man/man1/gdal_utilities.1
+++ b/man/man1/gdal_utilities.1
@@ -1,8 +1,8 @@
-.TH "gdal_utilities" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdal_utilities" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdal_utilities \- .TH "gdal_utilities" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdal_utilities \- .TH "gdal_utilities" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdaladdo.1 b/man/man1/gdaladdo.1
index 022ecf5..1246fa1 100644
--- a/man/man1/gdaladdo.1
+++ b/man/man1/gdaladdo.1
@@ -1,8 +1,8 @@
-.TH "gdaladdo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdaladdo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdaladdo \- .TH "gdaladdo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdaladdo \- .TH "gdaladdo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalbuildvrt.1 b/man/man1/gdalbuildvrt.1
index 20af7cc..e103d49 100644
--- a/man/man1/gdalbuildvrt.1
+++ b/man/man1/gdalbuildvrt.1
@@ -1,8 +1,8 @@
-.TH "gdalbuildvrt" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalbuildvrt" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalbuildvrt \- .TH "gdalbuildvrt" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalbuildvrt \- .TH "gdalbuildvrt" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalcompare.1 b/man/man1/gdalcompare.1
index 1375a0f..07a5e73 100644
--- a/man/man1/gdalcompare.1
+++ b/man/man1/gdalcompare.1
@@ -1,8 +1,8 @@
-.TH "gdalcompare" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalcompare" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalcompare \- .TH "gdalcompare" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalcompare \- .TH "gdalcompare" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdaldem.1 b/man/man1/gdaldem.1
index 45f664c..cd6c1db 100644
--- a/man/man1/gdaldem.1
+++ b/man/man1/gdaldem.1
@@ -1,8 +1,8 @@
-.TH "gdaldem" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdaldem" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdaldem \- .TH "gdaldem" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdaldem \- .TH "gdaldem" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalinfo.1 b/man/man1/gdalinfo.1
index cd82d04..761a813 100644
--- a/man/man1/gdalinfo.1
+++ b/man/man1/gdalinfo.1
@@ -1,8 +1,8 @@
-.TH "gdalinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalinfo \- .TH "gdalinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalinfo \- .TH "gdalinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdallocationinfo.1 b/man/man1/gdallocationinfo.1
index a2a238c..e27cd12 100644
--- a/man/man1/gdallocationinfo.1
+++ b/man/man1/gdallocationinfo.1
@@ -1,8 +1,8 @@
-.TH "gdallocationinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdallocationinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdallocationinfo \- .TH "gdallocationinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdallocationinfo \- .TH "gdallocationinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalmanage.1 b/man/man1/gdalmanage.1
index 8e5ed0c..4d51541 100644
--- a/man/man1/gdalmanage.1
+++ b/man/man1/gdalmanage.1
@@ -1,8 +1,8 @@
-.TH "gdalmanage" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalmanage" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalmanage \- .TH "gdalmanage" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalmanage \- .TH "gdalmanage" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalmove.1 b/man/man1/gdalmove.1
index a52472e..852a6e9 100644
--- a/man/man1/gdalmove.1
+++ b/man/man1/gdalmove.1
@@ -1,8 +1,8 @@
-.TH "gdalmove" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalmove" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalmove \- .TH "gdalmove" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalmove \- .TH "gdalmove" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalsrsinfo.1 b/man/man1/gdalsrsinfo.1
index 41c6092..ae68df1 100644
--- a/man/man1/gdalsrsinfo.1
+++ b/man/man1/gdalsrsinfo.1
@@ -1,8 +1,8 @@
-.TH "gdalsrsinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalsrsinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalsrsinfo \- .TH "gdalsrsinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalsrsinfo \- .TH "gdalsrsinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdaltindex.1 b/man/man1/gdaltindex.1
index 8301cd8..ba1de88 100644
--- a/man/man1/gdaltindex.1
+++ b/man/man1/gdaltindex.1
@@ -1,8 +1,8 @@
-.TH "gdaltindex" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdaltindex" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdaltindex \- .TH "gdaltindex" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdaltindex \- .TH "gdaltindex" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdaltransform.1 b/man/man1/gdaltransform.1
index 9fecbb5..8013647 100644
--- a/man/man1/gdaltransform.1
+++ b/man/man1/gdaltransform.1
@@ -1,8 +1,8 @@
-.TH "gdaltransform" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdaltransform" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdaltransform \- .TH "gdaltransform" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdaltransform \- .TH "gdaltransform" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/gdalwarp.1 b/man/man1/gdalwarp.1
index 4ff7d8e..83b6e35 100644
--- a/man/man1/gdalwarp.1
+++ b/man/man1/gdalwarp.1
@@ -1,8 +1,8 @@
-.TH "gdalwarp" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "gdalwarp" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-gdalwarp \- .TH "gdalwarp" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+gdalwarp \- .TH "gdalwarp" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/nearblack.1 b/man/man1/nearblack.1
index 4f3e154..24eaf48 100644
--- a/man/man1/nearblack.1
+++ b/man/man1/nearblack.1
@@ -1,8 +1,8 @@
-.TH "nearblack" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "nearblack" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-nearblack \- .TH "nearblack" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+nearblack \- .TH "nearblack" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/ogr2ogr.1 b/man/man1/ogr2ogr.1
index 72fe1c2..a9ad156 100644
--- a/man/man1/ogr2ogr.1
+++ b/man/man1/ogr2ogr.1
@@ -1,8 +1,8 @@
-.TH "ogr2ogr" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "ogr2ogr" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-ogr2ogr \- .TH "ogr2ogr" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+ogr2ogr \- .TH "ogr2ogr" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/ogr_utilities.1 b/man/man1/ogr_utilities.1
index 0a962f6..8223ed7 100644
--- a/man/man1/ogr_utilities.1
+++ b/man/man1/ogr_utilities.1
@@ -1,8 +1,8 @@
-.TH "ogr_utilities" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "ogr_utilities" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-ogr_utilities \- .TH "ogr_utilities" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+ogr_utilities \- .TH "ogr_utilities" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/ogrinfo.1 b/man/man1/ogrinfo.1
index 0717bb1..bee5b50 100644
--- a/man/man1/ogrinfo.1
+++ b/man/man1/ogrinfo.1
@@ -1,8 +1,8 @@
-.TH "ogrinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "ogrinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-ogrinfo \- .TH "ogrinfo" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+ogrinfo \- .TH "ogrinfo" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/ogrlineref.1 b/man/man1/ogrlineref.1
index a623e4b..dfd2ecc 100644
--- a/man/man1/ogrlineref.1
+++ b/man/man1/ogrlineref.1
@@ -1,8 +1,8 @@
-.TH "ogrlineref" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "ogrlineref" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-ogrlineref \- .TH "ogrlineref" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+ogrlineref \- .TH "ogrlineref" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/ogrtindex.1 b/man/man1/ogrtindex.1
index e5e3196..c816abd 100644
--- a/man/man1/ogrtindex.1
+++ b/man/man1/ogrtindex.1
@@ -1,8 +1,8 @@
-.TH "ogrtindex" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "ogrtindex" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-ogrtindex \- .TH "ogrtindex" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+ogrtindex \- .TH "ogrtindex" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/pct2rgb.1 b/man/man1/pct2rgb.1
index ce45733..5648066 100644
--- a/man/man1/pct2rgb.1
+++ b/man/man1/pct2rgb.1
@@ -1,8 +1,8 @@
-.TH "pct2rgb" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "pct2rgb" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-pct2rgb \- .TH "pct2rgb" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+pct2rgb \- .TH "pct2rgb" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/man/man1/rgb2pct.1 b/man/man1/rgb2pct.1
index a1cfd4d..bfec1b9 100644
--- a/man/man1/rgb2pct.1
+++ b/man/man1/rgb2pct.1
@@ -1,8 +1,8 @@
-.TH "rgb2pct" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+.TH "rgb2pct" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
-rgb2pct \- .TH "rgb2pct" 1 "Wed Apr 16 2014" "GDAL" \" -*- nroff -*-
+rgb2pct \- .TH "rgb2pct" 1 "Wed Sep 24 2014" "GDAL" \" -*- nroff -*-
 .ad l
 .nh
 .SH NAME
diff --git a/ogr/ogr_expat.cpp b/ogr/ogr_expat.cpp
index f9faeed..71cff3b 100644
--- a/ogr/ogr_expat.cpp
+++ b/ogr/ogr_expat.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_expat.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_expat.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  Convenience function for parsing with Expat library
@@ -32,7 +32,7 @@
 #include "ogr_expat.h"
 #include "cpl_error.h"
 
-CPL_CVSID("$Id: ogr_expat.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogr_expat.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define OGR_EXPAT_MAX_ALLOWED_ALLOC 10000000
 
@@ -152,7 +152,7 @@ static void FillISO885915(XML_Encoding *info)
 /*                  OGRExpatUnknownEncodingHandler()                    */
 /************************************************************************/
 
-static int OGRExpatUnknownEncodingHandler (void *unused_encodingHandlerData,
+static int OGRExpatUnknownEncodingHandler (CPL_UNUSED void *unused_encodingHandlerData,
                                            const XML_Char *name,
                                            XML_Encoding *info)
 {
diff --git a/ogr/ogr_fromepsg.cpp b/ogr/ogr_fromepsg.cpp
index 0ce5a6b..9334875 100644
--- a/ogr/ogr_fromepsg.cpp
+++ b/ogr/ogr_fromepsg.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_fromepsg.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_fromepsg.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Generate an OGRSpatialReference object based on an EPSG
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include "cpl_csv.h"
 
-CPL_CVSID("$Id: ogr_fromepsg.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogr_fromepsg.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #ifndef PI
 #  define PI 3.14159265358979323846
@@ -1325,7 +1325,7 @@ static OGRErr SetEPSGGeogCS( OGRSpatialReference * poSRS, int nGeogCS )
 /************************************************************************/
 
 static double OGR_FetchParm( double *padfProjParms, int *panParmIds, 
-                             int nTargetId, double dfFromGreenwich )
+                             int nTargetId, CPL_UNUSED double dfFromGreenwich )
 
 {
     int i;
diff --git a/ogr/ogr_geocoding.cpp b/ogr/ogr_geocoding.cpp
index bc78731..b44ba0b 100644
--- a/ogr/ogr_geocoding.cpp
+++ b/ogr/ogr_geocoding.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_geocoding.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_geocoding.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Client of geocoding service.
@@ -77,7 +77,7 @@ int OGR_gettimeofday(struct timeval *tv, struct timezone *tzIgnored)
 #include "ogr_mem.h"
 #include "ogrsf_frmts.h"
 
-CPL_CVSID("$Id: ogr_geocoding.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogr_geocoding.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 struct _OGRGeocodingSessionHS
 {
@@ -606,7 +606,7 @@ static OGRLayerH OGRGeocodeMakeRawLayer(const char* pszContent)
 /************************************************************************/
 
 static OGRLayerH OGRGeocodeBuildLayerNominatim(CPLXMLNode* psSearchResults,
-                                               const char* pszContent,
+                                               CPL_UNUSED const char* pszContent,
                                                int bAddRawFeature)
 {
     OGRMemLayer* poLayer = new OGRMemLayer( "place", NULL, wkbUnknown );
@@ -868,7 +868,7 @@ static OGRLayerH OGRGeocodeReverseBuildLayerNominatim(CPLXMLNode* psReverseGeoco
 /************************************************************************/
 
 static OGRLayerH OGRGeocodeBuildLayerYahoo(CPLXMLNode* psResultSet,
-                                           const char* pszContent,
+                                           CPL_UNUSED const char* pszContent,
                                            int bAddRawFeature)
 {
     OGRMemLayer* poLayer = new OGRMemLayer( "place", NULL, wkbPoint );
@@ -999,7 +999,7 @@ static OGRLayerH OGRGeocodeBuildLayerYahoo(CPLXMLNode* psResultSet,
 /************************************************************************/
 
 static OGRLayerH OGRGeocodeBuildLayerBing (CPLXMLNode* psResponse,
-                                           const char* pszContent,
+                                           CPL_UNUSED const char* pszContent,
                                            int bAddRawFeature)
 {
     CPLXMLNode* psResources = CPLGetXMLNode(psResponse, "ResourceSets.ResourceSet.Resources");
diff --git a/ogr/ogr_srs_proj4.cpp b/ogr/ogr_srs_proj4.cpp
index 8be829f..6360ba4 100644
--- a/ogr/ogr_srs_proj4.cpp
+++ b/ogr/ogr_srs_proj4.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_srs_proj4.cpp 27108 2014-03-28 20:25:46Z kyle $
+ * $Id: ogr_srs_proj4.cpp 27437 2014-06-06 19:14:53Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  OGRSpatialReference interface to PROJ.4.
@@ -35,7 +35,7 @@
 
 extern int EPSGGetWGS84Transform( int nGeogCS, double *padfTransform );
 
-CPL_CVSID("$Id: ogr_srs_proj4.cpp 27108 2014-03-28 20:25:46Z kyle $");
+CPL_CVSID("$Id: ogr_srs_proj4.cpp 27437 2014-06-06 19:14:53Z rouault $");
 
 /* -------------------------------------------------------------------- */
 /*      The following list comes from osrs/proj/src/pj_ellps.c          */
@@ -409,6 +409,23 @@ OGRErr OGRSpatialReference::importFromProj4( const char * pszProj4 )
     char *pszNormalized;
 
     pszNormalized = OCTProj4Normalize( pszCleanCopy );
+
+    /* Workaround proj.4 bug (#239) by manually re-adding no_off/no_uoff */
+    if( strstr(pszCleanCopy, "+no_off") != NULL && 
+        strstr(pszNormalized, "+no_off") == NULL )
+    {
+        char* pszTmp = CPLStrdup(CPLSPrintf("%s +no_off", pszNormalized));
+        CPLFree(pszNormalized);
+        pszNormalized = pszTmp;
+    }
+    else if( strstr(pszCleanCopy, "+no_uoff") != NULL && 
+        strstr(pszNormalized, "+no_uoff") == NULL )
+    {
+        char* pszTmp = CPLStrdup(CPLSPrintf("%s +no_uoff", pszNormalized));
+        CPLFree(pszNormalized);
+        pszNormalized = pszTmp;
+    }
+
     CPLFree( pszCleanCopy );
     
 /* -------------------------------------------------------------------- */
@@ -811,10 +828,17 @@ OGRErr OGRSpatialReference::importFromProj4( const char * pszProj4 )
         if( CSLFetchNameValue(papszNV,"no_uoff") != NULL
             || CSLFetchNameValue(papszNV,"no_off") != NULL )
         {
+            /* From PJ_omerc, when alpha is defined but not gamma */
+            /* the default gama value is alpha */
+            /*  if (alp || gam) {
+                    if (alp) {
+                        gamma0 = asin(sin(alpha_c) / D);
+                    if (!gam)
+                        gamma = alpha_c; */
             SetHOM( OSR_GDV( papszNV, "lat_0", 0.0 ), 
                     OSR_GDV( papszNV, "lonc", 0.0 ), 
                     OSR_GDV( papszNV, "alpha", 0.0 ), 
-                    OSR_GDV( papszNV, "gamma", 0.0 ), 
+                    OSR_GDV( papszNV, "gamma", OSR_GDV( papszNV, "alpha", 0.0 ) ), 
                     OSR_GDV( papszNV, "k", 1.0 ), 
                     OSR_GDV( papszNV, "x_0", 0.0 ), 
                     OSR_GDV( papszNV, "y_0", 0.0 ) );
@@ -824,7 +848,7 @@ OGRErr OGRSpatialReference::importFromProj4( const char * pszProj4 )
             SetHOMAC( OSR_GDV( papszNV, "lat_0", 0.0 ), 
                    OSR_GDV( papszNV, "lonc", 0.0 ), 
                    OSR_GDV( papszNV, "alpha", 0.0 ), 
-                   OSR_GDV( papszNV, "gamma", 0.0 ), 
+                   OSR_GDV( papszNV, "gamma", OSR_GDV( papszNV, "alpha", 0.0 ) ), 
                    OSR_GDV( papszNV, "k", 1.0 ), 
                    OSR_GDV( papszNV, "x_0", 0.0 ), 
                    OSR_GDV( papszNV, "y_0", 0.0 ) );
diff --git a/ogr/ogr_srs_xml.cpp b/ogr/ogr_srs_xml.cpp
index bca763f..de1fd53 100644
--- a/ogr/ogr_srs_xml.cpp
+++ b/ogr/ogr_srs_xml.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_srs_xml.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_srs_xml.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  OGRSpatialReference interface to OGC XML (014r4).
@@ -714,8 +714,7 @@ static CPLXMLNode *exportProjCSToXML( const OGRSpatialReference *poSRS )
  */
 
 OGRErr OGRSpatialReference::exportToXML( char **ppszRawXML, 
-                                         const char * pszDialect ) const
-
+                                         CPL_UNUSED const char * pszDialect ) const
 {
     CPLXMLNode *psXMLTree = NULL;
 
diff --git a/ogr/ogrfeature.cpp b/ogr/ogrfeature.cpp
index a157574..e6f9c24 100644
--- a/ogr/ogrfeature.cpp
+++ b/ogr/ogrfeature.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrfeature.cpp 27110 2014-03-28 21:29:20Z rouault $
+ * $Id: ogrfeature.cpp 27714 2014-09-21 15:51:52Z jef $
  * 
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  The OGRFeature class implementation. 
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include <vector>
 
-CPL_CVSID("$Id: ogrfeature.cpp 27110 2014-03-28 21:29:20Z rouault $");
+CPL_CVSID("$Id: ogrfeature.cpp 27714 2014-09-21 15:51:52Z jef $");
 
 /************************************************************************/
 /*                             OGRFeature()                             */
@@ -282,7 +282,7 @@ OGRFeatureDefnH OGR_F_GetDefnRef( OGRFeatureH hFeat )
  *
  * This method updates the features geometry, and operate exactly as
  * SetGeometry(), except that this method assumes ownership of the
- * passed geometry.
+ * passed geometry (even in case of failure of that function).
  *
  * This method is the same as the C function OGR_F_SetGeometryDirectly().
  *
@@ -301,7 +301,10 @@ OGRErr OGRFeature::SetGeometryDirectly( OGRGeometry * poGeomIn )
     if( GetGeomFieldCount() > 0 )
         return SetGeomFieldDirectly(0, poGeomIn);
     else
+    {
+        delete poGeomIn;
         return OGRERR_FAILURE;
+    }
 }
 
 /************************************************************************/
@@ -313,7 +316,7 @@ OGRErr OGRFeature::SetGeometryDirectly( OGRGeometry * poGeomIn )
  *
  * This function updates the features geometry, and operate exactly as
  * SetGeometry(), except that this function assumes ownership of the
- * passed geometry.
+ * passed geometry (even in case of failure of that function).
  *
  * This function is the same as the C++ method 
  * OGRFeature::SetGeometryDirectly.
@@ -594,7 +597,7 @@ OGRGeometryH OGR_F_GetGeomFieldRef( OGRFeatureH hFeat, int iField )
  *
  * This method updates the features geometry, and operate exactly as
  * SetGeomField(), except that this method assumes ownership of the
- * passed geometry.
+ * passed geometry (even in case of failure of that function).
  *
  * This method is the same as the C function OGR_F_SetGeomFieldDirectly().
  *
@@ -614,7 +617,10 @@ OGRErr OGRFeature::SetGeomFieldDirectly( int iField, OGRGeometry * poGeomIn )
 
 {
     if( iField < 0 || iField >= GetGeomFieldCount() )
+    {
+        delete poGeomIn;
         return OGRERR_FAILURE;
+    }
 
     delete papoGeometries[iField];
     papoGeometries[iField] = poGeomIn;
@@ -633,7 +639,7 @@ OGRErr OGRFeature::SetGeomFieldDirectly( int iField, OGRGeometry * poGeomIn )
  *
  * This function updates the features geometry, and operate exactly as
  * SetGeomField(), except that this function assumes ownership of the
- * passed geometry.
+ * passed geometry (even in case of failure of that function).
  *
  * This function is the same as the C++ method 
  * OGRFeature::SetGeomFieldDirectly.
@@ -2399,6 +2405,14 @@ void OGRFeature::SetField( int iField, const char * pszValue )
 
         CSLDestroy(papszValueList);
     }
+    else if ( poFDefn->GetType() == OFTStringList )
+    {
+        if( pszValue && *pszValue )
+        {
+            const char *papszValues[2] = { pszValue, 0 };
+            SetField( iField, (char **) papszValues );
+        }
+    }
     else
         /* do nothing for other field types */;
 }
diff --git a/ogr/ogrgeometry.cpp b/ogr/ogrgeometry.cpp
index 632bf8e..83cc3b6 100644
--- a/ogr/ogrgeometry.cpp
+++ b/ogr/ogrgeometry.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeometry.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeometry.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements a few base methods on OGRGeometry.
@@ -35,7 +35,7 @@
 #include "cpl_multiproc.h"
 #include <assert.h>
 
-CPL_CVSID("$Id: ogrgeometry.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgeometry.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 int OGRGeometry::bGenerate_DB2_V72_BYTE_ORDER = FALSE;
 
@@ -592,7 +592,7 @@ int OGRGeometry::getIsoGeometryType() const
  * @param dfMaxLength the maximum distance between 2 points after segmentization
  */
 
-void OGRGeometry::segmentize( double dfMaxLength )
+void OGRGeometry::segmentize( CPL_UNUSED double dfMaxLength )
 {
     /* Do nothing */
 }
diff --git a/ogr/ogrgeometrycollection.cpp b/ogr/ogrgeometrycollection.cpp
index 354dba2..57a1233 100644
--- a/ogr/ogrgeometrycollection.cpp
+++ b/ogr/ogrgeometrycollection.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeometrycollection.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeometrycollection.cpp 27610 2014-08-27 15:47:43Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  The OGRGeometryCollection class.
@@ -31,7 +31,7 @@
 #include "ogr_geometry.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrgeometrycollection.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgeometrycollection.cpp 27610 2014-08-27 15:47:43Z rouault $");
 
 /************************************************************************/
 /*                       OGRGeometryCollection()                        */
@@ -593,7 +593,7 @@ OGRErr  OGRGeometryCollection::exportToWkb( OGRwkbByteOrder eByteOrder,
 /* ==================================================================== */
     for( int iGeom = 0; iGeom < nGeomCount; iGeom++ )
     {
-        papoGeoms[iGeom]->exportToWkb( eByteOrder, pabyData + nOffset );
+        papoGeoms[iGeom]->exportToWkb( eByteOrder, pabyData + nOffset, eWkbVariant );
 
         nOffset += papoGeoms[iGeom]->WkbSize();
     }
diff --git a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadatasource.cpp b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadatasource.cpp
index f9963cf..26a9d79 100644
--- a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadatasource.cpp
+++ b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograeronavfaadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograeronavfaadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  AeronavFAA Translator
  * Purpose:  Implements OGRAeronavFAADataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ograeronavfaadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograeronavfaadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                      OGRAeronavFAADataSource()                       */
@@ -64,8 +64,7 @@ OGRAeronavFAADataSource::~OGRAeronavFAADataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAeronavFAADataSource::TestCapability( const char * pszCap )
-
+int OGRAeronavFAADataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadriver.cpp b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadriver.cpp
index ab4886b..8338dfc 100644
--- a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadriver.cpp
+++ b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaadriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograeronavfaadriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograeronavfaadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  AeronavFAA Translator
  * Purpose:  Implements OGRAeronavFAADriver.
@@ -30,7 +30,7 @@
 #include "ogr_aeronavfaa.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ograeronavfaadriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograeronavfaadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 // g++ ogr/ogrsf_frmts/aeronavfaa/*.cpp -Wall -g -fPIC -shared -o ogr_AeronavFAA.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts/aernovfaa -Iogr/ogrsf_frmts
 
@@ -77,8 +77,7 @@ OGRDataSource *OGRAeronavFAADriver::Open( const char * pszFilename, int bUpdate
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAeronavFAADriver::TestCapability( const char * pszCap )
-
+int OGRAeronavFAADriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaalayer.cpp b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaalayer.cpp
index 1297cd6..51cfdbd 100644
--- a/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaalayer.cpp
+++ b/ogr/ogrsf_frmts/aeronavfaa/ograeronavfaalayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograeronavfaalayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograeronavfaalayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  AeronavFAA Translator
  * Purpose:  Implements OGRAeronavFAALayer class.
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ograeronavfaalayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograeronavfaalayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRAeronavFAALayer()                          */
@@ -117,8 +117,7 @@ OGRFeature *OGRAeronavFAALayer::GetNextFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAeronavFAALayer::TestCapability( const char * pszCap )
-
+int OGRAeronavFAALayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/arcgen/ograrcgendatasource.cpp b/ogr/ogrsf_frmts/arcgen/ograrcgendatasource.cpp
index 2a48219..93008f0 100644
--- a/ogr/ogrsf_frmts/arcgen/ograrcgendatasource.cpp
+++ b/ogr/ogrsf_frmts/arcgen/ograrcgendatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograrcgendatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograrcgendatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Arc/Info Generate Translator
  * Purpose:  Implements OGRARCGENDataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ograrcgendatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograrcgendatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRARCGENDataSource()                          */
@@ -64,8 +64,7 @@ OGRARCGENDataSource::~OGRARCGENDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRARCGENDataSource::TestCapability( const char * pszCap )
-
+int OGRARCGENDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/arcgen/ograrcgendriver.cpp b/ogr/ogrsf_frmts/arcgen/ograrcgendriver.cpp
index a5afdc7..d8169f5 100644
--- a/ogr/ogrsf_frmts/arcgen/ograrcgendriver.cpp
+++ b/ogr/ogrsf_frmts/arcgen/ograrcgendriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograrcgendriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograrcgendriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Arc/Info Generate Translator
  * Purpose:  Implements OGRARCGENDriver.
@@ -30,7 +30,7 @@
 #include "ogr_arcgen.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ograrcgendriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograrcgendriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRARCGEN();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGRARCGENDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRARCGENDriver::TestCapability( const char * pszCap )
-
+int OGRARCGENDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/arcgen/ograrcgenlayer.cpp b/ogr/ogrsf_frmts/arcgen/ograrcgenlayer.cpp
index e6d7e9b..85bff7a 100644
--- a/ogr/ogrsf_frmts/arcgen/ograrcgenlayer.cpp
+++ b/ogr/ogrsf_frmts/arcgen/ograrcgenlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ograrcgenlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ograrcgenlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Arc/Info Generate Translator
  * Purpose:  Implements OGRARCGENLayer class.
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ograrcgenlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ograrcgenlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRARCGENLayer()                             */
@@ -225,8 +225,7 @@ OGRFeature *OGRARCGENLayer::GetNextRawFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRARCGENLayer::TestCapability( const char * pszCap )
-
+int OGRARCGENLayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/avc/avc_bin.c b/ogr/ogrsf_frmts/avc/avc_bin.c
index f28747f..dafc339 100644
--- a/ogr/ogrsf_frmts/avc/avc_bin.c
+++ b/ogr/ogrsf_frmts/avc/avc_bin.c
@@ -1556,7 +1556,7 @@ AVCTxt *AVCBinReadNextTxt(AVCBinFile *psFile)
  * Returns 0 on success or -1 on error.
  **********************************************************************/
 int _AVCBinReadNextRxp(AVCRawBinFile *psFile, AVCRxp *psRxp, 
-                       int nPrecision)
+                       CPL_UNUSED int nPrecision)
 {
 
     psRxp->n1  = AVCRawBinReadInt32(psFile);
diff --git a/ogr/ogrsf_frmts/avc/avc_binwr.c b/ogr/ogrsf_frmts/avc/avc_binwr.c
index 8bb353b..f217807 100644
--- a/ogr/ogrsf_frmts/avc/avc_binwr.c
+++ b/ogr/ogrsf_frmts/avc/avc_binwr.c
@@ -1176,7 +1176,7 @@ int _AVCBinWriteTxt(AVCRawBinFile *psFile, AVCTxt *psTxt,
  * Returns 0 on success or -1 on error.
  **********************************************************************/
 int _AVCBinWritePCCoverageTxt(AVCRawBinFile *psFile, AVCTxt *psTxt, 
-                              int nPrecision, AVCRawBinFile *psIndexFile)
+                              CPL_UNUSED int nPrecision, AVCRawBinFile *psIndexFile)
 {
     int i, nRecSize, nCurPos, nStrLen, numVertices;
 
@@ -1303,7 +1303,7 @@ int AVCBinWriteTxt(AVCBinFile *psFile, AVCTxt *psTxt)
  * Returns 0 on success or -1 on error.
  **********************************************************************/
 int _AVCBinWriteRxp(AVCRawBinFile *psFile, AVCRxp *psRxp, 
-                    int nPrecision)
+                    CPL_UNUSED int nPrecision)
 {
 
     AVCRawBinWriteInt32(psFile, psRxp->n1);
@@ -1913,7 +1913,7 @@ AVCBinFile *_AVCBinWriteCreateDBFTable(const char *pszPath,
                                        const char *pszCoverName,
                                        AVCTableDef *psSrcTableDef,
                                        AVCCoverType eCoverType,
-                                       int nPrecision, AVCDBCSInfo *psDBCSInfo)
+                                       int nPrecision, CPL_UNUSED AVCDBCSInfo *psDBCSInfo)
 {
     AVCBinFile    *psFile;
     AVCTableDef   *psTableDef = NULL;
diff --git a/ogr/ogrsf_frmts/avc/avc_misc.c b/ogr/ogrsf_frmts/avc/avc_misc.c
index 2b43443..8ae713c 100644
--- a/ogr/ogrsf_frmts/avc/avc_misc.c
+++ b/ogr/ogrsf_frmts/avc/avc_misc.c
@@ -347,7 +347,7 @@ char *AVCAdjustCaseSensitiveFilename(char *pszFname)
      * If we get to a point where a path component does not exist then
      * we simply return the rest of the path as is.
      *----------------------------------------------------------------*/
-    while(bValidPath && strlen(pszTmpPath) < nTotalLen)
+    while(bValidPath && strlen(pszTmpPath) < (unsigned long)nTotalLen)
     {
         char    **papszDir=NULL;
         int     iEntry, iLastPartStart;
diff --git a/ogr/ogrsf_frmts/avc/ogravcbindatasource.cpp b/ogr/ogrsf_frmts/avc/ogravcbindatasource.cpp
index 9c0e2b2..67f517d 100644
--- a/ogr/ogrsf_frmts/avc/ogravcbindatasource.cpp
+++ b/ogr/ogrsf_frmts/avc/ogravcbindatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogravcbindatasource.cpp 10645 2007-01-18 02:22:39Z warmerdam $
+ * $Id: ogravcbindatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  Implements OGRAVCBinDataSource class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogravcbindatasource.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
+CPL_CVSID("$Id: ogravcbindatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRAVCBinDataSource()                         */
@@ -159,8 +159,7 @@ int OGRAVCBinDataSource::Open( const char * pszNewName, int bTestOpen )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAVCBinDataSource::TestCapability( const char * pszCap )
-
+int OGRAVCBinDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp b/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp
index 971df71..e27d51c 100644
--- a/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp
+++ b/ogr/ogrsf_frmts/avc/ogravcbindriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogravcbindriver.cpp 10645 2007-01-18 02:22:39Z warmerdam $
+ * $Id: ogravcbindriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  OGRAVCBinDriver implementation (Arc/Info Binary Coverages)
@@ -29,7 +29,7 @@
 
 #include "ogr_avc.h"
 
-CPL_CVSID("$Id: ogravcbindriver.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
+CPL_CVSID("$Id: ogravcbindriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          ~OGRAVCBinDriver()                          */
@@ -89,8 +89,7 @@ OGRDataSource *OGRAVCBinDriver::Open( const char * pszFilename,
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAVCBinDriver::TestCapability( const char * pszCap )
-
+int OGRAVCBinDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/avc/ogravce00datasource.cpp b/ogr/ogrsf_frmts/avc/ogravce00datasource.cpp
index 0dd5636..c37d202 100644
--- a/ogr/ogrsf_frmts/avc/ogravce00datasource.cpp
+++ b/ogr/ogrsf_frmts/avc/ogravce00datasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogravce00datasource.cpp 24747 2012-08-08 00:13:30Z warmerdam $
+ * $Id: ogravce00datasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  Implements OGRAVCE00DataSource class.
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogravce00datasource.cpp 24747 2012-08-08 00:13:30Z warmerdam $");
+CPL_CVSID("$Id: ogravce00datasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRAVCE00DataSource()                         */
@@ -196,8 +196,7 @@ int OGRAVCE00DataSource::CheckAddTable( AVCE00Section *psTblSection )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAVCE00DataSource::TestCapability( const char * pszCap )
-
+int OGRAVCE00DataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/avc/ogravce00driver.cpp b/ogr/ogrsf_frmts/avc/ogravce00driver.cpp
index cee1771..e0c22c9 100644
--- a/ogr/ogrsf_frmts/avc/ogravce00driver.cpp
+++ b/ogr/ogrsf_frmts/avc/ogravce00driver.cpp
@@ -79,8 +79,7 @@ OGRDataSource *OGRAVCE00Driver::Open( const char * pszFilename,
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAVCE00Driver::TestCapability( const char * pszCap )
-
+int OGRAVCE00Driver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/avc/ogravclayer.cpp b/ogr/ogrsf_frmts/avc/ogravclayer.cpp
index 163dae3..baad055 100644
--- a/ogr/ogrsf_frmts/avc/ogravclayer.cpp
+++ b/ogr/ogrsf_frmts/avc/ogravclayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogravclayer.cpp 15014 2008-07-23 21:05:23Z dmorissette $
+ * $Id: ogravclayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  Implements OGRAVCLayer class.  This is the base class for E00
@@ -34,7 +34,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogravclayer.cpp 15014 2008-07-23 21:05:23Z dmorissette $");
+CPL_CVSID("$Id: ogravclayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRAVCLayer()                           */
@@ -72,8 +72,7 @@ OGRAVCLayer::~OGRAVCLayer()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRAVCLayer::TestCapability( const char * pszCap )
-
+int OGRAVCLayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/bna/ogrbnadatasource.cpp b/ogr/ogrsf_frmts/bna/ogrbnadatasource.cpp
index 75664b0..28508c4 100644
--- a/ogr/ogrsf_frmts/bna/ogrbnadatasource.cpp
+++ b/ogr/ogrsf_frmts/bna/ogrbnadatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrbnadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrbnadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  BNA Translator
  * Purpose:  Implements OGRBNADataSource class
@@ -106,10 +106,9 @@ OGRLayer *OGRBNADataSource::GetLayer( int iLayer )
 /************************************************************************/
 
 OGRLayer * OGRBNADataSource::CreateLayer( const char * pszLayerName,
-                                          OGRSpatialReference *poSRS,
+                                          CPL_UNUSED OGRSpatialReference *poSRS,
                                           OGRwkbGeometryType eType,
-                                          char ** papszOptions )
-
+                                          CPL_UNUSED char ** papszOptions )
 {
     BNAFeatureType bnaFeatureType;
     
diff --git a/ogr/ogrsf_frmts/bna/ogrbnalayer.cpp b/ogr/ogrsf_frmts/bna/ogrbnalayer.cpp
index 2c1197c..d8c171e 100644
--- a/ogr/ogrsf_frmts/bna/ogrbnalayer.cpp
+++ b/ogr/ogrsf_frmts/bna/ogrbnalayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrbnalayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrbnalayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  BNA Translator
  * Purpose:  Implements OGRBNALayer class.
@@ -560,8 +560,7 @@ OGRErr OGRBNALayer::CreateFeature( OGRFeature *poFeature )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRBNALayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRBNALayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     if( !bWriter || nFeatures != 0)
         return OGRERR_FAILURE;
diff --git a/ogr/ogrsf_frmts/bna/ogrbnaparser.cpp b/ogr/ogrsf_frmts/bna/ogrbnaparser.cpp
index f26452a..aef4527 100644
--- a/ogr/ogrsf_frmts/bna/ogrbnaparser.cpp
+++ b/ogr/ogrsf_frmts/bna/ogrbnaparser.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrbnaparser.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrbnaparser.cpp 27710 2014-09-21 15:30:29Z goatbar $
  *
  * Project:  BNA Parser
  * Purpose:  Parse a BNA record
@@ -228,7 +228,7 @@ BNARecord* BNA_GetNextRecord(VSILFILE* f,
     int dotFound = 0;
     int numChar = 0;
     const char* detailedErrorMsg = NULL;
-    BNAFeatureType currentFeatureType = (BNAFeatureType) -1;
+    BNAFeatureType currentFeatureType = BNA_UNKNOWN;
     int nbExtraId = 0;
     char tmpBuffer[NB_MAX_BNA_IDS][TMP_BUFFER_SIZE+1];
     int  tmpBufferLength[NB_MAX_BNA_IDS] = {0, 0, 0};
@@ -496,7 +496,7 @@ BNARecord* BNA_GetNextRecord(VSILFILE* f,
           {
             inQuotes = TRUE;
           }
-          else if (numField >= NB_MIN_BNA_IDS && currentFeatureType == -1)
+          else if (numField >= NB_MIN_BNA_IDS && currentFeatureType == BNA_UNKNOWN)
           {
             if (ptrBeginningOfNumber == NULL)
             {
diff --git a/ogr/ogrsf_frmts/bna/ogrbnaparser.h b/ogr/ogrsf_frmts/bna/ogrbnaparser.h
index 2bf9164..2ad5e7a 100644
--- a/ogr/ogrsf_frmts/bna/ogrbnaparser.h
+++ b/ogr/ogrsf_frmts/bna/ogrbnaparser.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrbnaparser.h 20996 2010-10-28 18:38:15Z rouault $
+ * $Id: ogrbnaparser.h 27710 2014-09-21 15:30:29Z goatbar $
  *
  * Project:  BNA Parser header
  * Purpose:  Definition of structures, enums and functions of BNA parser
@@ -40,6 +40,7 @@ extern "C"
 
 typedef enum
 {
+  BNA_UNKNOWN = -1,
   BNA_POINT,
   BNA_POLYGON,
   BNA_POLYLINE,
diff --git a/ogr/ogrsf_frmts/cartodb/ogrcartodbdatasource.cpp b/ogr/ogrsf_frmts/cartodb/ogrcartodbdatasource.cpp
index b443134..ac0f144 100644
--- a/ogr/ogrsf_frmts/cartodb/ogrcartodbdatasource.cpp
+++ b/ogr/ogrsf_frmts/cartodb/ogrcartodbdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcartodbdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcartodbdatasource.cpp 27268 2014-05-01 10:46:20Z rouault $
  *
  * Project:  CartoDB Translator
  * Purpose:  Implements OGRCARTODBDataSource class
@@ -29,7 +29,7 @@
 
 #include "ogr_cartodb.h"
 
-CPL_CVSID("$Id: ogrcartodbdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcartodbdatasource.cpp 27268 2014-05-01 10:46:20Z rouault $");
 
 /************************************************************************/
 /*                        OGRCARTODBDataSource()                        */
@@ -504,7 +504,7 @@ json_object* OGRCARTODBDataSource::RunSQL(const char* pszUnescapedSQL)
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                     "JSON parsing error: %s (at offset %d)",
-                    json_tokener_errors[jstok->err], jstok->char_offset);
+                    json_tokener_error_desc(jstok->err), jstok->char_offset);
         json_tokener_free(jstok);
         CPLHTTPDestroyResult(psResult);
         return NULL;
diff --git a/ogr/ogrsf_frmts/cartodb/ogrcartodbtablelayer.cpp b/ogr/ogrsf_frmts/cartodb/ogrcartodbtablelayer.cpp
index c5734e3..9564323 100644
--- a/ogr/ogrsf_frmts/cartodb/ogrcartodbtablelayer.cpp
+++ b/ogr/ogrsf_frmts/cartodb/ogrcartodbtablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcartodbtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcartodbtablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CartoDB Translator
  * Purpose:  Implements OGRCARTODBTableLayer class.
@@ -30,7 +30,7 @@
 #include "ogr_cartodb.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrcartodbtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcartodbtablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                    OGRCARTODBEscapeIdentifier( )                     */
@@ -226,8 +226,7 @@ OGRErr OGRCARTODBTableLayer::RollbackTransaction()
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRCARTODBTableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK )
-
+OGRErr OGRCARTODBTableLayer::CreateField( OGRFieldDefn *poFieldIn, CPL_UNUSED int bApproxOK )
 {
     GetLayerDefn();
 
diff --git a/ogr/ogrsf_frmts/couchdb/ogrcouchdbdatasource.cpp b/ogr/ogrsf_frmts/couchdb/ogrcouchdbdatasource.cpp
index a7ae260..0fddeec 100644
--- a/ogr/ogrsf_frmts/couchdb/ogrcouchdbdatasource.cpp
+++ b/ogr/ogrsf_frmts/couchdb/ogrcouchdbdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcouchdbdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcouchdbdatasource.cpp 27268 2014-05-01 10:46:20Z rouault $
  *
  * Project:  CouchDB Translator
  * Purpose:  Implements OGRCouchDBDataSource class
@@ -30,7 +30,7 @@
 #include "ogr_couchdb.h"
 #include "swq.h"
 
-CPL_CVSID("$Id: ogrcouchdbdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcouchdbdatasource.cpp 27268 2014-05-01 10:46:20Z rouault $");
 
 /************************************************************************/
 /*                        OGRCouchDBDataSource()                        */
@@ -1078,7 +1078,7 @@ json_object* OGRCouchDBDataSource::REQUEST(const char* pszVerb,
     {
         CPLError( CE_Failure, CPLE_AppDefined,
                     "JSON parsing error: %s (at offset %d)",
-                    json_tokener_errors[jstok->err], jstok->char_offset);
+                    json_tokener_error_desc(jstok->err), jstok->char_offset);
 
         json_tokener_free(jstok);
 
diff --git a/ogr/ogrsf_frmts/couchdb/ogrcouchdbdriver.cpp b/ogr/ogrsf_frmts/couchdb/ogrcouchdbdriver.cpp
index 8951c1e..4317240 100644
--- a/ogr/ogrsf_frmts/couchdb/ogrcouchdbdriver.cpp
+++ b/ogr/ogrsf_frmts/couchdb/ogrcouchdbdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcouchdbdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcouchdbdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CouchDB Translator
  * Purpose:  Implements OGRCouchDBDriver.
@@ -31,7 +31,7 @@
 
 // g++ -g -Wall -fPIC -shared -o ogr_CouchDB.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts -Iogr/ogrsf_frmts/couchdb ogr/ogrsf_frmts/couchdb/*.c* -L. -lgdal -Iogr/ogrsf_frmts/geojson/jsonc
 
-CPL_CVSID("$Id: ogrcouchdbdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcouchdbdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRCouchDB();
 
@@ -78,8 +78,7 @@ OGRDataSource *OGRCouchDBDriver::Open( const char * pszFilename, int bUpdate )
 /************************************************************************/
 
 OGRDataSource *OGRCouchDBDriver::CreateDataSource( const char * pszName,
-                                               char **papszOptions )
-
+                                                   CPL_UNUSED char **papszOptions )
 {
     OGRCouchDBDataSource   *poDS = new OGRCouchDBDataSource();
 
diff --git a/ogr/ogrsf_frmts/couchdb/ogrcouchdbtablelayer.cpp b/ogr/ogrsf_frmts/couchdb/ogrcouchdbtablelayer.cpp
index c586430..5ba7424 100644
--- a/ogr/ogrsf_frmts/couchdb/ogrcouchdbtablelayer.cpp
+++ b/ogr/ogrsf_frmts/couchdb/ogrcouchdbtablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcouchdbtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcouchdbtablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CouchDB Translator
  * Purpose:  Implements OGRCouchDBTableLayer class.
@@ -34,7 +34,7 @@
 
 #include <algorithm>
 
-CPL_CVSID("$Id: ogrcouchdbtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcouchdbtablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                       OGRCouchDBTableLayer()                         */
@@ -1034,7 +1034,7 @@ int OGRCouchDBTableLayer::GetTotalFeatureCount()
 /************************************************************************/
 
 OGRErr OGRCouchDBTableLayer::CreateField( OGRFieldDefn *poField,
-                                 int bApproxOK )
+                                          CPL_UNUSED int bApproxOK )
 {
 
     if (!poDS->IsReadWrite())
diff --git a/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp b/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp
index 7b1b99d..56d191f 100644
--- a/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp
+++ b/ogr/ogrsf_frmts/csv/ogrcsvdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcsvdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcsvdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CSV Translator
  * Purpose:  Implements OGRCSVDataSource class
@@ -34,7 +34,7 @@
 #include "cpl_csv.h"
 #include "cpl_vsi_virtual.h"
 
-CPL_CVSID("$Id: ogrcsvdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcsvdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRCSVDataSource()                          */
@@ -466,7 +466,7 @@ int OGRCSVDataSource::OpenTable( const char * pszFilename,
 
 OGRLayer *
 OGRCSVDataSource::CreateLayer( const char *pszLayerName, 
-                               OGRSpatialReference *poSpatialRef,
+                               CPL_UNUSED OGRSpatialReference *poSpatialRef,
                                OGRwkbGeometryType eGType,
                                char ** papszOptions  )
 
diff --git a/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp b/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp
index 66ce065..6f0d852 100644
--- a/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp
+++ b/ogr/ogrsf_frmts/csv/ogrcsvlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrcsvlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrcsvlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  CSV Translator
  * Purpose:  Implements OGRCSVLayer class.
@@ -34,7 +34,7 @@
 #include "cpl_csv.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrcsvlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrcsvlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 
 
@@ -983,7 +983,7 @@ OGRErr OGRCSVLayer::CreateField( OGRFieldDefn *poNewField, int bApproxOK )
 /************************************************************************/
 
 OGRErr OGRCSVLayer::CreateGeomField( OGRGeomFieldDefn *poGeomField,
-                                     int bApproxOK )
+                                     CPL_UNUSED int bApproxOK )
 
 {
     if( !TestCapability(OLCCreateGeomField) )
@@ -1275,21 +1275,16 @@ OGRErr OGRCSVLayer::CreateFeature( OGRFeature *poNewFeature )
 
     if( bHiddenWKTColumn )
     {
-        char *pszEscaped;
+        char *pszWKT = NULL;
         OGRGeometry     *poGeom = poNewFeature->GetGeomFieldRef(0);
-        if (poGeom && poGeom->exportToWkt(&pszEscaped) == OGRERR_NONE)
+        if (poGeom && poGeom->exportToWkt(&pszWKT) == OGRERR_NONE)
         {
-            char* pszNew = CPLStrdup(CPLSPrintf("\"%s\"", pszEscaped));
-            CPLFree(pszEscaped);
-            pszEscaped = pszNew;
+            bNonEmptyLine = TRUE;
+            VSIFWriteL( "\"", 1, 1, fpCSV );
+            VSIFWriteL( pszWKT, 1, strlen(pszWKT), fpCSV );
+            VSIFWriteL( "\"", 1, 1, fpCSV );
         }
-        else
-            pszEscaped = CPLStrdup("");
-
-        int nLen = (int)strlen(pszEscaped);
-        bNonEmptyLine |= (nLen != 0);
-        VSIFWriteL( pszEscaped, 1, nLen, fpCSV );
-        CPLFree( pszEscaped );
+        CPLFree(pszWKT);
     }
 
 /* -------------------------------------------------------------------- */
@@ -1310,7 +1305,12 @@ OGRErr OGRCSVLayer::CreateFeature( OGRFeature *poNewFeature )
             OGRGeometry     *poGeom = poNewFeature->GetGeomFieldRef(iGeom);
             if (poGeom && poGeom->exportToWkt(&pszEscaped) == OGRERR_NONE)
             {
-                char* pszNew = CPLStrdup(CPLSPrintf("\"%s\"", pszEscaped));
+                int nLenWKT = (int)strlen(pszEscaped);
+                char* pszNew = (char*) CPLMalloc(1 + nLenWKT + 1 + 1);
+                pszNew[0] = '"';
+                memcpy(pszNew + 1, pszEscaped, nLenWKT);
+                pszNew[1 + nLenWKT] = '"';
+                pszNew[1 + nLenWKT + 1] = '\0';
                 CPLFree(pszEscaped);
                 pszEscaped = pszNew;
             }
diff --git a/ogr/ogrsf_frmts/dgn/dgnhelp.cpp b/ogr/ogrsf_frmts/dgn/dgnhelp.cpp
index e39266f..458454f 100644
--- a/ogr/ogrsf_frmts/dgn/dgnhelp.cpp
+++ b/ogr/ogrsf_frmts/dgn/dgnhelp.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dgnhelp.cpp 15591 2008-10-24 19:43:56Z warmerdam $
+ * $Id: dgnhelp.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Microstation DGN Access Library
  * Purpose:  Application visible helper functions for parsing DGN information.
@@ -29,7 +29,7 @@
 
 #include "dgnlibp.h"
 
-CPL_CVSID("$Id: dgnhelp.cpp 15591 2008-10-24 19:43:56Z warmerdam $");
+CPL_CVSID("$Id: dgnhelp.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static unsigned char abyDefaultPCT[256][3] = 
 {
@@ -512,7 +512,7 @@ void DGNAsciiToRad50( const char *str, unsigned short *pRad50 )
 /*      The got name is stored in psLine.                               */
 /************************************************************************/
 
-int DGNGetLineStyleName(DGNInfo *psDGN, DGNElemMultiPoint *psLine,
+int DGNGetLineStyleName(CPL_UNUSED DGNInfo *psDGN, DGNElemMultiPoint *psLine,
                         char szLineStyle[65] )
 {
     if (psLine->core.attr_bytes > 0 &&
@@ -1200,7 +1200,7 @@ const char *DGNTypeToName( int nType )
  * @return size of linkage in bytes, or zero. 
  */
 
-int DGNGetAttrLinkSize( DGNHandle hDGN, DGNElemCore *psElement, 
+int DGNGetAttrLinkSize( CPL_UNUSED DGNHandle hDGN, DGNElemCore *psElement, 
                         int nOffset )
 
 {
@@ -1367,7 +1367,9 @@ void DGNQuaternionToMatrix( int *quat, float *mat )
 /*                  DGNTransformPointWithQuaternion()                   */
 /************************************************************************/
 
-void DGNTransformPointWithQuaternionVertex( int *quat, DGNPoint *v1, DGNPoint *v2 )
+void DGNTransformPointWithQuaternionVertex( CPL_UNUSED int *quat,
+                                            CPL_UNUSED DGNPoint *v1,
+                                            CPL_UNUSED DGNPoint *v2 )
 {
 
 /* ==================================================================== */
diff --git a/ogr/ogrsf_frmts/dgn/dgnread.cpp b/ogr/ogrsf_frmts/dgn/dgnread.cpp
index 7a3c74b..af307d1 100644
--- a/ogr/ogrsf_frmts/dgn/dgnread.cpp
+++ b/ogr/ogrsf_frmts/dgn/dgnread.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dgnread.cpp 21684 2011-02-11 22:14:01Z warmerdam $
+ * $Id: dgnread.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Microstation DGN Access Library
  * Purpose:  DGN Access Library element reading code.
@@ -29,7 +29,7 @@
 
 #include "dgnlibp.h"
 
-CPL_CVSID("$Id: dgnread.cpp 21684 2011-02-11 22:14:01Z warmerdam $");
+CPL_CVSID("$Id: dgnread.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static DGNElemCore *DGNParseTCB( DGNInfo * );
 static DGNElemCore *DGNParseColorTable( DGNInfo * );
@@ -1463,8 +1463,7 @@ static DGNElemCore *DGNParseTCB( DGNInfo * psDGN )
  * @param psElement the element structure returned by DGNReadElement().
  */
 
-void DGNFreeElement( DGNHandle hDGN, DGNElemCore *psElement )
-
+void DGNFreeElement( CPL_UNUSED DGNHandle hDGN, DGNElemCore *psElement )
 {
     if( psElement->attr_data != NULL )
         VSIFree( psElement->attr_data );
diff --git a/ogr/ogrsf_frmts/dgn/dgnstroke.cpp b/ogr/ogrsf_frmts/dgn/dgnstroke.cpp
index b94bc25..709e708 100644
--- a/ogr/ogrsf_frmts/dgn/dgnstroke.cpp
+++ b/ogr/ogrsf_frmts/dgn/dgnstroke.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dgnstroke.cpp 18382 2009-12-24 05:17:27Z warmerdam $
+ * $Id: dgnstroke.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Microstation DGN Access Library
  * Purpose:  Code to stroke Arcs/Ellipses into polylines.
@@ -30,7 +30,7 @@
 #include "dgnlibp.h"
 #include <math.h>
 
-CPL_CVSID("$Id: dgnstroke.cpp 18382 2009-12-24 05:17:27Z warmerdam $");
+CPL_CVSID("$Id: dgnstroke.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define DEG_TO_RAD (PI/180.0)
 
@@ -72,7 +72,7 @@ static void ComputePointOnArc2D( double dfPrimary, double dfSecondary,
  * @return TRUE on success or FALSE on failure.
  */
 
-int DGNStrokeArc( DGNHandle hFile, DGNElemArc *psArc, 
+int DGNStrokeArc( CPL_UNUSED DGNHandle hFile, DGNElemArc *psArc, 
                   int nPoints, DGNPoint * pasPoints )
 
 {
@@ -127,7 +127,7 @@ int DGNStrokeArc( DGNHandle hFile, DGNElemArc *psArc,
  * @return TRUE on success or FALSE on failure.
  */
 
-int DGNStrokeCurve( DGNHandle hFile, DGNElemMultiPoint *psCurve, 
+int DGNStrokeCurve( CPL_UNUSED DGNHandle hFile, DGNElemMultiPoint *psCurve, 
                     int nPoints, DGNPoint * pasPoints )
 
 {
diff --git a/ogr/ogrsf_frmts/dgn/dgnwrite.cpp b/ogr/ogrsf_frmts/dgn/dgnwrite.cpp
index 2ac49da..b303d8c 100644
--- a/ogr/ogrsf_frmts/dgn/dgnwrite.cpp
+++ b/ogr/ogrsf_frmts/dgn/dgnwrite.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: dgnwrite.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: dgnwrite.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Microstation DGN Access Library
  * Purpose:  DGN Access functions related to writing DGN elements.
@@ -30,7 +30,7 @@
 
 #include "dgnlibp.h"
 
-CPL_CVSID("$Id: dgnwrite.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: dgnwrite.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static void DGNPointToInt( DGNInfo *psDGN, DGNPoint *psPoint, 
                            unsigned char *pabyTarget );
@@ -451,9 +451,8 @@ DGNHandle
  * the source element suitable to write to hDGNDst. 
  */
 
-DGNElemCore *DGNCloneElement( DGNHandle hDGNSrc, DGNHandle hDGNDst, 
+DGNElemCore *DGNCloneElement( CPL_UNUSED DGNHandle hDGNSrc, DGNHandle hDGNDst, 
                               DGNElemCore *psSrcElement )
-
 {
     DGNElemCore *psClone = NULL;
 
@@ -760,8 +759,7 @@ int DGNUpdateElemCore( DGNHandle hDGN, DGNElemCore *psElement,
  */
 
 
-int DGNUpdateElemCoreExtended( DGNHandle hDGN, DGNElemCore *psElement )
-
+int DGNUpdateElemCoreExtended( CPL_UNUSED DGNHandle hDGN, DGNElemCore *psElement )
 {
     GByte *rd = psElement->raw_data;
     int   nWords = (psElement->raw_bytes / 2) - 2;
@@ -818,8 +816,7 @@ int DGNUpdateElemCoreExtended( DGNHandle hDGN, DGNElemCore *psElement )
 /*                         DGNInitializeElemCore()                      */
 /************************************************************************/
 
-static void DGNInitializeElemCore( DGNHandle hDGN, DGNElemCore *psElement )
-
+static void DGNInitializeElemCore( CPL_UNUSED DGNHandle hDGN, DGNElemCore *psElement )
 {
     memset( psElement, 0, sizeof(DGNElemCore) );
 
diff --git a/ogr/ogrsf_frmts/dgn/ogrdgnlayer.cpp b/ogr/ogrsf_frmts/dgn/ogrdgnlayer.cpp
index eec9496..0cfebbe 100644
--- a/ogr/ogrsf_frmts/dgn/ogrdgnlayer.cpp
+++ b/ogr/ogrsf_frmts/dgn/ogrdgnlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrdgnlayer.cpp 26929 2014-02-11 20:45:17Z rouault $
+ * $Id: ogrdgnlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRDGNLayer class.
@@ -33,7 +33,7 @@
 #include "ogr_api.h"
 #include <list>
 
-CPL_CVSID("$Id: ogrdgnlayer.cpp 26929 2014-02-11 20:45:17Z rouault $");
+CPL_CVSID("$Id: ogrdgnlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRDGNLayer()                              */
@@ -802,8 +802,7 @@ int OGRDGNLayer::GetFeatureCount( int bForce )
 /*                             GetExtent()                              */
 /************************************************************************/
 
-OGRErr OGRDGNLayer::GetExtent( OGREnvelope *psExtent, int bForce )
-
+OGRErr OGRDGNLayer::GetExtent( OGREnvelope *psExtent, CPL_UNUSED int bForce )
 {
     double      adfExtents[6];
 
@@ -1143,7 +1142,7 @@ OGRErr OGRDGNLayer::CreateFeatureWithGeom( OGRFeature *poFeature,
     nColor = MAX(0,MIN(255,nColor));
     nWeight = MAX(0,MIN(31,nWeight));
     nStyle = MAX(0,MIN(7,nStyle));
-    nMSLink = MAX(0,MIN(4294967295,nMSLink));
+    nMSLink = MAX(0,nMSLink);
 
     DGNUpdateElemCore( hDGN, papsGroup[0], nLevel, nGraphicGroup, nColor, 
                        nWeight, nStyle );
diff --git a/ogr/ogrsf_frmts/dxf/ogrdxfdatasource.cpp b/ogr/ogrsf_frmts/dxf/ogrdxfdatasource.cpp
index d433800..a2afab1 100644
--- a/ogr/ogrsf_frmts/dxf/ogrdxfdatasource.cpp
+++ b/ogr/ogrsf_frmts/dxf/ogrdxfdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrdxfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrdxfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DXF Translator
  * Purpose:  Implements OGRDXFDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrdxfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrdxfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRDXFDataSource()                          */
@@ -74,8 +74,7 @@ OGRDXFDataSource::~OGRDXFDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRDXFDataSource::TestCapability( const char * pszCap )
-
+int OGRDXFDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp b/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp
index 8e1969b..6b1385a 100644
--- a/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp
+++ b/ogr/ogrsf_frmts/dxf/ogrdxfdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrdxfdriver.cpp 22527 2011-06-13 03:58:34Z warmerdam $
+ * $Id: ogrdxfdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DXF Translator
  * Purpose:  Implements OGRDXFDriver.
@@ -30,7 +30,7 @@
 #include "ogr_dxf.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrdxfdriver.cpp 22527 2011-06-13 03:58:34Z warmerdam $");
+CPL_CVSID("$Id: ogrdxfdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          ~OGRDXFDriver()                          */
@@ -55,8 +55,7 @@ const char *OGRDXFDriver::GetName()
 /*                                Open()                                */
 /************************************************************************/
 
-OGRDataSource *OGRDXFDriver::Open( const char * pszFilename, int bUpdate )
-
+OGRDataSource *OGRDXFDriver::Open( const char * pszFilename, CPL_UNUSED int bUpdate )
 {
     OGRDXFDataSource   *poDS = new OGRDXFDataSource();
 
diff --git a/ogr/ogrsf_frmts/dxf/ogrdxfwriterlayer.cpp b/ogr/ogrsf_frmts/dxf/ogrdxfwriterlayer.cpp
index 7c9000e..a189760 100644
--- a/ogr/ogrsf_frmts/dxf/ogrdxfwriterlayer.cpp
+++ b/ogr/ogrsf_frmts/dxf/ogrdxfwriterlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrdxfwriterlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrdxfwriterlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  DXF Translator
  * Purpose:  Implements OGRDXFWriterLayer - the OGRLayer class used for
@@ -34,7 +34,7 @@
 #include "cpl_string.h"
 #include "ogr_featurestyle.h"
 
-CPL_CVSID("$Id: ogrdxfwriterlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrdxfwriterlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #ifndef PI
 #define PI  3.14159265358979323846
@@ -519,9 +519,8 @@ OGRErr OGRDXFWriterLayer::WriteTEXT( OGRFeature *poFeature )
 /*                     PrepareLineTypeDefinition()                      */
 /************************************************************************/
 CPLString 
-OGRDXFWriterLayer::PrepareLineTypeDefinition( OGRFeature *poFeature, 
+OGRDXFWriterLayer::PrepareLineTypeDefinition( CPL_UNUSED OGRFeature *poFeature,
                                               OGRStyleTool *poTool )
-
 {
     CPLString osDef;
     OGRStylePen *poPen = (OGRStylePen *) poTool;
diff --git a/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp b/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp
index 2e2844f..b4669e5 100644
--- a/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp
+++ b/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogredigeodatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogredigeodatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  EDIGEO Translator
  * Purpose:  Implements OGREDIGEODataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogredigeodatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogredigeodatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #ifndef M_PI
 # define M_PI  3.1415926535897932384626433832795
@@ -94,8 +94,7 @@ OGREDIGEODataSource::~OGREDIGEODataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGREDIGEODataSource::TestCapability( const char * pszCap )
-
+int OGREDIGEODataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp b/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp
index 355be16..dd0d275 100644
--- a/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp
+++ b/ogr/ogrsf_frmts/edigeo/ogredigeodriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogredigeodriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogredigeodriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  EDIGEO Translator
  * Purpose:  Implements OGREDIGEODriver.
@@ -30,7 +30,7 @@
 #include "ogr_edigeo.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogredigeodriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogredigeodriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGREDIGEO();
 
@@ -77,8 +77,7 @@ OGRDataSource *OGREDIGEODriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGREDIGEODriver::TestCapability( const char * pszCap )
-
+int OGREDIGEODriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/elastic/ogrelasticdatasource.cpp b/ogr/ogrsf_frmts/elastic/ogrelasticdatasource.cpp
index 424219c..7a74ef9 100644
--- a/ogr/ogrsf_frmts/elastic/ogrelasticdatasource.cpp
+++ b/ogr/ogrsf_frmts/elastic/ogrelasticdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrelasticdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrelasticdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ElasticSearch Translator
  * Purpose:
@@ -28,7 +28,8 @@
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
 
-#pragma warning( disable : 4251 )
+/* This pragma was for what? */
+/* #pragma warning( disable : 4251 ) */
 
 #include "ogr_elastic.h"
 #include "cpl_conv.h"
@@ -36,7 +37,7 @@
 #include "cpl_csv.h"
 #include "cpl_http.h"
 
-CPL_CVSID("$Id: ogrelasticdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrelasticdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRElasticDataSource()                        */
@@ -90,9 +91,9 @@ OGRLayer *OGRElasticDataSource::GetLayer(int iLayer) {
 /************************************************************************/
 
 OGRLayer * OGRElasticDataSource::CreateLayer(const char * pszLayerName,
-        OGRSpatialReference *poSRS,
-        OGRwkbGeometryType eType,
-        char ** papszOptions) {
+                                             OGRSpatialReference *poSRS,
+                                             CPL_UNUSED OGRwkbGeometryType eType,
+                                             CPL_UNUSED char ** papszOptions) {
     nLayers++;
     papoLayers = (OGRElasticLayer **) CPLRealloc(papoLayers, nLayers * sizeof (OGRElasticLayer*));
     papoLayers[nLayers - 1] = new OGRElasticLayer(pszName, pszLayerName, this, poSRS, TRUE);
@@ -104,7 +105,8 @@ OGRLayer * OGRElasticDataSource::CreateLayer(const char * pszLayerName,
 /*                                Open()                                */
 /************************************************************************/
 
-int OGRElasticDataSource::Open(const char * pszFilename, int bUpdateIn) {
+int OGRElasticDataSource::Open(CPL_UNUSED const char * pszFilename,
+                               CPL_UNUSED int bUpdateIn) {
     CPLError(CE_Failure, CPLE_NotSupported,
             "OGR/Elastic driver does not support opening a file");
     return FALSE;
@@ -147,8 +149,7 @@ void OGRElasticDataSource::UploadFile(const CPLString &url, const CPLString &dat
 /************************************************************************/
 
 int OGRElasticDataSource::Create(const char *pszFilename,
-        char **papszOptions) {
-
+                                 CPL_UNUSED char **papszOptions) {
     this->pszName = CPLStrdup(pszFilename);
 
     const char* pszMetaFile = CPLGetConfigOption("ES_META", NULL);
diff --git a/ogr/ogrsf_frmts/elastic/ogrelasticdriver.cpp b/ogr/ogrsf_frmts/elastic/ogrelasticdriver.cpp
index 5843e25..ddd9af6 100644
--- a/ogr/ogrsf_frmts/elastic/ogrelasticdriver.cpp
+++ b/ogr/ogrsf_frmts/elastic/ogrelasticdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrelasticdriver.cpp 23836 2012-01-31 19:32:04Z rouault $
+ * $Id: ogrelasticdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ElasticSearch Translator
  * Purpose:
@@ -30,7 +30,7 @@
 #include "ogr_elastic.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrelasticdriver.cpp 23836 2012-01-31 19:32:04Z rouault $");
+CPL_CVSID("$Id: ogrelasticdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         ~OGRElasticDriver()                          */
@@ -51,7 +51,8 @@ const char *OGRElasticDriver::GetName() {
 /*                                Open()                                */
 /************************************************************************/
 
-OGRDataSource *OGRElasticDriver::Open(const char * pszFilename, int bUpdate) {
+OGRDataSource *OGRElasticDriver::Open(CPL_UNUSED const char * pszFilename,
+                                      CPL_UNUSED int bUpdate) {
     return NULL;
 }
 
diff --git a/ogr/ogrsf_frmts/elastic/ogrelasticlayer.cpp b/ogr/ogrsf_frmts/elastic/ogrelasticlayer.cpp
index ad412e3..5c025a8 100644
--- a/ogr/ogrsf_frmts/elastic/ogrelasticlayer.cpp
+++ b/ogr/ogrsf_frmts/elastic/ogrelasticlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrelasticlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrelasticlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ElasticSearch Translator
  * Purpose:
@@ -35,17 +35,17 @@
 #include "ogr_p.h"
 #include <json.h> // JSON-C
 
-CPL_CVSID("$Id: ogrelasticlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrelasticlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRElasticLayer()                          */
 /************************************************************************/
 
-OGRElasticLayer::OGRElasticLayer(const char* pszFilename,
-        const char* pszLayerName,
-        OGRElasticDataSource* poDS,
-        OGRSpatialReference *poSRSIn,
-        int bWriteMode) {
+OGRElasticLayer::OGRElasticLayer(CPL_UNUSED const char* pszFilename,
+                                 const char* pszLayerName,
+                                 OGRElasticDataSource* poDS,
+                                 OGRSpatialReference *poSRSIn,
+                                 CPL_UNUSED int bWriteMode) {
     this->pszLayerName = CPLStrdup(pszLayerName);
     this->poDS = poDS;
     this->pAttributes = NULL;
@@ -285,7 +285,8 @@ void OGRElasticLayer::PushIndex() {
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRElasticLayer::CreateField(OGRFieldDefn *poFieldDefn, int bApproxOK) {
+OGRErr OGRElasticLayer::CreateField(OGRFieldDefn *poFieldDefn,
+                                    CPL_UNUSED int bApproxOK) {
     if (!pAttributes) {
         pAttributes = json_object_new_object();
     }
@@ -345,7 +346,7 @@ int OGRElasticLayer::TestCapability(const char * pszCap) {
 /*                          GetFeatureCount()                           */
 /************************************************************************/
 
-int OGRElasticLayer::GetFeatureCount(int bForce) {
+int OGRElasticLayer::GetFeatureCount(CPL_UNUSED int bForce) {
     CPLError(CE_Failure, CPLE_NotSupported,
             "Cannot read features when writing a Elastic file");
     return 0;
diff --git a/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp b/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp
index 2a75f81..edfe1fa 100644
--- a/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp
+++ b/ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
-* $Id: FGdbLayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+* $Id: FGdbLayer.cpp 27654 2014-09-09 18:28:10Z rouault $
 *
 * Project:  OpenGIS Simple Features Reference Implementation
 * Purpose:  Implements FileGDB OGR layer.
@@ -9,7 +9,7 @@
 ******************************************************************************
 * Copyright (c) 2010, Ragi Yaser Burhum
 * Copyright (c) 2011, Paul Ramsey <pramsey at cleverelephant.ca>
- * Copyright (c) 2011-2014, Even Rouault <even dot rouault at mines-paris dot org>
+ * Copyright (c) 2011-2014, Even Rouault <even dot rouault at mines-paris dot org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
@@ -37,7 +37,7 @@
 #include "FGdbUtils.h"
 #include "cpl_minixml.h" // the only way right now to extract schema information
 
-CPL_CVSID("$Id: FGdbLayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: FGdbLayer.cpp 27654 2014-09-09 18:28:10Z rouault $");
 
 using std::string;
 using std::wstring;
@@ -1724,7 +1724,7 @@ bool FGdbLayer::ParseGeometryDef(CPLXMLNode* psRoot)
 
     string geometryType;
     bool hasZ = false;
-    string wkt, wkid;
+    string wkt, wkid, latestwkid;
 
     for (psGeometryDefItem = psRoot->psChild;
         psGeometryDefItem != NULL;
@@ -1747,7 +1747,7 @@ bool FGdbLayer::ParseGeometryDef(CPLXMLNode* psRoot)
             }
             else if (EQUAL(psGeometryDefItem->pszValue,"SpatialReference"))
             {
-                ParseSpatialReference(psGeometryDefItem, &wkt, &wkid); // we don't check for success because it
+                ParseSpatialReference(psGeometryDefItem, &wkt, &wkid, &latestwkid); // we don't check for success because it
                                                                 // may not be there
             }
             /* No M support in OGR yet
@@ -1785,10 +1785,36 @@ bool FGdbLayer::ParseGeometryDef(CPLXMLNode* psRoot)
         wkbFlatten(ogrGeoType) == wkbMultiPoint)
         m_forceMulti = true;
 
-    if (wkid.length() > 0)
+    if (latestwkid.length() > 0 || wkid.length() > 0)
     {
+        int bSuccess = FALSE;
         m_pSRS = new OGRSpatialReference();
-        if (m_pSRS->importFromEPSG(atoi(wkid.c_str())) != OGRERR_NONE)
+        CPLPushErrorHandler(CPLQuietErrorHandler);
+        if( latestwkid.length() > 0 )
+        {
+            if( m_pSRS->importFromEPSG(atoi(latestwkid.c_str())) == OGRERR_NONE )
+            {
+                bSuccess = TRUE;
+            }
+            else
+            {
+                CPLDebug("FGDB", "Cannot import SRID %s", latestwkid.c_str());
+            }
+        }
+        if( !bSuccess && wkid.length() > 0 )
+        {
+            if( m_pSRS->importFromEPSG(atoi(wkid.c_str())) == OGRERR_NONE )
+            {
+                bSuccess = TRUE;
+            }
+            else
+            {
+                CPLDebug("OpenFileGDB", "Cannot import SRID %s", wkid.c_str());
+            }
+        }
+        CPLPopErrorHandler();
+        CPLErrorReset();
+        if( !bSuccess )
         {
             delete m_pSRS;
             m_pSRS = NULL;
@@ -1820,7 +1846,7 @@ bool FGdbLayer::ParseGeometryDef(CPLXMLNode* psRoot)
 /************************************************************************/
 
 bool FGdbLayer::ParseSpatialReference(CPLXMLNode* psSpatialRefNode,
-                                      string* pOutWkt, string* pOutWKID)
+                                      string* pOutWkt, string* pOutWKID, string* pOutLatestWKID)
 {
     *pOutWkt = "";
     *pOutWKID = "";
@@ -1841,6 +1867,15 @@ bool FGdbLayer::ParseSpatialReference(CPLXMLNode* psSpatialRefNode,
             *pOutWKID = pszUnescaped;
             CPLFree(pszUnescaped);
         }
+        /* The concept of LatestWKID is explained in http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000n1000000 */
+        else if( psSRItemNode->eType == CXT_Element &&
+            psSRItemNode->psChild != NULL &&
+            EQUAL(psSRItemNode->pszValue,"LatestWKID") )
+        {
+            char* pszUnescaped = CPLUnescapeString(psSRItemNode->psChild->pszValue, NULL, CPLES_XML);
+            *pOutLatestWKID = pszUnescaped;
+            CPLFree(pszUnescaped);
+        }
         /* The WKT well-known text can be converted by OGR */
         else if( psSRItemNode->eType == CXT_Element &&
                 psSRItemNode->psChild != NULL &&
diff --git a/ogr/ogrsf_frmts/filegdb/ogr_fgdb.h b/ogr/ogrsf_frmts/filegdb/ogr_fgdb.h
index 9904938..6a0e7b3 100644
--- a/ogr/ogrsf_frmts/filegdb/ogr_fgdb.h
+++ b/ogr/ogrsf_frmts/filegdb/ogr_fgdb.h
@@ -1,5 +1,5 @@
 /******************************************************************************
-* $Id: ogr_fgdb.h 27044 2014-03-16 23:41:27Z rouault $
+* $Id: ogr_fgdb.h 27654 2014-09-09 18:28:10Z rouault $
 *
 * Project:  OpenGIS Simple Features Reference Implementation
 * Purpose:  Standard includes and class definitions ArcObjects OGR driver.
@@ -181,7 +181,8 @@ protected:
 
   bool GDBToOGRFields(CPLXMLNode* psFields);  
   bool ParseGeometryDef(CPLXMLNode* psGeometryDef);
-  bool ParseSpatialReference(CPLXMLNode* psSpatialRefNode, std::string* pOutWkt, std::string* pOutWKID);
+  bool ParseSpatialReference(CPLXMLNode* psSpatialRefNode, std::string* pOutWkt,
+                             std::string* pOutWKID, std::string* pOutLatestWKID);
 
   FGdbDataSource* m_pDS;
   Table* m_pTable;
diff --git a/ogr/ogrsf_frmts/generic/ogrlayer.cpp b/ogr/ogrsf_frmts/generic/ogrlayer.cpp
index 4284322..c23d798 100644
--- a/ogr/ogrsf_frmts/generic/ogrlayer.cpp
+++ b/ogr/ogrsf_frmts/generic/ogrlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  The generic portions of the OGRSFLayer class.
@@ -34,7 +34,7 @@
 #include "ogr_attrind.h"
 #include "swq.h"
 
-CPL_CVSID("$Id: ogrlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                              OGRLayer()                              */
@@ -879,7 +879,7 @@ int OGR_L_FindFieldIndex( OGRLayerH hLayer, const char *pszFieldName, int bExact
 /*                           FindFieldIndex()                           */
 /************************************************************************/
 
-int OGRLayer::FindFieldIndex( const char *pszFieldName, int bExactMatch )
+int OGRLayer::FindFieldIndex( const char *pszFieldName, CPL_UNUSED int bExactMatch )
 {
     return GetLayerDefn()->GetFieldIndex( pszFieldName );
 }
@@ -1346,7 +1346,7 @@ OGRErr OGR_L_SyncToDisk( OGRLayerH hDS )
 /*                           DeleteFeature()                            */
 /************************************************************************/
 
-OGRErr OGRLayer::DeleteFeature( long nFID )
+OGRErr OGRLayer::DeleteFeature( CPL_UNUSED long nFID )
 
 {
     return OGRERR_UNSUPPORTED_OPERATION;
diff --git a/ogr/ogrsf_frmts/generic/ogrlayerdecorator.cpp b/ogr/ogrsf_frmts/generic/ogrlayerdecorator.cpp
index 8d11f1e..604df53 100644
--- a/ogr/ogrsf_frmts/generic/ogrlayerdecorator.cpp
+++ b/ogr/ogrsf_frmts/generic/ogrlayerdecorator.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrlayerdecorator.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrlayerdecorator.cpp 27588 2014-08-18 20:57:46Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRLayerDecorator class
@@ -29,7 +29,7 @@
 
 #include "ogrlayerdecorator.h"
 
-CPL_CVSID("$Id: ogrlayerdecorator.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrlayerdecorator.cpp 27588 2014-08-18 20:57:46Z rouault $");
 
 OGRLayerDecorator::OGRLayerDecorator(OGRLayer* poDecoratedLayer,
                                      int bTakeOwnership) :
@@ -186,12 +186,12 @@ OGRStyleTable *OGRLayerDecorator::GetStyleTable()
 
 void        OGRLayerDecorator::SetStyleTableDirectly( OGRStyleTable *poStyleTable )
 {
-    return m_poDecoratedLayer->SetStyleTableDirectly(poStyleTable);
+    m_poDecoratedLayer->SetStyleTableDirectly(poStyleTable);
 }
 
 void        OGRLayerDecorator::SetStyleTable(OGRStyleTable *poStyleTable)
 {
-    return m_poDecoratedLayer->SetStyleTable(poStyleTable);
+    m_poDecoratedLayer->SetStyleTable(poStyleTable);
 }
 
 OGRErr      OGRLayerDecorator::StartTransaction()
diff --git a/ogr/ogrsf_frmts/geoconcept/geoconcept.c b/ogr/ogrsf_frmts/geoconcept/geoconcept.c
index e28b2d1..b08f7db 100644
--- a/ogr/ogrsf_frmts/geoconcept/geoconcept.c
+++ b/ogr/ogrsf_frmts/geoconcept/geoconcept.c
@@ -35,7 +35,7 @@
 #include "cpl_string.h"
 #include "ogr_core.h"
 
-GCIO_CVSID("$Id: geoconcept.c,v 1.0.0 2007-11-03 20:58:19 drichard Exp $")
+CPL_CVSID("$Id: geoconcept.c,v 1.0.0 2007-11-03 20:58:19 drichard Exp $")
 
 #define kItemSize_GCIO      256
 #define kExtraSize_GCIO    4096
@@ -4718,8 +4718,8 @@ GCField GCIOAPI_CALL1(*) FindFeatureField_GCIO (
 
 /* -------------------------------------------------------------------- */
 static char GCIOAPI_CALL1(*) _escapeString_GCIO (
-                                                  GCExportFileH* H,
-                                                  const char *theString
+                                                 CPL_UNUSED GCExportFileH* H,
+                                                 const char *theString
                                                 )
 {
   int l, i, o;
diff --git a/ogr/ogrsf_frmts/geoconcept/geoconcept.h b/ogr/ogrsf_frmts/geoconcept/geoconcept.h
index b76e0e1..07153e7 100644
--- a/ogr/ogrsf_frmts/geoconcept/geoconcept.h
+++ b/ogr/ogrsf_frmts/geoconcept/geoconcept.h
@@ -81,21 +81,6 @@
 #  define GCIOAPI_CALL1(x)      x GCIOAPI_CALL
 #endif
 
-/* -------------------------------------------------------------------- */
-/*      Macros for controlling CVSID and ensuring they don't appear     */
-/*      as unreferenced variables resulting in lots of warnings.        */
-/* -------------------------------------------------------------------- */
-#ifndef DISABLE_CVSID
-#if defined(__GNUC__) && __GNUC__ >= 4
-#  define GCIO_CVSID(string)     static char cpl_cvsid[] __attribute__((used)) = string;
-#else
-#  define GCIO_CVSID(string)     static char gcio_cvsid[] = string; \
-static char *cvsid_aw() { return( cvsid_aw() ? ((char *) NULL) : gcio_cvsid ); }
-#endif
-#else
-#  define GCIO_CVSID(string)
-#endif
-
 #ifdef __cplusplus
 extern "C" {
 #endif
diff --git a/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.c b/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.c
index 54f0894..455d788 100644
--- a/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.c
+++ b/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.c
@@ -33,7 +33,7 @@
 #include "geoconcept_syscoord.h"
 #include "cpl_string.h"
 
-GCSRS_CVSID("$Id: geoconcept_syscoord.c,v 1.0.0 2007-12-24 15:40:28 drichard Exp $")
+CPL_CVSID("$Id: geoconcept_syscoord.c,v 1.0.0 2007-12-24 15:40:28 drichard Exp $")
 
 #ifndef PI
 #define PI 3.14159265358979323846
diff --git a/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.h b/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.h
index bc4cd51..a4600c5 100644
--- a/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.h
+++ b/ogr/ogrsf_frmts/geoconcept/geoconcept_syscoord.h
@@ -47,17 +47,6 @@
 #  define GCSRSAPI_CALL1(x) x GCSRSAPI_CALL
 #endif
 
-/* -------------------------------------------------------------------- */
-/*      Macros for controlling CVSID and ensuring they don't appear     */
-/*      as unreferenced variables resulting in lots of warnings.        */
-/* -------------------------------------------------------------------- */
-#ifndef DISABLE_CVSID
-#  define GCSRS_CVSID(string)     static char gcsrs_cvsid[] = string; \
-static char *cvsid_aw() { return( cvsid_aw() ? ((char *) NULL) : gcsrs_cvsid ); }
-#else
-#  define GCSRS_CVSID(string)
-#endif
-
 #ifdef __cplusplus
 extern "C" {
 #endif
diff --git a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptlayer.cpp b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptlayer.cpp
index a3b987e..0e97b18 100644
--- a/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptlayer.cpp
+++ b/ogr/ogrsf_frmts/geoconcept/ogrgeoconceptlayer.cpp
@@ -445,8 +445,7 @@ int OGRGeoconceptLayer::GetFeatureCount( int bForce )
 /*                             GetExtent()                              */
 /************************************************************************/
 
-OGRErr OGRGeoconceptLayer::GetExtent( OGREnvelope* psExtent, int bForce )
-
+OGRErr OGRGeoconceptLayer::GetExtent( OGREnvelope* psExtent, CPL_UNUSED int bForce )
 {
     GCExtent* theExtent;
 
@@ -501,8 +500,7 @@ int OGRGeoconceptLayer::TestCapability( const char* pszCap )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRGeoconceptLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRGeoconceptLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     if( GetGCMode_GCIO(GetSubTypeGCHandle_GCIO(_gcFeature))==vReadAccess_GCIO )
     {
diff --git a/ogr/ogrsf_frmts/geojson/libjson/json_object.c b/ogr/ogrsf_frmts/geojson/libjson/json_object.c
index 6158d05..3547245 100644
--- a/ogr/ogrsf_frmts/geojson/libjson/json_object.c
+++ b/ogr/ogrsf_frmts/geojson/libjson/json_object.c
@@ -429,8 +429,8 @@ void json_object_object_del(struct json_object* jso, const char *key)
 
 static int json_object_boolean_to_json_string(struct json_object* jso,
 					      struct printbuf *pb,
-					      int level,
-						  int flags)
+					      CPL_UNUSED int level,
+                                              CPL_UNUSED int flags)
 {
   if(jso->o.c_boolean) return sprintbuf(pb, "true");
   else return sprintbuf(pb, "false");
@@ -467,8 +467,8 @@ json_bool json_object_get_boolean(struct json_object *jso)
 
 static int json_object_int_to_json_string(struct json_object* jso,
 					  struct printbuf *pb,
-					  int level,
-					  int flags)
+					  CPL_UNUSED int level,
+					  CPL_UNUSED int flags)
 {
   return sprintbuf(pb, "%"PRId64, jso->o.c_int64);
 }
@@ -554,8 +554,8 @@ int64_t json_object_get_int64(struct json_object *jso)
 
 static int json_object_double_to_json_string(struct json_object* jso,
 					     struct printbuf *pb,
-					     int level,
-						 int flags)
+					     CPL_UNUSED int level,
+                                             int flags)
 {
   char buf[128], *p, *q;
   int size;
@@ -612,8 +612,8 @@ double json_object_get_double(struct json_object *jso)
 
 static int json_object_string_to_json_string(struct json_object* jso,
 					     struct printbuf *pb,
-					     int level,
-						 int flags)
+					     CPL_UNUSED int level,
+                                             CPL_UNUSED int flags)
 {
   sprintbuf(pb, "\"");
   json_escape_str(pb, jso->o.c_string.str, jso->o.c_string.len);
diff --git a/ogr/ogrsf_frmts/geojson/libjson/json_object_iterator.c b/ogr/ogrsf_frmts/geojson/libjson/json_object_iterator.c
index 7066649..1a0883a 100644
--- a/ogr/ogrsf_frmts/geojson/libjson/json_object_iterator.c
+++ b/ogr/ogrsf_frmts/geojson/libjson/json_object_iterator.c
@@ -22,6 +22,8 @@
 
 #include "json_object_iterator.h"
 
+#include "cpl_port.h"
+
 /**
  * How It Works
  *
@@ -84,7 +86,7 @@ json_object_iter_begin(struct json_object* obj)
  * ****************************************************************************
  */
 struct json_object_iterator
-json_object_iter_end(const struct json_object* obj)
+json_object_iter_end(CPL_UNUSED const struct json_object* obj)
 {
     struct json_object_iterator iter;
 
diff --git a/ogr/ogrsf_frmts/geojson/ogr_geojson.h b/ogr/ogrsf_frmts/geojson/ogr_geojson.h
index 4a33748..588067a 100644
--- a/ogr/ogrsf_frmts/geojson/ogr_geojson.h
+++ b/ogr/ogrsf_frmts/geojson/ogr_geojson.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_geojson.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_geojson.h 27718 2014-09-21 16:55:01Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Definitions of OGR OGRGeoJSON driver types.
@@ -30,7 +30,9 @@
 #ifndef OGR_GEOJSON_H_INCLUDED
 #define OGR_GEOJSON_H_INCLUDED
 
+#include "cpl_port.h"
 #include <ogrsf_frmts.h>
+
 #include <cstdio>
 #include <vector> // used by OGRGeoJSONLayer
 
@@ -80,7 +82,8 @@ private:
     FeaturesSeq seqFeatures_;
     FeaturesSeq::iterator iterCurrent_;
 
-    OGRGeoJSONDataSource* poDS_;
+    /* poDS_ retained for ABI compatibility. */
+    CPL_UNUSED OGRGeoJSONDataSource* poDS_;
     OGRFeatureDefn* poFeatureDefn_;
     CPLString sFIDColumn_;
 };
diff --git a/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp b/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp
index f33058f..41afbb1 100644
--- a/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogresrijsonreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogresrijsonreader.cpp 27050 2014-03-18 00:09:03Z kyle $
+ * $Id: ogresrijsonreader.cpp 27268 2014-05-01 10:46:20Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of OGRESRIJSONReader class (OGR ESRIJSON Driver)
@@ -78,7 +78,7 @@ OGRErr OGRESRIJSONReader::Parse( const char* pszText )
         {
             CPLError( CE_Failure, CPLE_AppDefined,
                       "ESRIJSON parsing error: %s (at offset %d)",
-            	      json_tokener_errors[jstok->err], jstok->char_offset);
+            	      json_tokener_error_desc(jstok->err), jstok->char_offset);
             
             json_tokener_free(jstok);
             return OGRERR_CORRUPT_DATA;
diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonlayer.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonlayer.cpp
index ad2b13b..bf87689 100644
--- a/ogr/ogrsf_frmts/geojson/ogrgeojsonlayer.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeojsonlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeojsonlayer.cpp 27718 2014-09-21 16:55:01Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of OGRGeoJSONLayer class (OGR GeoJSON Driver).
@@ -51,10 +51,10 @@ const OGRwkbGeometryType OGRGeoJSONLayer::DefaultGeometryType = wkbUnknown;
 OGRGeoJSONLayer::OGRGeoJSONLayer( const char* pszName,
                                   OGRSpatialReference* poSRSIn,
                                   OGRwkbGeometryType eGType,
-                                  OGRGeoJSONDataSource* poDS )
-    : iterCurrent_( seqFeatures_.end() ), poDS_( poDS ), poFeatureDefn_(new OGRFeatureDefn( pszName ) )
+                                  CPL_UNUSED OGRGeoJSONDataSource* poDS )
+  : iterCurrent_( seqFeatures_.end() ), /* poDS_( poDS ), */ poFeatureDefn_(new OGRFeatureDefn( pszName ) )
 {
-    CPLAssert( NULL != poDS_ );
+    /* CPLAssert( NULL != poDS_ ); */
     CPLAssert( NULL != poFeatureDefn_ );
     
     poFeatureDefn_->Reference();
diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp
index bd21b03..48bf918 100644
--- a/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeojsonreader.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeojsonreader.cpp 27613 2014-08-30 15:55:30Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of OGRGeoJSONReader class (OGR GeoJSON Driver).
@@ -71,13 +71,21 @@ OGRErr OGRGeoJSONReader::Parse( const char* pszText )
         json_tokener* jstok = NULL;
         json_object* jsobj = NULL;
 
+        /* Skip UTF-8 BOM (#5630) */
+        const GByte* pabyData = (const GByte*)pszText;
+        if( pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF )
+        {
+            CPLDebug("GeoJSON", "Skip UTF-8 BOM");
+            pszText += 3;
+        }
+
         jstok = json_tokener_new();
         jsobj = json_tokener_parse_ex(jstok, pszText, -1);
         if( jstok->err != json_tokener_success)
         {
             CPLError( CE_Failure, CPLE_AppDefined,
                       "GeoJSON parsing error: %s (at offset %d)",
-            	      json_tokener_errors[jstok->err], jstok->char_offset);
+            	      json_tokener_error_desc(jstok->err), jstok->char_offset);
             
             json_tokener_free(jstok);
             return OGRERR_CORRUPT_DATA;
@@ -1516,7 +1524,7 @@ OGRGeometryH OGR_G_CreateGeometryFromJson( const char* pszJson )
         {
             CPLError( CE_Failure, CPLE_AppDefined,
                       "GeoJSON parsing error: %s (at offset %d)",
-                      json_tokener_errors[jstok->err], jstok->char_offset);
+                      json_tokener_error_desc(jstok->err), jstok->char_offset);
             json_tokener_free(jstok);
             return NULL;
         }
diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonutils.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonutils.cpp
index a86e36c..e6f6e46 100644
--- a/ogr/ogrsf_frmts/geojson/ogrgeojsonutils.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonutils.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeojsonutils.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeojsonutils.cpp 27613 2014-08-30 15:55:30Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of private utilities used within OGR GeoJSON Driver.
@@ -42,6 +42,11 @@ int GeoJSONIsObject( const char* pszText )
     if( NULL == pszText )
         return FALSE;
 
+    /* Skip UTF-8 BOM (#5630) */
+    const GByte* pabyData = (const GByte*)pszText;
+    if( pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF )
+        pszText += 3;
+
 /* -------------------------------------------------------------------- */
 /*      This is a primitive test, but we need to perform it fast.       */
 /* -------------------------------------------------------------------- */
diff --git a/ogr/ogrsf_frmts/geojson/ogrgeojsonwriter.cpp b/ogr/ogrsf_frmts/geojson/ogrgeojsonwriter.cpp
index 2e661cd..198b134 100644
--- a/ogr/ogrsf_frmts/geojson/ogrgeojsonwriter.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogrgeojsonwriter.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeojsonwriter.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeojsonwriter.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of GeoJSON writer utilities (OGR GeoJSON Driver).
@@ -603,8 +603,8 @@ char* OGR_G_ExportToJsonEx( OGRGeometryH hGeometry, char** papszOptions )
 
 static int OGR_json_double_with_precision_to_string(struct json_object *jso,
                                                     struct printbuf *pb,
-                                                    int level,
-                                                    int flags)
+                                                    CPL_UNUSED int level,
+                                                    CPL_UNUSED int flags)
 {
     char szBuffer[75]; 
     int nPrecision = (int) (size_t) jso->_userdata;
diff --git a/ogr/ogrsf_frmts/geojson/ogrtopojsonreader.cpp b/ogr/ogrsf_frmts/geojson/ogrtopojsonreader.cpp
index 0871c65..b558faa 100644
--- a/ogr/ogrsf_frmts/geojson/ogrtopojsonreader.cpp
+++ b/ogr/ogrsf_frmts/geojson/ogrtopojsonreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrtopojsonreader.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrtopojsonreader.cpp 27268 2014-05-01 10:46:20Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implementation of OGRTopoJSONReader class
@@ -74,7 +74,7 @@ OGRErr OGRTopoJSONReader::Parse( const char* pszText )
         {
             CPLError( CE_Failure, CPLE_AppDefined,
                       "TopoJSON parsing error: %s (at offset %d)",
-            	      json_tokener_errors[jstok->err], jstok->char_offset);
+            	      json_tokener_error_desc(jstok->err), jstok->char_offset);
             
             json_tokener_free(jstok);
             return OGRERR_CORRUPT_DATA;
diff --git a/ogr/ogrsf_frmts/georss/ogrgeorssdatasource.cpp b/ogr/ogrsf_frmts/georss/ogrgeorssdatasource.cpp
index 6a3bb04..6baa9ed 100644
--- a/ogr/ogrsf_frmts/georss/ogrgeorssdatasource.cpp
+++ b/ogr/ogrsf_frmts/georss/ogrgeorssdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeorssdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeorssdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GeoRSS Translator
  * Purpose:  Implements OGRGeoRSSDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "cpl_csv.h"
 
-CPL_CVSID("$Id: ogrgeorssdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgeorssdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRGeoRSSDataSource()                          */
@@ -118,9 +118,8 @@ OGRLayer *OGRGeoRSSDataSource::GetLayer( int iLayer )
 
 OGRLayer * OGRGeoRSSDataSource::CreateLayer( const char * pszLayerName,
                                              OGRSpatialReference *poSRS,
-                                             OGRwkbGeometryType eType,
-                                             char ** papszOptions )
-
+                                             CPL_UNUSED OGRwkbGeometryType eType,
+                                             CPL_UNUSED char ** papszOptions )
 {
     if (fpOutput == NULL)
         return NULL;
@@ -188,7 +187,8 @@ void OGRGeoRSSDataSource::startElementValidateCbk(const char *pszName, const cha
 /*                      dataHandlerValidateCbk()                        */
 /************************************************************************/
 
-void OGRGeoRSSDataSource::dataHandlerValidateCbk(const char *data, int nLen)
+void OGRGeoRSSDataSource::dataHandlerValidateCbk(CPL_UNUSED const char *data,
+                                                 CPL_UNUSED int nLen)
 {
     nDataHandlerCounter ++;
     if (nDataHandlerCounter >= BUFSIZ)
diff --git a/ogr/ogrsf_frmts/georss/ogrgeorsslayer.cpp b/ogr/ogrsf_frmts/georss/ogrgeorsslayer.cpp
index 19f573a..6de0e54 100644
--- a/ogr/ogrsf_frmts/georss/ogrgeorsslayer.cpp
+++ b/ogr/ogrsf_frmts/georss/ogrgeorsslayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgeorsslayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgeorsslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GeoRSS Translator
  * Purpose:  Implements OGRGeoRSSLayer class.
@@ -33,7 +33,7 @@
 #include "ogr_api.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrgeorsslayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgeorsslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static const char* apszAllowedATOMFieldNamesWithSubElements[] = { "author", "contributor", NULL };
 
@@ -1634,8 +1634,7 @@ OGRErr OGRGeoRSSLayer::CreateFeature( OGRFeature *poFeature )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRGeoRSSLayer::CreateField( OGRFieldDefn *poFieldDefn, int bApproxOK )
-
+OGRErr OGRGeoRSSLayer::CreateField( OGRFieldDefn *poFieldDefn, CPL_UNUSED int bApproxOK )
 {
     const char* pszName = poFieldDefn->GetNameRef();
     if (((eFormat == GEORSS_RSS && strcmp(pszName, "pubDate") == 0) ||
diff --git a/ogr/ogrsf_frmts/gft/ogrgftdatasource.cpp b/ogr/ogrsf_frmts/gft/ogrgftdatasource.cpp
index cb7cef9..eaa5bc0 100644
--- a/ogr/ogrsf_frmts/gft/ogrgftdatasource.cpp
+++ b/ogr/ogrsf_frmts/gft/ogrgftdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgftdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgftdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Google Fusion Table Translator
  * Purpose:  Implements OGRGFTDataSource class
@@ -29,7 +29,7 @@
 
 #include "ogr_gft.h"
 
-CPL_CVSID("$Id: ogrgftdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgftdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define GDAL_API_KEY "AIzaSyA_2h1_wXMOLHNSVeo-jf1ACME-M1XMgP0"
 #define FUSION_TABLE_SCOPE "https://www.googleapis.com/Fauth/fusiontables"
@@ -305,7 +305,7 @@ const char*  OGRGFTDataSource::GetAPIURL() const
 /************************************************************************/
 
 OGRLayer   *OGRGFTDataSource::CreateLayer( const char *pszName,
-                                           OGRSpatialReference *poSpatialRef,
+                                           CPL_UNUSED OGRSpatialReference *poSpatialRef,
                                            OGRwkbGeometryType eGType,
                                            char ** papszOptions )
 {
diff --git a/ogr/ogrsf_frmts/gft/ogrgftdriver.cpp b/ogr/ogrsf_frmts/gft/ogrgftdriver.cpp
index 9d0d747..9ddebb2 100644
--- a/ogr/ogrsf_frmts/gft/ogrgftdriver.cpp
+++ b/ogr/ogrsf_frmts/gft/ogrgftdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgftdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgftdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GFT Translator
  * Purpose:  Implements OGRGFTDriver.
@@ -33,7 +33,7 @@
 
 /* http://code.google.com/intl/fr/apis/fusiontables/docs/developers_reference.html */
 
-CPL_CVSID("$Id: ogrgftdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgftdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRGFT();
 
@@ -80,8 +80,7 @@ OGRDataSource *OGRGFTDriver::Open( const char * pszFilename, int bUpdate )
 /************************************************************************/
 
 OGRDataSource *OGRGFTDriver::CreateDataSource( const char * pszName,
-                                               char **papszOptions )
-
+                                               CPL_UNUSED char **papszOptions )
 {
     OGRGFTDataSource   *poDS = new OGRGFTDataSource();
 
diff --git a/ogr/ogrsf_frmts/gft/ogrgfttablelayer.cpp b/ogr/ogrsf_frmts/gft/ogrgfttablelayer.cpp
index a348989..45bc74b 100644
--- a/ogr/ogrsf_frmts/gft/ogrgfttablelayer.cpp
+++ b/ogr/ogrsf_frmts/gft/ogrgfttablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgfttablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgfttablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GFT Translator
  * Purpose:  Implements OGRGFTTableLayer class.
@@ -29,7 +29,7 @@
 
 #include "ogr_gft.h"
 
-CPL_CVSID("$Id: ogrgfttablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgfttablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         OGRGFTTableLayer()                           */
@@ -471,7 +471,7 @@ OGRFeatureDefn * OGRGFTTableLayer::GetLayerDefn()
 /*                          GetFeatureCount()                           */
 /************************************************************************/
 
-int OGRGFTTableLayer::GetFeatureCount(int bForce)
+int OGRGFTTableLayer::GetFeatureCount(CPL_UNUSED int bForce)
 {
     GetLayerDefn();
 
@@ -522,7 +522,7 @@ int OGRGFTTableLayer::GetFeatureCount(int bForce)
 /************************************************************************/
 
 OGRErr OGRGFTTableLayer::CreateField( OGRFieldDefn *poField,
-                                 int bApproxOK )
+                                      CPL_UNUSED int bApproxOK )
 {
 
     if (!poDS->IsReadWrite())
diff --git a/ogr/ogrsf_frmts/gme/ogr_gme.h b/ogr/ogrsf_frmts/gme/ogr_gme.h
index 699d17d..47e08a5 100644
--- a/ogr/ogrsf_frmts/gme/ogr_gme.h
+++ b/ogr/ogrsf_frmts/gme/ogr_gme.h
@@ -50,7 +50,7 @@ class OGRGMELayer : public OGRLayer
     OGRGMEDataSource* poDS;
 
     OGRFeatureDefn*    poFeatureDefn;
-    OGRSpatialReference *poSRS;
+    OGRSpatialReference* poSRS;
 
     int                iGeometryField;
     int                iGxIdField;
@@ -65,6 +65,7 @@ class OGRGMELayer : public OGRLayer
 
     CPLString          osWhere;
     CPLString          osSelect;
+    CPLString          osIntersects;
 
     json_object*       current_feature_page;
     json_object*       current_features_array;
@@ -93,6 +94,7 @@ class OGRGMELayer : public OGRLayer
     OGRErr             BatchRequest(const char *osMethod, std::map<int, OGRFeature *> &omnpoFeatures);
     unsigned int       GetBatchPatchSize();
     bool               CreateTableIfNotCreated();
+    static OGRPolygon  *WindPolygonCCW( OGRPolygon *poPolygon );
 
   public:
     OGRGMELayer(OGRGMEDataSource* poDS, const char* pszTableId);
@@ -112,6 +114,8 @@ class OGRGMELayer : public OGRLayer
 
     virtual int         TestCapability( const char * );
 
+    virtual void        SetSpatialFilter( OGRGeometry * );
+
     virtual OGRErr      SetAttributeFilter( const char * pszWhere );
 
     virtual OGRErr      SetIgnoredFields(const char ** papszFields );
diff --git a/ogr/ogrsf_frmts/gme/ogrgmedatasource.cpp b/ogr/ogrsf_frmts/gme/ogrgmedatasource.cpp
index 81e8692..953a798 100644
--- a/ogr/ogrsf_frmts/gme/ogrgmedatasource.cpp
+++ b/ogr/ogrsf_frmts/gme/ogrgmedatasource.cpp
@@ -241,7 +241,7 @@ int OGRGMEDataSource::Open( const char * pszFilename, int bUpdateIn)
 /************************************************************************/
 
 OGRLayer   *OGRGMEDataSource::CreateLayer( const char *pszName,
-                                           OGRSpatialReference *poSpatialRef,
+                                           CPL_UNUSED OGRSpatialReference *poSpatialRef,
                                            OGRwkbGeometryType eGType,
                                            char ** papszOptions )
 {
diff --git a/ogr/ogrsf_frmts/gme/ogrgmedriver.cpp b/ogr/ogrsf_frmts/gme/ogrgmedriver.cpp
index c9656d4..bccdeee 100644
--- a/ogr/ogrsf_frmts/gme/ogrgmedriver.cpp
+++ b/ogr/ogrsf_frmts/gme/ogrgmedriver.cpp
@@ -77,8 +77,7 @@ OGRDataSource *OGRGMEDriver::Open( const char * pszFilename, int bUpdate )
 /************************************************************************/
 
 OGRDataSource *OGRGMEDriver::CreateDataSource( const char * pszName,
-                                               char **papszOptions )
-
+                                               CPL_UNUSED char **papszOptions )
 {
     OGRGMEDataSource   *poDS = new OGRGMEDataSource();
 
diff --git a/ogr/ogrsf_frmts/gme/ogrgmejson.cpp b/ogr/ogrsf_frmts/gme/ogrgmejson.cpp
index ce5b6b3..6a8b0e5 100644
--- a/ogr/ogrsf_frmts/gme/ogrgmejson.cpp
+++ b/ogr/ogrsf_frmts/gme/ogrgmejson.cpp
@@ -302,7 +302,7 @@ json_object* OGRGMEPolygonToGeoJSON( OGRPolygon* poPolygon )
     json_object* pjoRing = NULL;
     // If the linear ring is CW re-wind it CCW
     if (poRing->isClockwise() ) {
-      poRing->reverseWindingOrder();;
+      poRing->reverseWindingOrder();
     }
 
     pjoRing = OGRGMELineCoordsToGeoJSON( poRing );
@@ -315,6 +315,9 @@ json_object* OGRGMEPolygonToGeoJSON( OGRPolygon* poPolygon )
         if (poRing == NULL)
             continue;
         // If the linear ring is CW re-wind it CCW
+        if (poRing->isClockwise() ) {
+            poRing->reverseWindingOrder();
+        }
         pjoRing = OGRGMELineCoordsToGeoJSON( poRing );
         json_object_array_add( pjoCoordinates, pjoRing );
     }
@@ -467,8 +470,8 @@ json_object* json_object_new_gme_double(double dfVal)
 
 static int json_gme_double_to_string(json_object *pjo,
                                      printbuf *pb,
-                                     int level,
-                                     int flags)
+                                     CPL_UNUSED int level,
+                                     CPL_UNUSED int flags)
 {
   char buf[128], *p, *q;
   int size;
@@ -511,7 +514,7 @@ json_object *OGRGMEParseJSON( const char* pszText )
         {
             CPLError( CE_Failure, CPLE_AppDefined,
                       "JSON parsing error: %s (at offset %d)",
-                          json_tokener_errors[jstok->err], jstok->char_offset);
+                          json_tokener_error_desc(jstok->err), jstok->char_offset);
 
             json_tokener_free(jstok);
             return NULL;
diff --git a/ogr/ogrsf_frmts/gme/ogrgmelayer.cpp b/ogr/ogrsf_frmts/gme/ogrgmelayer.cpp
index 1c91782..19c2374 100644
--- a/ogr/ogrsf_frmts/gme/ogrgmelayer.cpp
+++ b/ogr/ogrsf_frmts/gme/ogrgmelayer.cpp
@@ -54,6 +54,7 @@ OGRGMELayer::OGRGMELayer(OGRGMEDataSource* poDS,
     bCreateTablePending = false;
     osTableId = pszTableId;
     bInTransaction = false;
+    m_poFilterGeom = NULL;
 }
 
 
@@ -120,8 +121,14 @@ int OGRGMELayer::TestCapability( const char * pszCap )
         return TRUE;
     else if(EQUAL(pszCap,OLCIgnoreFields))
         return TRUE;
+    else if(EQUAL(pszCap,OLCFastSpatialFilter))
+        return TRUE;
+    else if(EQUAL(pszCap,OLCSequentialWrite))
+        return TRUE;
     else if(EQUAL(pszCap,OLCRandomWrite))
         return TRUE;
+    else if(EQUAL(pszCap,OLCDeleteFeature))
+        return TRUE;
     else if(EQUAL(pszCap,OLCTransactions))
         return TRUE;
     return FALSE;
@@ -277,6 +284,12 @@ void OGRGMELayer::GetPageOfFeatures()
         osMoreOptions += osWhere;
     }
 
+    if (!osIntersects.empty()) {
+        CPLDebug( "GME Layer", "found intersects=%s", osIntersects.c_str());
+        osMoreOptions += "&intersects=";
+        osMoreOptions += osIntersects;
+    }
+
     CPLHTTPResult *psFeaturesResult =
         poDS->MakeRequest(osRequest, osMoreOptions);
 
@@ -354,10 +367,12 @@ OGRFeature *OGRGMELayer::GetNextRawFeature()
 /*      Handle gx_id.                                                   */
 /* -------------------------------------------------------------------- */
     const char *gx_id = OGRGMEGetJSONString(properties_obj, "gx_id");
-    CPLString gmeId(gx_id);
-    omnosIdToGMEKey[++m_nFeaturesRead] = gmeId;
-    poFeature->SetFID(m_nFeaturesRead);
-    CPLDebug("GME", "Mapping ids: \"%s\" to %d", gx_id, (int)m_nFeaturesRead);
+    if (gx_id) {
+        CPLString gmeId(gx_id);
+        omnosIdToGMEKey[++m_nFeaturesRead] = gmeId;
+        poFeature->SetFID(m_nFeaturesRead);
+        CPLDebug("GME", "Mapping ids: \"%s\" to %d", gx_id, (int)m_nFeaturesRead);
+    }
 
 /* -------------------------------------------------------------------- */
 /*      Handle geometry.                                                */
@@ -472,6 +487,79 @@ OGRErr OGRGMELayer::SetIgnoredFields(const char ** papszFields )
 }
 
 /************************************************************************/
+/*                       SetSpatialFilter()                             */
+/************************************************************************/
+
+void OGRGMELayer::SetSpatialFilter( OGRGeometry *poGeomIn)
+{
+    if (poGeomIn == NULL) {
+        osIntersects.clear();
+        OGRLayer::SetSpatialFilter( poGeomIn );
+        return;
+    }
+    switch( poGeomIn->getGeometryType() )
+    {
+      case wkbPolygon:
+        WindPolygonCCW((OGRPolygon *) poGeomIn);
+      case wkbPoint:
+      case wkbLineString:
+        if( poGeomIn == NULL ) {
+          osIntersects = "";
+        }
+        else {
+            char * pszWkt;
+            poGeomIn->exportToWkt(&pszWkt);
+            char * pszEscaped = CPLEscapeString(pszWkt, -1, CPLES_URL);
+            osIntersects = CPLString(pszEscaped);
+            CPLFree(pszEscaped);
+            CPLFree(pszWkt);
+        }
+        ResetReading();
+        break;
+      default:
+        m_iGeomFieldFilter = 0;
+        if( InstallFilter( poGeomIn ) )
+            ResetReading();
+        break;
+    }
+}
+
+/************************************************************************/
+/*                          WindPolygonCCW()                            */
+/************************************************************************/
+
+OGRPolygon* OGRGMELayer::WindPolygonCCW( OGRPolygon *poPolygon )
+{
+    CPLAssert( NULL != poPolygon );
+
+    OGRLinearRing* poRing = poPolygon->getExteriorRing();
+    if (poRing == NULL) {
+        return poPolygon;
+    }
+
+    // If the linear ring is CW re-wind it CCW
+    if (poRing->isClockwise() ) {
+      poRing->reverseWindingOrder();
+    }
+
+    /* Interior rings. */
+    const int nCount = poPolygon->getNumInteriorRings();
+    for( int i = 0; i < nCount; ++i ) {
+        poRing = poPolygon->getInteriorRing( i );
+        if (poRing == NULL)
+            continue;
+        // If the linear ring is CW re-wind it CCW
+
+        if (poRing->isClockwise() ) {
+            poRing->reverseWindingOrder();
+        }
+    }
+
+    return poPolygon;
+}
+
+
+/************************************************************************/
 /*                            BatchPatch()                              */
 /************************************************************************/
 
@@ -725,7 +813,7 @@ OGRErr OGRGMELayer::DeleteFeature( long nFID )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRGMELayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
+OGRErr OGRGMELayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     CPLDebug("GME", "create field %s of type %s, pending = %d",
              poField->GetNameRef(), OGRFieldDefn::GetFieldTypeName(poField->GetType()),
diff --git a/ogr/ogrsf_frmts/gml/gmlfeature.cpp b/ogr/ogrsf_frmts/gml/gmlfeature.cpp
index dd84fc6..544f2a9 100644
--- a/ogr/ogrsf_frmts/gml/gmlfeature.cpp
+++ b/ogr/ogrsf_frmts/gml/gmlfeature.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: gmlfeature.cpp 27188 2014-04-14 23:26:49Z rouault $
+ * $Id: gmlfeature.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GML Reader
  * Purpose:  Implementation of GMLFeature.
@@ -165,8 +165,7 @@ void GMLFeature::SetPropertyDirectly( int iIndex, char *pszValue )
 /*                                Dump()                                */
 /************************************************************************/
 
-void GMLFeature::Dump( FILE * fp )
-
+void GMLFeature::Dump( CPL_UNUSED FILE * fp )
 {
     printf( "GMLFeature(%s):\n", m_poClass->GetName() );
     
diff --git a/ogr/ogrsf_frmts/gml/gmlhandler.cpp b/ogr/ogrsf_frmts/gml/gmlhandler.cpp
index db05127..13812a9 100644
--- a/ogr/ogrsf_frmts/gml/gmlhandler.cpp
+++ b/ogr/ogrsf_frmts/gml/gmlhandler.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: gmlhandler.cpp 27120 2014-04-03 20:33:49Z rouault $
+ * $Id: gmlhandler.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GML Reader
  * Purpose:  Implementation of GMLHandler class.
@@ -307,7 +307,7 @@ void XMLCALL GMLExpatHandler::startElementCbk(void *pUserData, const char *pszNa
 /************************************************************************/
 /*                            endElementCbk()                           */
 /************************************************************************/
-void XMLCALL GMLExpatHandler::endElementCbk(void *pUserData, const char* pszName )
+void XMLCALL GMLExpatHandler::endElementCbk(void *pUserData, CPL_UNUSED const char* pszName )
 
 {
     GMLExpatHandler* pThis = ((GMLExpatHandler*)pUserData);
@@ -639,7 +639,7 @@ OGRErr GMLHandler::dataHandler(const char *data, int nLen)
 /*                       startElementBoundedBy()                        */
 /************************************************************************/
 
-OGRErr GMLHandler::startElementBoundedBy(const char *pszName, int nLenName, void* attr )
+OGRErr GMLHandler::startElementBoundedBy(const char *pszName, CPL_UNUSED int nLenName, void* attr )
 {
     if ( m_nDepth == 2 && strcmp(pszName, "Envelope") == 0 )
     {
@@ -729,7 +729,9 @@ OGRErr GMLHandler::startElementGeometry(const char *pszName, int nLenName, void*
 /*                    startElementCityGMLGenericAttr()                  */
 /************************************************************************/
 
-OGRErr GMLHandler::startElementCityGMLGenericAttr(const char *pszName, int nLenName, void* attr )
+OGRErr GMLHandler::startElementCityGMLGenericAttr(const char *pszName,
+                                                  CPL_UNUSED int nLenName,
+                                                  CPL_UNUSED void* attr )
 {
     if( strcmp(pszName, "value") == 0 )
     {
@@ -1187,8 +1189,7 @@ OGRErr GMLHandler::startElementFeatureAttribute(const char *pszName, int nLenNam
 /*                         startElementTop()                            */
 /************************************************************************/
 
-OGRErr GMLHandler::startElementTop(const char *pszName, int nLenName, void* attr )
-
+OGRErr GMLHandler::startElementTop(const char *pszName, CPL_UNUSED int nLenName, void* attr )
 {
     if (strcmp(pszName, "CityModel") == 0 )
     {
@@ -1588,7 +1589,9 @@ OGRErr GMLHandler::endElementAttribute()
 /*                    startElementFeatureProperty()                     */
 /************************************************************************/
 
-OGRErr GMLHandler::startElementFeatureProperty(const char *pszName, int nLenName, void* attr )
+OGRErr GMLHandler::startElementFeatureProperty(CPL_UNUSED const char *pszName,
+                                               CPL_UNUSED int nLenName,
+                                               void* attr )
 {
     if (m_nDepth == m_nAttributeDepth + 1)
     {
diff --git a/ogr/ogrsf_frmts/gml/gmlreader.cpp b/ogr/ogrsf_frmts/gml/gmlreader.cpp
index ea8d7d7..358e825 100644
--- a/ogr/ogrsf_frmts/gml/gmlreader.cpp
+++ b/ogr/ogrsf_frmts/gml/gmlreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gmlreader.cpp 27132 2014-04-05 21:48:58Z rouault $
+ * $Id: gmlreader.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GML Reader
  * Purpose:  Implementation of GMLReader class.
@@ -100,7 +100,7 @@ IGMLReader *CreateGMLReader(int bUseExpatParserPreferably,
 
 #endif
 
-int GMLReader::m_bXercesInitialized = -1;
+OGRGMLXercesState GMLReader::m_eXercesInitState = OGRGML_XERCES_UNINITIALIZED;
 int GMLReader::m_nInstanceCount = 0;
 void *GMLReader::hMutex = NULL;
 
@@ -108,7 +108,11 @@ void *GMLReader::hMutex = NULL;
 /*                             GMLReader()                              */
 /************************************************************************/
 
-GMLReader::GMLReader(int bUseExpatParserPreferably,
+GMLReader::GMLReader(
+#ifndef HAVE_XERCES
+CPL_UNUSED
+#endif
+                     int bUseExpatParserPreferably,
                      int bInvertAxisOrderIfLatLong,
                      int bConsiderEPSGAsURN,
                      int bGetSecondaryGeometryOption)
@@ -118,10 +122,10 @@ GMLReader::GMLReader(int bUseExpatParserPreferably,
     bUseExpatReader = TRUE;
 #else
     bUseExpatReader = FALSE;
-#ifdef HAVE_EXPAT
+#  ifdef HAVE_EXPAT
     if(bUseExpatParserPreferably)
         bUseExpatReader = TRUE;
-#endif
+#  endif
 #endif
 
 #if defined(HAVE_EXPAT) && defined(HAVE_XERCES)
@@ -206,10 +210,10 @@ GMLReader::~GMLReader()
     {
     CPLMutexHolderD(&hMutex);
     --m_nInstanceCount;
-    if( m_nInstanceCount == 0 && m_bXercesInitialized > 0 )
+    if( m_nInstanceCount == 0 && m_eXercesInitState == OGRGML_XERCES_INIT_SUCCESSFUL )
     {
         XMLPlatformUtils::Terminate();
-        m_bXercesInitialized = FALSE;
+        m_eXercesInitState = OGRGML_XERCES_UNINITIALIZED;
     }
     }
 #endif
@@ -306,7 +310,7 @@ int GMLReader::SetupParserXerces()
     {
     CPLMutexHolderD(&hMutex);
     m_nInstanceCount++;
-    if( m_bXercesInitialized < 0 )
+    if( m_eXercesInitState == OGRGML_XERCES_UNINITIALIZED )
     {
         try
         {
@@ -318,12 +322,12 @@ int GMLReader::SetupParserXerces()
             CPLError( CE_Warning, CPLE_AppDefined,
                       "Exception initializing Xerces based GML reader.\n%s", 
                       tr_strdup(toCatch.getMessage()) );
-            m_bXercesInitialized = FALSE;
+            m_eXercesInitState = OGRGML_XERCES_INIT_FAILED;
             return FALSE;
         }
-        m_bXercesInitialized = TRUE;
+        m_eXercesInitState = OGRGML_XERCES_INIT_SUCCESSFUL;
     }
-    if( !m_bXercesInitialized )
+    if( m_eXercesInitState != OGRGML_XERCES_INIT_SUCCESSFUL )
         return FALSE;
     }
 
diff --git a/ogr/ogrsf_frmts/gml/gmlreader.h b/ogr/ogrsf_frmts/gml/gmlreader.h
index b131c4f..5e3b279 100644
--- a/ogr/ogrsf_frmts/gml/gmlreader.h
+++ b/ogr/ogrsf_frmts/gml/gmlreader.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gmlreader.h 27132 2014-04-05 21:48:58Z rouault $
+ * $Id: gmlreader.h 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GML Reader
  * Purpose:  Public Declarations for OGR free GML Reader code.
@@ -261,7 +261,7 @@ public:
     virtual void SetClassListLocked( int bFlag ) = 0;
 
     virtual void SetSourceFile( const char *pszFilename ) = 0;
-    virtual void SetFP( VSILFILE* fp ) { }
+    virtual void SetFP( CPL_UNUSED VSILFILE* fp ) { }
     virtual const char* GetSourceFileName() = 0;
 
     virtual int  GetClassCount() const = 0;
@@ -291,7 +291,7 @@ public:
 
     virtual int HasStoppedParsing() = 0;
 
-    virtual void  SetGlobalSRSName( const char* pszGlobalSRSName ) {}
+    virtual void  SetGlobalSRSName( CPL_UNUSED const char* pszGlobalSRSName ) {}
     virtual const char* GetGlobalSRSName() = 0;
     virtual int CanUseGlobalSRSName() = 0;
 
diff --git a/ogr/ogrsf_frmts/gml/gmlreaderp.h b/ogr/ogrsf_frmts/gml/gmlreaderp.h
index c719a47..4f5f695 100644
--- a/ogr/ogrsf_frmts/gml/gmlreaderp.h
+++ b/ogr/ogrsf_frmts/gml/gmlreaderp.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gmlreaderp.h 27120 2014-04-03 20:33:49Z rouault $
+ * $Id: gmlreaderp.h 27531 2014-07-14 20:33:03Z rouault $
  *
  * Project:  GML Reader
  * Purpose:  Private Declarations for OGR free GML Reader code.
@@ -381,10 +381,17 @@ public:
 /*                              GMLReader                               */
 /************************************************************************/
 
+typedef enum
+{
+    OGRGML_XERCES_UNINITIALIZED,
+    OGRGML_XERCES_INIT_FAILED,
+    OGRGML_XERCES_INIT_SUCCESSFUL
+} OGRGMLXercesState;
+
 class GMLReader : public IGMLReader 
 {
 private:
-    static int    m_bXercesInitialized;
+    static OGRGMLXercesState    m_eXercesInitState;
     static int    m_nInstanceCount;
     int           m_bClassListLocked;
 
diff --git a/ogr/ogrsf_frmts/gml/hugefileresolver.cpp b/ogr/ogrsf_frmts/gml/hugefileresolver.cpp
index 6f9c705..b2d124a 100644
--- a/ogr/ogrsf_frmts/gml/hugefileresolver.cpp
+++ b/ogr/ogrsf_frmts/gml/hugefileresolver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: hugefileresolver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: hugefileresolver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GML Reader
  * Purpose:  Implementation of GMLReader::HugeFileResolver() method.
@@ -47,7 +47,7 @@
 
 #include <stack>
 
-CPL_CVSID("$Id: hugefileresolver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: hugefileresolver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /****************************************************/
 /*      SQLite is absolutely required in order to   */
@@ -1057,7 +1057,7 @@ static int gmlHugeFindGmlId( const CPLXMLNode *psNode, CPLString **gmlId )
 
 static void gmlHugeFileNodeCoords( struct huge_tag *pItem,
                                    const CPLXMLNode * psNode,
-                                   CPLString **nodeSrs )
+                                   CPL_UNUSED CPLString **nodeSrs )
 {
 /* 
 / this function attempts to set coordinates for <Node> items
@@ -1461,7 +1461,7 @@ static int gmlHugeSetChild( struct huge_parent *pParent,
 }
 
 static int gmlHugeResolveEdges( struct huge_helper *helper,
-                                CPLXMLNode *psNode, sqlite3 *hDB )
+                                CPL_UNUSED CPLXMLNode *psNode, sqlite3 *hDB )
 {
 /* resolving GML <Edge> xlink:href */
     CPLString      osCommand;
diff --git a/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp b/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp
index de28acd..412c793 100644
--- a/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp
+++ b/ogr/ogrsf_frmts/gml/ogrgmldatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgmldatasource.cpp 27195 2014-04-16 11:03:12Z rouault $
+ * $Id: ogrgmldatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OGR
  * Purpose:  Implements OGRGMLDataSource class.
@@ -46,7 +46,7 @@
 
 #include <vector>
 
-CPL_CVSID("$Id: ogrgmldatasource.cpp 27195 2014-04-16 11:03:12Z rouault $");
+CPL_CVSID("$Id: ogrgmldatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static int ExtractSRSName(const char* pszXML, char* szSRSName,
                           size_t sizeof_szSRSName);
@@ -1421,8 +1421,7 @@ OGRLayer *
 OGRGMLDataSource::CreateLayer( const char * pszLayerName,
                                OGRSpatialReference *poSRS,
                                OGRwkbGeometryType eType,
-                               char ** papszOptions )
-
+                               CPL_UNUSED char ** papszOptions )
 {
 /* -------------------------------------------------------------------- */
 /*      Verify we are in update mode.                                   */
diff --git a/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp b/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp
index fd49b35..5998ecb 100644
--- a/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp
+++ b/ogr/ogrsf_frmts/gmt/ogrgmtdatasource.cpp
@@ -113,7 +113,7 @@ OGRLayer *
 OGRGmtDataSource::CreateLayer( const char * pszLayerName,
                                OGRSpatialReference *poSRS,
                                OGRwkbGeometryType eType,
-                               char ** papszOptions )
+                               CPL_UNUSED char ** papszOptions )
 
 {
 /* -------------------------------------------------------------------- */
diff --git a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp
index 68c6de9..c53b996 100644
--- a/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp
+++ b/ogr/ogrsf_frmts/gpkg/ogrgeopackagedatasource.cpp
@@ -538,7 +538,8 @@ sqlite3* OGRGeoPackageDataSource::GetDatabaseHandle()
 /*                                Create()                              */
 /************************************************************************/
 
-int OGRGeoPackageDataSource::Create( const char * pszFilename, char **papszOptions )
+int OGRGeoPackageDataSource::Create( const char * pszFilename,
+                                     CPL_UNUSED char **papszOptions )
 {
     CPLString osCommand;
     const char *pszSpatialRefSysRecord;
@@ -823,7 +824,7 @@ OGRLayer* OGRGeoPackageDataSource::CreateLayer( const char * pszLayerName,
     {
         /* Requirement 27: The z value in a gpkg_geometry_columns table row */
         /* SHALL be one of 0 (none), 1 (mandatory), or 2 (optional) */
-        int bGeometryTypeHasZ = wkb25DBit & eGType;
+        int bGeometryTypeHasZ = (wkb25DBit & eGType) != 0;
 
         /* Update gpkg_geometry_columns with the table info */
         pszSQL = sqlite3_mprintf(
diff --git a/ogr/ogrsf_frmts/gpkg/ogrgeopackagelayer.cpp b/ogr/ogrsf_frmts/gpkg/ogrgeopackagelayer.cpp
index de7a442..6886bbb 100644
--- a/ogr/ogrsf_frmts/gpkg/ogrgeopackagelayer.cpp
+++ b/ogr/ogrsf_frmts/gpkg/ogrgeopackagelayer.cpp
@@ -485,7 +485,7 @@ OGRErr OGRGeoPackageLayer::ReadTableDefinition()
             CPLError( CE_Failure, CPLE_AppDefined, "error reading gpkg_contents" );
             
         SQLResultFree(&oResultContents);
-        return err;        
+        return OGRERR_FAILURE;
     }
 
     const char *pszMinX = SQLResultGetValue(&oResultContents, 4, 0);
@@ -524,7 +524,7 @@ OGRErr OGRGeoPackageLayer::ReadTableDefinition()
     {
         CPLError( CE_Failure, CPLE_AppDefined, "%s", oResultGeomCols.pszErrMsg );
         SQLResultFree(&oResultGeomCols);
-        return err;
+        return OGRERR_FAILURE;
     }
 
     /* Use the "PRAGMA TABLE_INFO()" call to get table definition */
@@ -541,10 +541,10 @@ OGRErr OGRGeoPackageLayer::ReadTableDefinition()
             CPLError( CE_Failure, CPLE_AppDefined, "%s", oResultTable.pszErrMsg );
         else
             CPLError( CE_Failure, CPLE_AppDefined, "Cannot find table %s", m_pszTableName );
-        err = OGRERR_FAILURE;
+
         SQLResultFree(&oResultGeomCols);
         SQLResultFree(&oResultTable);
-        return err;
+        return OGRERR_FAILURE;
     }
     
     /* Populate feature definition from table description */
@@ -727,7 +727,8 @@ OGRGeoPackageLayer::~OGRGeoPackageLayer()
 /*                      CreateField()                                   */
 /************************************************************************/
 
-OGRErr OGRGeoPackageLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
+OGRErr OGRGeoPackageLayer::CreateField( OGRFieldDefn *poField,
+                                        CPL_UNUSED int bApproxOK )
 {
     if( !m_poDS->IsUpdatable() )
     {
@@ -1231,7 +1232,10 @@ OGRErr OGRGeoPackageLayer::GetExtent(OGREnvelope *psExtent, int bForce)
         if ( err != OGRERR_NONE )
             return err;
     
-        *m_poExtent = *psExtent;
+        if ( ! m_poExtent )
+            m_poExtent = new OGREnvelope( *psExtent );
+        else
+            *m_poExtent = *psExtent;
         return SaveExtent();
     }
 
diff --git a/ogr/ogrsf_frmts/gpkg/ogrgeopackageutility.cpp b/ogr/ogrsf_frmts/gpkg/ogrgeopackageutility.cpp
index 6fc9f80..94d84ac 100644
--- a/ogr/ogrsf_frmts/gpkg/ogrgeopackageutility.cpp
+++ b/ogr/ogrsf_frmts/gpkg/ogrgeopackageutility.cpp
@@ -582,7 +582,7 @@ OGRGeometry* GPkgGeometryToOGR(GByte *pabyGpkg, size_t szGpkg, OGRSpatialReferen
 }
 
 
-OGRErr GPkgEnvelopeToOGR(GByte *pabyGpkg, size_t szGpkg, OGREnvelope *poEnv)
+OGRErr GPkgEnvelopeToOGR(GByte *pabyGpkg, CPL_UNUSED size_t szGpkg, OGREnvelope *poEnv)
 {
     CPLAssert( poEnv != NULL );
     CPLAssert( pabyGpkg != NULL );
@@ -611,4 +611,4 @@ OGRErr GPkgEnvelopeToOGR(GByte *pabyGpkg, size_t szGpkg, OGREnvelope *poEnv)
     // }
     
     return OGRERR_NONE;
-}
\ No newline at end of file
+}
diff --git a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp
index 7263633..6d531b4 100644
--- a/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp
+++ b/ogr/ogrsf_frmts/gpsbabel/ogrgpsbabeldatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgpsbabeldatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgpsbabeldatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRGPSBabelDataSource class.
@@ -35,7 +35,7 @@
 
 #include <string.h>
 
-CPL_CVSID("$Id: ogrgpsbabeldatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgpsbabeldatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                      OGRGPSBabelDataSource()                         */
@@ -377,8 +377,7 @@ int OGRGPSBabelDataSource::Open( const char * pszDatasourceName, int bUpdateIn)
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRGPSBabelDataSource::TestCapability( const char * pszCap )
-
+int OGRGPSBabelDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp b/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp
index e18129b..b789a0c 100644
--- a/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp
+++ b/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgpxdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgpxdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GPX Translator
  * Purpose:  Implements OGRGPXDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "cpl_csv.h"
 
-CPL_CVSID("$Id: ogrgpxdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgpxdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define SPACE_FOR_METADATA 160
 
@@ -145,7 +145,7 @@ OGRLayer *OGRGPXDataSource::GetLayer( int iLayer )
 /************************************************************************/
 
 OGRLayer * OGRGPXDataSource::CreateLayer( const char * pszLayerName,
-                                          OGRSpatialReference *poSRS,
+                                          CPL_UNUSED OGRSpatialReference *poSRS,
                                           OGRwkbGeometryType eType,
                                           char ** papszOptions )
 
@@ -239,7 +239,7 @@ void OGRGPXDataSource::startElementValidateCbk(const char *pszName, const char *
 /*                      dataHandlerValidateCbk()                        */
 /************************************************************************/
 
-void OGRGPXDataSource::dataHandlerValidateCbk(const char *data, int nLen)
+void OGRGPXDataSource::dataHandlerValidateCbk(CPL_UNUSED const char *data, CPL_UNUSED int nLen)
 {
     nDataHandlerCounter ++;
     if (nDataHandlerCounter >= BUFSIZ)
diff --git a/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp b/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp
index eb6bf6a..3e76574 100644
--- a/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp
+++ b/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgpxlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrgpxlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GPX Translator
  * Purpose:  Implements OGRGPXLayer class.
@@ -33,7 +33,7 @@
 #include "cpl_minixml.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrgpxlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrgpxlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FLD_TRACK_FID       0
 #define FLD_TRACK_SEG_ID    1
@@ -1768,8 +1768,7 @@ OGRErr OGRGPXLayer::CreateFeature( OGRFeature *poFeature )
 /************************************************************************/
 
 
-OGRErr OGRGPXLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRGPXLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
     {
@@ -1894,7 +1893,8 @@ void OGRGPXLayer::LoadExtensionsSchema()
 /************************************************************************/
 
 
-void OGRGPXLayer::startElementLoadSchemaCbk(const char *pszName, const char **ppszAttr)
+void OGRGPXLayer::startElementLoadSchemaCbk(const char *pszName,
+                                            CPL_UNUSED const char **ppszAttr)
 {
     if (bStopParsing) return;
 
diff --git a/ogr/ogrsf_frmts/gtm/gtmtracklayer.cpp b/ogr/ogrsf_frmts/gtm/gtmtracklayer.cpp
index de4672a..ec6aa8e 100644
--- a/ogr/ogrsf_frmts/gtm/gtmtracklayer.cpp
+++ b/ogr/ogrsf_frmts/gtm/gtmtracklayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gtmtracklayer.cpp 26464 2013-09-13 21:06:03Z rouault $
+ * $Id: gtmtracklayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GTM Driver
  * Purpose:  Implementation of GTMTrackLayer class.
@@ -32,7 +32,7 @@
 
 GTMTrackLayer::GTMTrackLayer( const char* pszName,
                               OGRSpatialReference* poSRSIn,
-                              int bWriterIn,
+                              CPL_UNUSED int bWriterIn,
                               OGRGTMDataSource* poDSIn )
 {
     poCT = NULL;
diff --git a/ogr/ogrsf_frmts/gtm/gtmwaypointlayer.cpp b/ogr/ogrsf_frmts/gtm/gtmwaypointlayer.cpp
index d28058b..d696b8a 100644
--- a/ogr/ogrsf_frmts/gtm/gtmwaypointlayer.cpp
+++ b/ogr/ogrsf_frmts/gtm/gtmwaypointlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gtmwaypointlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gtmwaypointlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GTM Driver
  * Purpose:  Implementation of gtmwaypoint class.
@@ -33,7 +33,7 @@
 
 GTMWaypointLayer::GTMWaypointLayer( const char* pszName,
                                     OGRSpatialReference* poSRSIn,
-                                    int bWriterIn,
+                                    CPL_UNUSED int bWriterIn,
                                     OGRGTMDataSource* poDSIn )
 {
     poCT = NULL;
diff --git a/ogr/ogrsf_frmts/gtm/ogrgtmdatasource.cpp b/ogr/ogrsf_frmts/gtm/ogrgtmdatasource.cpp
index bad77ee..bbb3c64 100644
--- a/ogr/ogrsf_frmts/gtm/ogrgtmdatasource.cpp
+++ b/ogr/ogrsf_frmts/gtm/ogrgtmdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgtmdatasource.cpp 21684 2011-02-11 22:14:01Z warmerdam $
+ * $Id: ogrgtmdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GTM Driver
  * Purpose:  Implementation of OGRGTMDataSource class.
@@ -324,7 +324,7 @@ int OGRGTMDataSource::Open(const char* pszFilename, int bUpdate)
 /*                               Create()                               */
 /************************************************************************/
 
-int OGRGTMDataSource::Create( const char* pszFilename, char** papszOptions )
+int OGRGTMDataSource::Create( const char* pszFilename, CPL_UNUSED char** papszOptions )
 {
     CPLAssert( NULL != pszFilename );
 
@@ -453,8 +453,7 @@ OGRLayer* OGRGTMDataSource::GetLayer( int iLayer )
 OGRLayer * OGRGTMDataSource::CreateLayer( const char * pszLayerName,
                                           OGRSpatialReference *poSRS,
                                           OGRwkbGeometryType eType,
-                                          char ** papszOptions )
-
+                                          CPL_UNUSED char ** papszOptions )
 {
     if (eType == wkbPoint || eType == wkbPoint25D)
     {
diff --git a/ogr/ogrsf_frmts/gtm/ogrgtmlayer.cpp b/ogr/ogrsf_frmts/gtm/ogrgtmlayer.cpp
index 950fe6f..726bde7 100644
--- a/ogr/ogrsf_frmts/gtm/ogrgtmlayer.cpp
+++ b/ogr/ogrsf_frmts/gtm/ogrgtmlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrgtmlayer.cpp 17588 2009-08-27 20:52:33Z rouault $
+ * $Id: ogrgtmlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  GTM Driver
  * Purpose:  Implementation of OGRGTMLayer class.
@@ -132,7 +132,7 @@ OGRErr OGRGTMLayer::CheckAndFixCoordinatesValidity( double& pdfLatitude, double&
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRGTMLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
+OGRErr OGRGTMLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 
 {
     for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
diff --git a/ogr/ogrsf_frmts/htf/ogrhtfdatasource.cpp b/ogr/ogrsf_frmts/htf/ogrhtfdatasource.cpp
index 38b2de8..959e201 100644
--- a/ogr/ogrsf_frmts/htf/ogrhtfdatasource.cpp
+++ b/ogr/ogrsf_frmts/htf/ogrhtfdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrhtfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrhtfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  HTF Translator
  * Purpose:  Implements OGRHTFDataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrhtfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrhtfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRHTFDataSource()                          */
@@ -66,8 +66,7 @@ OGRHTFDataSource::~OGRHTFDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRHTFDataSource::TestCapability( const char * pszCap )
-
+int OGRHTFDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/htf/ogrhtfdriver.cpp b/ogr/ogrsf_frmts/htf/ogrhtfdriver.cpp
index 0f2de65..877856f 100644
--- a/ogr/ogrsf_frmts/htf/ogrhtfdriver.cpp
+++ b/ogr/ogrsf_frmts/htf/ogrhtfdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrhtfdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrhtfdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  HTF Translator
  * Purpose:  Implements OGRHTFDriver.
@@ -30,7 +30,7 @@
 #include "ogr_htf.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrhtfdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrhtfdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRHTF();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGRHTFDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRHTFDriver::TestCapability( const char * pszCap )
-
+int OGRHTFDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/idrisi/generate_test_files.c b/ogr/ogrsf_frmts/idrisi/generate_test_files.c
index a7b4288..1f4ad26 100644
--- a/ogr/ogrsf_frmts/idrisi/generate_test_files.c
+++ b/ogr/ogrsf_frmts/idrisi/generate_test_files.c
@@ -129,7 +129,7 @@ int main(int argc, char* argv[])
     f = fopen("polygons.vct", "wb");
     c = 0x03;
     fwrite(&c, 1, 1, f);
-    nfeatures = 1;
+    nfeatures = 2;
     fwrite(&nfeatures, 1, sizeof(int), f);
     for(i=5;i<0x105;i++)
     {
@@ -154,6 +154,10 @@ int main(int argc, char* argv[])
 
     nodes = 5;
     fwrite(&nodes, 1, sizeof(int), f);
+
+    nodes = 5;
+    fwrite(&nodes, 1, sizeof(int), f);
+
     x = 400000;
     y = 4000000;
     fwrite(&x, 1, sizeof(double), f);
@@ -175,9 +179,6 @@ int main(int argc, char* argv[])
     fwrite(&x, 1, sizeof(double), f);
     fwrite(&y, 1, sizeof(double), f);
 
-
-    nodes = 5;
-    fwrite(&nodes, 1, sizeof(int), f);
     x = 450000;
     y = 4250000;
     fwrite(&x, 1, sizeof(double), f);
@@ -199,6 +200,48 @@ int main(int argc, char* argv[])
     fwrite(&x, 1, sizeof(double), f);
     fwrite(&y, 1, sizeof(double), f);
 
+
+    
+    id = 2;
+    minx = 400000;
+    miny = 4000000;
+    maxx = 600000;
+    maxy = 5000000;
+    fwrite(&id, 1, sizeof(double), f);
+    fwrite(&minx, 1, sizeof(double), f);
+    fwrite(&miny, 1, sizeof(double), f);
+    fwrite(&maxx, 1, sizeof(double), f);
+    fwrite(&maxy, 1, sizeof(double), f);
+    nparts = 1;
+    fwrite(&nparts, 1, sizeof(int), f);
+    nodes = 5;
+    fwrite(&nodes, 1, sizeof(int), f);
+
+    nodes = 5;
+    fwrite(&nodes, 1, sizeof(int), f);
+
+    x = 400000;
+    y = 4000000;
+    fwrite(&x, 1, sizeof(double), f);
+    fwrite(&y, 1, sizeof(double), f);
+    x = 400000;
+    y = 5000000;
+    fwrite(&x, 1, sizeof(double), f);
+    fwrite(&y, 1, sizeof(double), f);
+    x = 600000;
+    y = 5000000;
+    fwrite(&x, 1, sizeof(double), f);
+    fwrite(&y, 1, sizeof(double), f);
+    x = 600000;
+    y = 4000000;
+    fwrite(&x, 1, sizeof(double), f);
+    fwrite(&y, 1, sizeof(double), f);
+    x = 400000;
+    y = 4000000;
+    fwrite(&x, 1, sizeof(double), f);
+    fwrite(&y, 1, sizeof(double), f);
+
+
     fclose(f);
 
     return 0;
diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp
index d709518..74f2015 100644
--- a/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp
+++ b/ogr/ogrsf_frmts/idrisi/ogridrisidatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogridrisidatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogridrisidatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  Idrisi Translator
  * Purpose:  Implements OGRIdrisiDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "idrisi.h"
 
-CPL_CVSID("$Id: ogridrisidatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogridrisidatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRIdrisiDataSource()                         */
@@ -65,8 +65,7 @@ OGRIdrisiDataSource::~OGRIdrisiDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRIdrisiDataSource::TestCapability( const char * pszCap )
-
+int OGRIdrisiDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp
index 25f6774..c1ed5e5 100644
--- a/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp
+++ b/ogr/ogrsf_frmts/idrisi/ogridrisidriver.cpp
@@ -30,7 +30,7 @@
 #include "ogr_idrisi.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogridrisidriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogridrisidriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 // g++ ogr/ogrsf_frmts/idrisi/*.cpp -Wall -g -fPIC -shared -o ogr_Idrisi.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts/idrisi -Iogr/ogrsf_frmts -Ifrmts/idrisi
 
@@ -77,8 +77,7 @@ OGRDataSource *OGRIdrisiDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRIdrisiDriver::TestCapability( const char * pszCap )
-
+int OGRIdrisiDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp b/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp
index 5aebc90..f2afdb5 100644
--- a/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp
+++ b/ogr/ogrsf_frmts/idrisi/ogridrisilayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogridrisilayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogridrisilayer.cpp 27500 2014-07-06 15:01:51Z rouault $
  *
  * Project:  Idrisi Translator
  * Purpose:  Implements OGRIdrisiLayer class.
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ogridrisilayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogridrisilayer.cpp 27500 2014-07-06 15:01:51Z rouault $");
 
 /************************************************************************/
 /*                         OGRIdrisiLayer()                             */
@@ -461,17 +461,7 @@ OGRFeature *OGRIdrisiLayer::GetNextRawFeature()
                  dfMaxYShape < m_sFilterEnvelope.MinY ||
                  dfMinYShape > m_sFilterEnvelope.MaxY))
             {
-                unsigned int iPart;
-                for(iPart = 0; iPart < nParts; iPart ++)
-                {
-                    unsigned int nNodes;
-                    if (VSIFReadL(&nNodes, sizeof(unsigned int), 1, fp) != 1)
-                        return NULL;
-                    CPL_LSBPTR32(&nNodes);
-                    if (nNodes > nTotalNodes)
-                        return NULL;
-                    VSIFSeekL(fp, sizeof(OGRRawPoint) * nNodes, SEEK_CUR);
-                }
+                VSIFSeekL(fp, sizeof(unsigned int) * nParts + sizeof(OGRRawPoint) * nTotalNodes, SEEK_CUR);
                 nNextFID ++;
                 continue;
             }
@@ -481,24 +471,49 @@ OGRFeature *OGRIdrisiLayer::GetNextRawFeature()
             {
                 return NULL;
             }
-
-            unsigned int iPart;
-            OGRPolygon* poGeom = new OGRPolygon();
-            for(iPart = 0; iPart < nParts; iPart ++)
+            unsigned int* panNodesCount = NULL;
+            if( nParts > 1 )
+            {
+                panNodesCount = (unsigned int *)CPLMalloc(sizeof(unsigned int) * nParts);
+                if (VSIFReadL(panNodesCount, sizeof(unsigned int) * nParts, 1, fp) != 1)
+                {
+                    VSIFree(poRawPoints);
+                    VSIFree(panNodesCount);
+                    return NULL;
+                }
+#if defined(CPL_MSB)
+                for(unsigned int iPart=0; iPart < nParts; iPart ++)
+                {
+                    CPL_LSBPTR32(&panNodesCount[iPart]);
+                }
+#endif
+            }
+            else
             {
                 unsigned int nNodes;
-                if (VSIFReadL(&nNodes, sizeof(unsigned int), 1, fp) != 1)
+                if (VSIFReadL(&nNodes, sizeof(unsigned int) * nParts, 1, fp) != 1)
                 {
                     VSIFree(poRawPoints);
-                    delete poGeom;
                     return NULL;
                 }
                 CPL_LSBPTR32(&nNodes);
+                if( nNodes != nTotalNodes )
+                {
+                    VSIFree(poRawPoints);
+                    return NULL;
+                }
+            }
 
+            unsigned int iPart;
+            OGRPolygon* poGeom = new OGRPolygon();
+            for(iPart = 0; iPart < nParts; iPart ++)
+            {
+                unsigned int nNodes = (nParts > 1) ? panNodesCount[iPart] : nTotalNodes;
                 if (nNodes > nTotalNodes ||
                     (unsigned int)VSIFReadL(poRawPoints, sizeof(OGRRawPoint), nNodes, fp) != nNodes)
                 {
                     VSIFree(poRawPoints);
+                    VSIFree(panNodesCount);
                     delete poGeom;
                     return NULL;
                 }
@@ -517,6 +532,7 @@ OGRFeature *OGRIdrisiLayer::GetNextRawFeature()
             }
 
             VSIFree(poRawPoints);
+            VSIFree(panNodesCount);
 
             if (poSRS)
                 poGeom->assignSpatialReference(poSRS);
diff --git a/ogr/ogrsf_frmts/kml/kml.cpp b/ogr/ogrsf_frmts/kml/kml.cpp
index a7fe63e..73d77dc 100644
--- a/ogr/ogrsf_frmts/kml/kml.cpp
+++ b/ogr/ogrsf_frmts/kml/kml.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: kml.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: kml.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  KML Driver
  * Purpose:  Class for reading, parsing and handling a kmlfile.
@@ -319,7 +319,9 @@ void XMLCALL KML::startElementValidate(void* pUserData, const char* pszName, con
     }
 }
 
-void XMLCALL KML::dataHandlerValidate(void * pUserData, const char * pszData, int nLen)
+void XMLCALL KML::dataHandlerValidate(void * pUserData,
+                                      CPL_UNUSED const char * pszData,
+                                      CPL_UNUSED int nLen)
 {
     KML* poKML = (KML*) pUserData;
 
@@ -533,32 +535,32 @@ bool KML::isHandled(std::string const& elem) const
     return false;
 }
 
-bool KML::isLeaf(std::string const& elem) const
+bool KML::isLeaf(CPL_UNUSED std::string const& elem) const
 {
     return false;
 };
 
-bool KML::isFeature(std::string const& elem) const
+bool KML::isFeature(CPL_UNUSED std::string const& elem) const
 {
     return false;
 };
 
-bool KML::isFeatureContainer(std::string const& elem) const
+bool KML::isFeatureContainer(CPL_UNUSED std::string const& elem) const
 {
     return false;
 };
 
-bool KML::isContainer(std::string const& elem) const
+bool KML::isContainer(CPL_UNUSED std::string const& elem) const
 {
     return false;
 };
 
-bool KML::isRest(std::string const& elem) const
+bool KML::isRest(CPL_UNUSED std::string const& elem) const
 {
     return false;
 };
 
-void KML::findLayers(KMLNode* poNode, int bKeepEmptyContainers)
+void KML::findLayers(CPL_UNUSED KMLNode* poNode, CPL_UNUSED int bKeepEmptyContainers)
 {
     // idle
 };
diff --git a/ogr/ogrsf_frmts/kml/ogrkmldatasource.cpp b/ogr/ogrsf_frmts/kml/ogrkmldatasource.cpp
index f0cc250..4310db3 100644
--- a/ogr/ogrsf_frmts/kml/ogrkmldatasource.cpp
+++ b/ogr/ogrsf_frmts/kml/ogrkmldatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrkmldatasource.cpp 27051 2014-03-19 12:27:33Z rouault $
+ * $Id: ogrkmldatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  KML Driver
  * Purpose:  Implementation of OGRKMLDataSource class.
@@ -342,7 +342,7 @@ OGRLayer *
 OGRKMLDataSource::CreateLayer( const char * pszLayerName,
                                OGRSpatialReference *poSRS,
                                OGRwkbGeometryType eType,
-                               char ** papszOptions )
+                               CPL_UNUSED char ** papszOptions )
 {
     CPLAssert( NULL != pszLayerName);
 
diff --git a/ogr/ogrsf_frmts/kml/ogrkmllayer.cpp b/ogr/ogrsf_frmts/kml/ogrkmllayer.cpp
index 348152b..ea4a607 100644
--- a/ogr/ogrsf_frmts/kml/ogrkmllayer.cpp
+++ b/ogr/ogrsf_frmts/kml/ogrkmllayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrkmllayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrkmllayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  KML Driver
  * Purpose:  Implementation of OGRKMLLayer class.
@@ -599,7 +599,7 @@ int OGRKMLLayer::TestCapability( const char * pszCap )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRKMLLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
+OGRErr OGRKMLLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     if( !bWriter_ || iNextKMLId_ != 0 )
         return OGRERR_FAILURE;
diff --git a/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp b/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp
index 5c83d55..d18e138 100644
--- a/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp
+++ b/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmemdatasource.cpp 26302 2013-08-11 16:24:14Z rouault $
+ * $Id: ogrmemdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRMemDataSource class.
@@ -31,15 +31,14 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrmemdatasource.cpp 26302 2013-08-11 16:24:14Z rouault $");
+CPL_CVSID("$Id: ogrmemdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRMemDataSource()                          */
 /************************************************************************/
 
 OGRMemDataSource::OGRMemDataSource( const char *pszFilename, 
-                                    char **papszOptions)
-
+                                    CPL_UNUSED char **papszOptions)
 {
     pszName = CPLStrdup(pszFilename);
     papoLayers = NULL;
@@ -67,10 +66,9 @@ OGRMemDataSource::~OGRMemDataSource()
 
 OGRLayer *
 OGRMemDataSource::CreateLayer( const char * pszLayerName,
-                                 OGRSpatialReference *poSRS,
-                                 OGRwkbGeometryType eType,
-                                 char ** papszOptions )
-
+                               OGRSpatialReference *poSRS,
+                               OGRwkbGeometryType eType,
+                               CPL_UNUSED char ** papszOptions )
 {
 /* -------------------------------------------------------------------- */
 /*      Create the layer object.                                        */
diff --git a/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp b/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp
index 84c4960..35e86dc 100644
--- a/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp
+++ b/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmemdriver.cpp 10645 2007-01-18 02:22:39Z warmerdam $
+ * $Id: ogrmemdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRMemDriver class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrmemdriver.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
+CPL_CVSID("$Id: ogrmemdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          ~OGRMemDriver()                           */
@@ -56,8 +56,7 @@ const char *OGRMemDriver::GetName()
 /*                                Open()                                */
 /************************************************************************/
 
-OGRDataSource *OGRMemDriver::Open( const char * pszFilename, int )
-
+OGRDataSource *OGRMemDriver::Open( CPL_UNUSED const char * pszFilename, int )
 {
     return NULL;
 }
diff --git a/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp b/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp
index d0b9313..da7290b 100644
--- a/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp
+++ b/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmemlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrmemlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRMemLayer class.
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrmemlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrmemlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRMemLayer()                             */
@@ -343,8 +343,7 @@ int OGRMemLayer::TestCapability( const char * pszCap )
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRMemLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRMemLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     if (!bUpdatable)
         return OGRERR_FAILURE;
@@ -567,8 +566,7 @@ OGRErr OGRMemLayer::AlterFieldDefn( int iField, OGRFieldDefn* poNewFieldDefn, in
 /************************************************************************/
 
 OGRErr OGRMemLayer::CreateGeomField( OGRGeomFieldDefn *poGeomField,
-                                     int bApproxOK )
-
+                                     CPL_UNUSED int bApproxOK )
 {
     if (!bUpdatable)
         return OGRERR_FAILURE;
diff --git a/ogr/ogrsf_frmts/mitab/mitab.h b/ogr/ogrsf_frmts/mitab/mitab.h
index 1e035be..02cd107 100644
--- a/ogr/ogrsf_frmts/mitab/mitab.h
+++ b/ogr/ogrsf_frmts/mitab/mitab.h
@@ -182,7 +182,7 @@ class IMapInfoFile : public OGRLayer
                      GBool bTestOpenNoError = FALSE ) = 0;
     virtual int Close() = 0;
 
-    virtual int SetQuickSpatialIndexMode(GBool bQuickSpatialIndexMode=TRUE) {return -1;}
+    virtual int SetQuickSpatialIndexMode(CPL_UNUSED GBool bQuickSpatialIndexMode=TRUE) {return -1;}
 
     virtual const char *GetTableName() = 0;
 
@@ -592,30 +592,31 @@ class TABSeamless: public IMapInfoFile
     ///////////////
     // Write access specific stuff
     //
-    virtual int SetBounds(double dXMin, double dYMin, 
-                          double dXMax, double dYMax)   {return -1;}
-    virtual int SetFeatureDefn(OGRFeatureDefn *poFeatureDefn,
-                               TABFieldType *paeMapInfoNativeFieldTypes=NULL)
+    virtual int SetBounds(CPL_UNUSED double dXMin, CPL_UNUSED double dYMin, 
+                          CPL_UNUSED double dXMax, CPL_UNUSED double dYMax)   {return -1;}
+    virtual int SetFeatureDefn(CPL_UNUSED OGRFeatureDefn *poFeatureDefn,
+                               CPL_UNUSED TABFieldType *paeMapInfoNativeFieldTypes=NULL)
                                                         {return -1;}
-    virtual int AddFieldNative(const char *pszName,
-                               TABFieldType eMapInfoType,
-                               int nWidth=0, int nPrecision=0,
-                               GBool bIndexed=FALSE, 
-                               GBool bUnique=FALSE, 
-                               int bApproxOK = TRUE)     {return -1;}
+    virtual int AddFieldNative(CPL_UNUSED const char *pszName,
+                               CPL_UNUSED TABFieldType eMapInfoType,
+                               CPL_UNUSED int nWidth=0,
+                               CPL_UNUSED int nPrecision=0,
+                               CPL_UNUSED GBool bIndexed=FALSE, 
+                               CPL_UNUSED GBool bUnique=FALSE, 
+                               CPL_UNUSED int bApproxOK = TRUE)     {return -1;}
 
-    virtual int SetSpatialRef(OGRSpatialReference *poSpatialRef) {return -1;}
+    virtual int SetSpatialRef(CPL_UNUSED OGRSpatialReference *poSpatialRef) {return -1;}
 
-    virtual OGRErr CreateFeature(TABFeature *poFeature) 
+    virtual OGRErr CreateFeature(CPL_UNUSED TABFeature *poFeature) 
                                         {return OGRERR_UNSUPPORTED_OPERATION;}
 
-    virtual int SetFieldIndexed(int nFieldId)   {return -1;}
+    virtual int SetFieldIndexed(CPL_UNUSED int nFieldId)   {return -1;}
 
     ///////////////
     // semi-private.
     virtual int  GetProjInfo(TABProjInfo *poPI)
             { return m_poIndexTable?m_poIndexTable->GetProjInfo(poPI):-1; }
-    virtual int  SetProjInfo(TABProjInfo *poPI)         { return -1; }
+    virtual int  SetProjInfo(CPL_UNUSED TABProjInfo *poPI)         { return -1; }
     virtual int  SetMIFCoordSys(const char * /*pszMIFCoordSys*/) {return -1;};
 
 #ifdef DEBUG
@@ -1074,7 +1075,7 @@ class TABFeature: public OGRFeature
     virtual TABFeature     *CloneTABFeature(OGRFeatureDefn *pNewDefn = NULL);
     virtual TABFeatureClass GetFeatureClass() { return TABFCNoGeomFeature; };
     virtual int             GetMapInfoType()  { return m_nMapInfoType; };
-    virtual int             ValidateMapInfoType(TABMAPFile *poMapFile = NULL)
+    virtual int             ValidateMapInfoType(CPL_UNUSED TABMAPFile *poMapFile = NULL)
                                                 {m_nMapInfoType=TAB_GEOM_NONE;
                                                  return m_nMapInfoType;};
     GBool       IsRecordDeleted() { return m_bDeletedFlag; };
diff --git a/ogr/ogrsf_frmts/mitab/mitab_bounds.cpp b/ogr/ogrsf_frmts/mitab/mitab_bounds.cpp
index f66ef0b..d50b1f0 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_bounds.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_bounds.cpp
@@ -69,6 +69,8 @@
  * bounds lookups
  *----------------------------------------------------------------*/
 static MapInfoBoundsInfo **gpapsExtBoundsList = NULL;
+
+/* TODO: Clean up the initializers! */
 static MapInfoBoundsInfo gasBoundsList[] = {
 {{1, 0xff, 0xff, {0,0,0,0,0,0}, 0,0,0,0, {0,0,0,0,0}}, -1000, -1000, 1000, 1000},  /* Lat/Lon */
 
diff --git a/ogr/ogrsf_frmts/mitab/mitab_feature_mif.cpp b/ogr/ogrsf_frmts/mitab/mitab_feature_mif.cpp
index f5ae46b..d916887 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_feature_mif.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_feature_mif.cpp
@@ -1083,6 +1083,8 @@ int TABRegion::ReadGeometryFromMIFFile(MIDDATAFile *fp)
                 papszToken = NULL;
             }   
         }
+        
+        poRing->closeRings();
 
         tabPolygons[iSection]->addRingDirectly(poRing);
 
@@ -2402,7 +2404,7 @@ int TABDebugFeature::ReadGeometryFromMIFFile(MIDDATAFile *fp)
 /**********************************************************************
  *
  **********************************************************************/
-int TABDebugFeature::WriteGeometryToMIFFile(MIDDATAFile *fp){ return -1; }
+int TABDebugFeature::WriteGeometryToMIFFile(CPL_UNUSED MIDDATAFile *fp){ return -1; }
 
 
 
diff --git a/ogr/ogrsf_frmts/mitab/mitab_mapindexblock.cpp b/ogr/ogrsf_frmts/mitab/mitab_mapindexblock.cpp
index 77d3eb3..7fcace7 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_mapindexblock.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_mapindexblock.cpp
@@ -1429,7 +1429,7 @@ void TABMAPIndexBlock::RecomputeMBR()
  **********************************************************************/
 void TABMAPIndexBlock::UpdateCurChildMBR(GInt32 nXMin, GInt32 nYMin,
                                          GInt32 nXMax, GInt32 nYMax,
-                                         GInt32 nBlockPtr)
+                                         CPL_UNUSED GInt32 nBlockPtr)
 {
     CPLAssert(m_poCurChild);
     CPLAssert(m_asEntries[m_nCurChildIndex].nBlockPtr == nBlockPtr);
diff --git a/ogr/ogrsf_frmts/mitab/mitab_miffile.cpp b/ogr/ogrsf_frmts/mitab/mitab_miffile.cpp
index 4891400..4fddea8 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_miffile.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_miffile.cpp
@@ -1099,13 +1099,8 @@ int MIFFile::WriteMIFHeader()
         switch(m_paeFieldType[iField])
         {
           case TABFInteger:
-            if (poFieldDefn->GetWidth() == 0)
-                m_poMIFFile->WriteLine("  %s Integer\n",
-                                   poFieldDefn->GetNameRef());
-            else
-                m_poMIFFile->WriteLine("  %s Integer(%d)\n",
-                                   poFieldDefn->GetNameRef(),
-                                   poFieldDefn->GetWidth());
+            m_poMIFFile->WriteLine("  %s Integer\n",
+                                poFieldDefn->GetNameRef());
             break;
           case TABFSmallInt:
             m_poMIFFile->WriteLine("  %s SmallInt\n",
@@ -1773,7 +1768,7 @@ int MIFFile::AddFieldNative(const char *pszName, TABFieldType eMapInfoType,
      *----------------------------------------------------------------*/
     if (eMapInfoType == TABFDecimal && nWidth == 0)
         nWidth=20;
-    else if (nWidth == 0)
+    else if (eMapInfoType == TABFChar && nWidth == 0)
         nWidth=254; /* char fields */
 
     /*-----------------------------------------------------------------
@@ -2255,9 +2250,6 @@ int MIFFile::TestCapability( const char * pszCap )
     else if( EQUAL(pszCap,OLCSequentialWrite) )
         return TRUE;
 
-    else if( EQUAL(pszCap,OLCSequentialWrite) )
-        return FALSE;
-
     else if( EQUAL(pszCap,OLCFastFeatureCount) )
         return m_bPreParsed;
 
@@ -2267,6 +2259,9 @@ int MIFFile::TestCapability( const char * pszCap )
     else if( EQUAL(pszCap,OLCFastGetExtent) )
         return m_bPreParsed;
 
+    else if( EQUAL(pszCap,OLCCreateField) ) 
+        return TRUE; 
+
     else 
         return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp b/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp
index 8dddd66..859b7b8 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_tabfile.cpp
@@ -1580,8 +1580,7 @@ OGRErr TABFile::CreateFeature(TABFeature *poFeature)
  * Implementation of OGRLayer's SetFeature(), enabled only for
  * random write access   
  **********************************************************************/
-OGRErr TABFile::SetFeature( OGRFeature *poFeature )
-
+OGRErr TABFile::SetFeature( CPL_UNUSED OGRFeature *poFeature )
 {
 //TODO: See CreateFeature()
 // Need to convert OGRFeature to TABFeature, extract FID and then forward
@@ -2242,7 +2241,7 @@ int TABFile::GetBounds(double &dXMin, double &dYMin,
  *
  * Returns OGRERR_NONE/OGRRERR_FAILURE.
  **********************************************************************/
-OGRErr TABFile::GetExtent (OGREnvelope *psExtent, int bForce)
+OGRErr TABFile::GetExtent (OGREnvelope *psExtent, CPL_UNUSED int bForce)
 {
     TABMAPHeaderBlock *poHeader;
 
diff --git a/ogr/ogrsf_frmts/mitab/mitab_tabseamless.cpp b/ogr/ogrsf_frmts/mitab/mitab_tabseamless.cpp
index e4eb5a3..e0bd312 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_tabseamless.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_tabseamless.cpp
@@ -799,9 +799,9 @@ OGRErr TABSeamless::GetExtent (OGREnvelope *psExtent, int bForce)
  * Returns 0 on success, or silently returns -1 (with no error) if this
  * information is not available.
  **********************************************************************/
-int TABSeamless::GetFeatureCountByType(int &numPoints, int &numLines,
-                                   int &numRegions, int &numTexts,
-                                   GBool bForce /*= TRUE*/)
+int TABSeamless::GetFeatureCountByType(CPL_UNUSED int &numPoints, CPL_UNUSED int &numLines,
+                                       CPL_UNUSED int &numRegions, CPL_UNUSED int &numTexts,
+                                       CPL_UNUSED GBool bForce /*= TRUE*/)
 {
     /*-----------------------------------------------------------------
      * __TODO__  This should be implemented to return -1 if force=false,
diff --git a/ogr/ogrsf_frmts/mitab/mitab_tabview.cpp b/ogr/ogrsf_frmts/mitab/mitab_tabview.cpp
index a8ce2f7..4cbcd45 100644
--- a/ogr/ogrsf_frmts/mitab/mitab_tabview.cpp
+++ b/ogr/ogrsf_frmts/mitab/mitab_tabview.cpp
@@ -967,7 +967,7 @@ OGRFeatureDefn *TABView::GetLayerDefn()
  * properly, so this function can be used only with an empty feature defn.
  **********************************************************************/
 int TABView::SetFeatureDefn(OGRFeatureDefn *poFeatureDefn,
-                         TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
+                            CPL_UNUSED TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
 {
     if (m_poRelation)
         return m_poRelation->SetFeatureDefn(poFeatureDefn);
@@ -2088,7 +2088,7 @@ int TABRelation::WriteFeature(TABFeature *poFeature, int nFeatureId /*=-1*/)
  * Returns 0 on success, -1 on error.
  **********************************************************************/
 int TABRelation::SetFeatureDefn(OGRFeatureDefn *poFeatureDefn,
-                         TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
+                                CPL_UNUSED TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */)
 {
     if (m_poDefn && m_poDefn->GetFieldCount() > 0)
     {
diff --git a/ogr/ogrsf_frmts/mssqlspatial/ogr_mssqlspatial.h b/ogr/ogrsf_frmts/mssqlspatial/ogr_mssqlspatial.h
index b6473c2..d4756b5 100644
--- a/ogr/ogrsf_frmts/mssqlspatial/ogr_mssqlspatial.h
+++ b/ogr/ogrsf_frmts/mssqlspatial/ogr_mssqlspatial.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_mssqlspatial.h 26395 2013-09-03 11:49:23Z tamas $
+ * $Id: ogr_mssqlspatial.h 27344 2014-05-15 21:13:54Z tamas $
  *
  * Project:  MSSQL Spatial driver
  * Purpose:  Definition of classes for OGR MSSQL Spatial driver.
@@ -329,6 +329,7 @@ class OGRMSSQLSpatialDataSource : public OGRDataSource
     const char          *GetName() { return pszName; }
     int                 GetLayerCount();
     OGRLayer            *GetLayer( int );
+    OGRLayer            *GetLayerByName( const char* pszLayerName );
 
     int                 GetGeometryFormat() { return nGeometryFormat; }
     int                 UseGeometryColumns() { return bUseGeometryColumns; }
diff --git a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialdatasource.cpp b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialdatasource.cpp
index fa960a1..3358c4f 100644
--- a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialdatasource.cpp
+++ b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialdatasource.cpp
@@ -1,191 +1,124 @@
-/******************************************************************************
- * $Id: ogrmssqlspatialdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
- *
- * Project:  MSSQL Spatial driver
- * Purpose:  Implements OGRMSSQLSpatialDataSource class..
- * Author:   Tamas Szekeres, szekerest at gmail.com
- *
- ******************************************************************************
- * Copyright (c) 2010, Tamas Szekeres
+/******************************************************************************
+ * $Id: ogrmssqlspatialdatasource.cpp 27344 2014-05-15 21:13:54Z tamas $
+ *
+ * Project:  MSSQL Spatial driver
+ * Purpose:  Implements OGRMSSQLSpatialDataSource class..
+ * Author:   Tamas Szekeres, szekerest at gmail.com
+ *
+ ******************************************************************************
+ * Copyright (c) 2010, Tamas Szekeres
  * Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- ****************************************************************************/
-
-#include "ogr_mssqlspatial.h"
-
-CPL_CVSID("$Id: ogrmssqlspatialdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
-
-/************************************************************************/
-/*                          OGRMSSQLSpatialDataSource()                 */
-/************************************************************************/
-
-OGRMSSQLSpatialDataSource::OGRMSSQLSpatialDataSource()
-
-{
-    pszName = NULL;
-    pszCatalog = NULL;
-    papoLayers = NULL;
-    nLayers = 0;
-
-    nKnownSRID = 0;
-    panSRID = NULL;
-    papoSRS = NULL;
-
-    nGeometryFormat = MSSQLGEOMETRY_NATIVE;
-
-    bUseGeometryColumns = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_USE_GEOMETRY_COLUMNS", "YES"));
-    bListAllTables = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_LIST_ALL_TABLES", "NO"));
-}
-
-/************************************************************************/
-/*                         ~OGRMSSQLSpatialDataSource()                 */
-/************************************************************************/
-
-OGRMSSQLSpatialDataSource::~OGRMSSQLSpatialDataSource()
-
-{
-    int         i;
-
-    CPLFree( pszName );
-    CPLFree( pszCatalog );
-
-    for( i = 0; i < nLayers; i++ )
-        delete papoLayers[i];
-    
-    CPLFree( papoLayers );
-
-    for( i = 0; i < nKnownSRID; i++ )
-    {
-        if( papoSRS[i] != NULL )
-            papoSRS[i]->Release();
-    }
-    CPLFree( panSRID );
-    CPLFree( papoSRS );
-}
-
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ ****************************************************************************/
+
+#include "ogr_mssqlspatial.h"
+
+CPL_CVSID("$Id: ogrmssqlspatialdatasource.cpp 27344 2014-05-15 21:13:54Z tamas $");
+
+/************************************************************************/
+/*                          OGRMSSQLSpatialDataSource()                 */
+/************************************************************************/
+
+OGRMSSQLSpatialDataSource::OGRMSSQLSpatialDataSource()
+
+{
+    pszName = NULL;
+    pszCatalog = NULL;
+    papoLayers = NULL;
+    nLayers = 0;
+
+    nKnownSRID = 0;
+    panSRID = NULL;
+    papoSRS = NULL;
+
+    nGeometryFormat = MSSQLGEOMETRY_NATIVE;
+
+    bUseGeometryColumns = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_USE_GEOMETRY_COLUMNS", "YES"));
+    bListAllTables = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_LIST_ALL_TABLES", "NO"));
+}
+
+/************************************************************************/
+/*                         ~OGRMSSQLSpatialDataSource()                 */
+/************************************************************************/
+
+OGRMSSQLSpatialDataSource::~OGRMSSQLSpatialDataSource()
+
+{
+    int         i;
+
+    CPLFree( pszName );
+    CPLFree( pszCatalog );
+
+    for( i = 0; i < nLayers; i++ )
+        delete papoLayers[i];
+    
+    CPLFree( papoLayers );
+
+    for( i = 0; i < nKnownSRID; i++ )
+    {
+        if( papoSRS[i] != NULL )
+            papoSRS[i]->Release();
+    }
+    CPLFree( panSRID );
+    CPLFree( papoSRS );
+}
+
+/************************************************************************/
+/*                           TestCapability()                           */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::TestCapability( const char * pszCap )
+
+{
+    if( EQUAL(pszCap,ODsCCreateLayer) || EQUAL(pszCap,ODsCDeleteLayer) )
+        return TRUE;
+    else
+        return FALSE;
+}
+
+/************************************************************************/
+/*                              GetLayer()                              */
+/************************************************************************/
+
+OGRLayer *OGRMSSQLSpatialDataSource::GetLayer( int iLayer )
+
+{
+    if( iLayer < 0 || iLayer >= nLayers )
+        return NULL;
+    else
+        return papoLayers[iLayer];
+}
+
 /************************************************************************/
-/*                           TestCapability()                           */
+/*                           GetLayerByName()                           */
 /************************************************************************/
 
-int OGRMSSQLSpatialDataSource::TestCapability( const char * pszCap )
+OGRLayer *OGRMSSQLSpatialDataSource::GetLayerByName( const char* pszLayerName )
 
 {
-    if( EQUAL(pszCap,ODsCCreateLayer) || EQUAL(pszCap,ODsCDeleteLayer) )
-        return TRUE;
-    else
-        return FALSE;
-}
-
-/************************************************************************/
-/*                              GetLayer()                              */
-/************************************************************************/
-
-OGRLayer *OGRMSSQLSpatialDataSource::GetLayer( int iLayer )
-
-{
-    if( iLayer < 0 || iLayer >= nLayers )
+    if (!pszLayerName)
         return NULL;
-    else
-        return papoLayers[iLayer];
-}
-
-/************************************************************************/
-/*                            DeleteLayer()                             */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::DeleteLayer( int iLayer )
-
-{
-    if( iLayer < 0 || iLayer >= nLayers )
-        return OGRERR_FAILURE;
-
-/* -------------------------------------------------------------------- */
-/*      Blow away our OGR structures related to the layer.  This is     */
-/*      pretty dangerous if anything has a reference to this layer!     */
-/* -------------------------------------------------------------------- */
-    const char* pszLayerName = papoLayers[iLayer]->GetTableName();
-    const char* pszSchemaName = papoLayers[iLayer]->GetSchemaName();
-
-    CPLODBCStatement oStmt( &oSession );
-    if (bUseGeometryColumns)
-        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' AND f_table_name = '%s'\n", 
-            pszSchemaName, pszLayerName );
-    oStmt.Appendf("DROP TABLE [%s].[%s]", pszSchemaName, pszLayerName );
-
-    CPLDebug( "MSSQLSpatial", "DeleteLayer(%s)", pszLayerName );
-
-    delete papoLayers[iLayer];
-    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
-             sizeof(void *) * (nLayers - iLayer - 1) );
-    nLayers--;
-
-    if ( strlen(pszLayerName) == 0 )
-        return OGRERR_NONE;
-
-/* -------------------------------------------------------------------- */
-/*      Remove from the database.                                       */
-/* -------------------------------------------------------------------- */
-
-    oSession.BeginTransaction();
     
-    if( !oStmt.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                    "Error deleting layer: %s", GetSession()->GetLastError() );
-
-        return OGRERR_FAILURE;
-    }
+    char *pszTableName = NULL;
+    char *pszSchemaName = NULL;
 
-    oSession.CommitTransaction();
-
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                            CreateLayer()                             */
-/************************************************************************/
-
-OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
-                                          OGRSpatialReference *poSRS,
-                                          OGRwkbGeometryType eType,
-                                          char ** papszOptions )
-
-{
-    char                *pszTableName = NULL;
-    char                *pszSchemaName = NULL;
-    const char          *pszGeomType = NULL;
-    const char          *pszGeomColumn = NULL;
-    int                 nCoordDimension = 3;
-
-    /* determine the dimension */
-    if( eType == wkbFlatten(eType) )
-        nCoordDimension = 2;
-
-    if( CSLFetchNameValue( papszOptions, "DIM") != NULL )
-        nCoordDimension = atoi(CSLFetchNameValue( papszOptions, "DIM"));
-        
-    /* MSSQL Schema handling:
-       Extract schema name from input layer name or passed with -lco SCHEMA.
-       Set layer name to "schema.table" or to "table" if schema is not
-       specified
-    */
     const char* pszDotPos = strstr(pszLayerName,".");
     if ( pszDotPos != NULL )
     {
@@ -193,1036 +126,1156 @@ OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
       pszSchemaName = (char*)CPLMalloc(length+1);
       strncpy(pszSchemaName, pszLayerName, length);
       pszSchemaName[length] = '\0';
-      
-      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
-          pszTableName = LaunderName( pszDotPos + 1 ); //skip "."
-      else
-          pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
+      pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
     }
     else
     {
-      pszSchemaName = NULL;
-      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
-          pszTableName = LaunderName( pszLayerName ); //skip "."
-      else
-          pszTableName = CPLStrdup( pszLayerName ); //skip "."
-    }
-
-    if( CSLFetchNameValue( papszOptions, "SCHEMA" ) != NULL )
-    {
-        CPLFree(pszSchemaName);
-        pszSchemaName = CPLStrdup(CSLFetchNameValue( papszOptions, "SCHEMA" ));
+      pszSchemaName = CPLStrdup("dbo");
+      pszTableName = CPLStrdup( pszLayerName );
     }
-
-    if (pszSchemaName == NULL)
-        pszSchemaName = CPLStrdup("dbo");
-
-/* -------------------------------------------------------------------- */
-/*      Do we already have this layer?  If so, should we blow it        */
-/*      away?                                                           */
-/* -------------------------------------------------------------------- */
-    int iLayer;
-
-    for( iLayer = 0; iLayer < nLayers; iLayer++ )
-    {
-        if( EQUAL(pszLayerName,papoLayers[iLayer]->GetTableName()) )
-        {
-            if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
-                && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
-            {
-                if (!pszSchemaName)
-                    pszSchemaName = CPLStrdup(papoLayers[iLayer]->GetSchemaName());
-
-                DeleteLayer( iLayer );
-            }
-            else
-            {
-                CPLError( CE_Failure, CPLE_AppDefined, 
-                          "Layer %s already exists, CreateLayer failed.\n"
-                          "Use the layer creation option OVERWRITE=YES to "
-                          "replace it.",
-                          pszLayerName );
-
-                CPLFree( pszSchemaName );
-                CPLFree( pszTableName );
-                return NULL;
-            }
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Handle the GEOM_TYPE option.                                    */
-/* -------------------------------------------------------------------- */
-    if ( eType != wkbNone )
+    
+    for( int iLayer = 0; iLayer < nLayers; iLayer++ )
     {
-        pszGeomType = CSLFetchNameValue( papszOptions, "GEOM_TYPE" );
-
-        if( !pszGeomType )
-            pszGeomType = "geometry";
-        
-        if( !EQUAL(pszGeomType, "geometry")
-            && !EQUAL(pszGeomType, "geography"))
+        if( EQUAL(pszTableName,papoLayers[iLayer]->GetTableName()) && 
+            EQUAL(pszSchemaName,papoLayers[iLayer]->GetSchemaName()) )
         {
-            CPLError( CE_Failure, CPLE_AppDefined, 
-                      "FORMAT=%s not recognised or supported.", 
-                      pszGeomType );
-
             CPLFree( pszSchemaName );
             CPLFree( pszTableName );
-            return NULL;
+            return papoLayers[iLayer];
         }
-
-        /* determine the geometry column name */
-        pszGeomColumn =  CSLFetchNameValue( papszOptions, "GEOM_NAME");
-        if (!pszGeomColumn)
-            pszGeomColumn = "ogr_geometry";
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Initialize the metadata tables                                  */
-/* -------------------------------------------------------------------- */
-
-    if (InitializeMetadataTables() != OGRERR_NONE)
-    {
-        CPLFree( pszSchemaName );
-        CPLFree( pszTableName );
-        return NULL;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Try to get the SRS Id of this spatial reference system,         */
-/*      adding to the srs table if needed.                              */
-/* -------------------------------------------------------------------- */
-    int nSRSId = 0;
-
-    if( CSLFetchNameValue( papszOptions, "SRID") != NULL )
-        nSRSId = atoi(CSLFetchNameValue( papszOptions, "SRID"));
-
-    if( nSRSId == 0 && poSRS != NULL )
-        nSRSId = FetchSRSId( poSRS );
-
-/* -------------------------------------------------------------------- */
-/*      Create a new table and create a new entry in the geometry,      */
-/*      geometry_columns metadata table.                                */
-/* -------------------------------------------------------------------- */
-
-    CPLODBCStatement oStmt( &oSession );
-
-    if( eType != wkbNone && bUseGeometryColumns)
-    {
-        const char *pszGeometryType = OGRToOGCGeomType(eType);
-      
-        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' "
-            "AND f_table_name = '%s'\n", pszSchemaName, pszTableName );
-    
-        oStmt.Appendf("INSERT INTO [geometry_columns] ([f_table_catalog], [f_table_schema] ,[f_table_name], "
-            "[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES ('%s', '%s', '%s', '%s', %d, %d, '%s')\n", 
-            pszCatalog, pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszGeometryType );
-    }
-
-    if( eType == wkbNone ) 
-    { 
-        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL"
-            "CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
-            pszSchemaName, pszTableName, pszTableName);
-    }
-    else
-    {
-        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL, "
-            "[%s] [%s] NULL, CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
-            pszSchemaName, pszTableName, pszGeomColumn, pszGeomType, pszTableName);
-    }
-    oSession.BeginTransaction();
-        
-    if( !oStmt.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                    "Error creating layer: %s", GetSession()->GetLastError() );
-
-        return NULL;
-    }
-
-    oSession.CommitTransaction();
-
-/* -------------------------------------------------------------------- */
-/*      Create the layer object.                                        */
-/* -------------------------------------------------------------------- */
-    OGRMSSQLSpatialTableLayer   *poLayer;
-
-    poLayer = new OGRMSSQLSpatialTableLayer( this );
-
-    poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) );
-    poLayer->SetPrecisionFlag( CSLFetchBoolean(papszOptions,"PRECISION",TRUE));
-
-    char *pszWKT = NULL;
-    if( poSRS && poSRS->exportToWkt( &pszWKT ) != OGRERR_NONE )
-    {
-        CPLFree(pszWKT);
-        pszWKT = NULL;
-    }
-    
-    if (poLayer->Initialize(pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszWKT, eType) == OGRERR_FAILURE)
-    {
-        CPLFree( pszSchemaName );
-        CPLFree( pszTableName );
-        CPLFree( pszWKT );
-        return NULL;
     }
 
     CPLFree( pszSchemaName );
     CPLFree( pszTableName );
-    CPLFree( pszWKT );
-
-/* -------------------------------------------------------------------- */
-/*      Add layer to data source layer list.                            */
-/* -------------------------------------------------------------------- */
-    papoLayers = (OGRMSSQLSpatialTableLayer **)
-        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
-
-    papoLayers[nLayers++] = poLayer;
-
-
-    return poLayer;
-}
-
-/************************************************************************/
-/*                             OpenTable()                              */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::OpenTable( const char *pszSchemaName, const char *pszTableName, 
-                    const char *pszGeomCol, int nCoordDimension,
-                    int nSRID, const char *pszSRText, OGRwkbGeometryType eType, int bUpdate )
-
-{
-/* -------------------------------------------------------------------- */
-/*      Create the layer object.                                        */
-/* -------------------------------------------------------------------- */
-    OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
-
-    if( poLayer->Initialize( pszSchemaName, pszTableName, pszGeomCol, nCoordDimension, nSRID, pszSRText, eType ) )
-    {
-        delete poLayer;
-        return FALSE;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Add layer to data source layer list.                            */
-/* -------------------------------------------------------------------- */
-    papoLayers = (OGRMSSQLSpatialTableLayer **)
-        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
-    papoLayers[nLayers++] = poLayer;
-    
-    return TRUE;
-}
-
-
-/************************************************************************/
-/*                       GetLayerCount()                                */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::GetLayerCount() 
-{ 
-    return nLayers; 
-}
-
-/************************************************************************/
-/*                       ParseValue()                                   */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::ParseValue(char** pszValue, char* pszSource, const char* pszKey, int nStart, int nNext, int nTerm, int bRemove)
-{
-    int nLen = strlen(pszKey);
-    if ((*pszValue) == NULL && nStart + nLen < nNext && 
-            EQUALN(pszSource + nStart, pszKey, nLen))
-    {
-        *pszValue = (char*)CPLMalloc( sizeof(char) * (nNext - nStart - nLen + 1) );
-        if (*pszValue)
-            strncpy(*pszValue, pszSource + nStart + nLen, nNext - nStart - nLen);
-        (*pszValue)[nNext - nStart - nLen] = 0;
-
-        if (bRemove)
-        {
-            // remove the value from the source string
-            if (pszSource[nNext] == ';')
-                memmove( pszSource + nStart, pszSource + nNext + 1, nTerm - nNext);
-            else
-                memmove( pszSource + nStart, pszSource + nNext, nTerm - nNext + 1);
-        }
-        return TRUE;
-    }
-    return FALSE;
-}
-
-
-/************************************************************************/
-/*                                Open()                                */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::Open( const char * pszNewName, int bUpdate,
-                             int bTestOpen )
-
-{
-    CPLAssert( nLayers == 0 );
-
-    if( !EQUALN(pszNewName,"MSSQL:",6) )
-    {
-        if( !bTestOpen )
-            CPLError( CE_Failure, CPLE_AppDefined,
-                      "%s does not conform to MSSSQLSpatial naming convention,"
-                      " MSSQL:*\n", pszNewName );
-        return FALSE;
-    }
-
-    /* Determine if the connection string contains specific values */
-    char* pszTableSpec = NULL;
-    char* pszGeometryFormat = NULL;
-    char* pszConnectionName = CPLStrdup(pszNewName + 6);
-    char* pszDriver = NULL;
-    int nCurrent, nNext, nTerm;
-    nCurrent = nNext = nTerm = strlen(pszConnectionName);
-
-    while (nCurrent > 0)
-    {
-        --nCurrent;
-        if (pszConnectionName[nCurrent] == ';')
-        {
-            nNext = nCurrent;
-            continue;
-        }
-
-        if (ParseValue(&pszCatalog, pszConnectionName, "database=", 
-            nCurrent, nNext, nTerm, FALSE))
-            continue;
-
-        if (ParseValue(&pszTableSpec, pszConnectionName, "tables=", 
-            nCurrent, nNext, nTerm, TRUE))
-            continue;
-
-        if (ParseValue(&pszDriver, pszConnectionName, "driver=", 
-            nCurrent, nNext, nTerm, FALSE))
-            continue;
-
-        if (ParseValue(&pszGeometryFormat, pszConnectionName, 
-            "geometryformat=", nCurrent, nNext, nTerm, TRUE))
-        {
-            if (EQUALN(pszGeometryFormat,"wkbzm",5))
-                nGeometryFormat = MSSQLGEOMETRY_WKBZM;
-            else if (EQUALN(pszGeometryFormat, "wkb",3))
-                nGeometryFormat = MSSQLGEOMETRY_WKB;
-            else if (EQUALN(pszGeometryFormat,"wkt",3))
-                nGeometryFormat = MSSQLGEOMETRY_WKT;
-            else if (EQUALN(pszGeometryFormat,"native",6))
-                nGeometryFormat = MSSQLGEOMETRY_NATIVE;
-            else
-            {
-                CPLError( CE_Failure, CPLE_AppDefined,
-                    "Invalid geometry type specified: %s,"
-                      " MSSQL:*\n", pszGeometryFormat );
-                
-                CPLFree(pszTableSpec);
-                CPLFree(pszGeometryFormat);
-                CPLFree(pszConnectionName);
-                CPLFree(pszDriver);
-                return FALSE;
-            }
-
-            CPLFree(pszGeometryFormat);
-            pszGeometryFormat = NULL;
-            continue;
-        }
-    }
-
-    /* Determine if the connection string contains the catalog portion */
-    if( pszCatalog == NULL )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                      "'%s' does not contain the 'database' portion\n", pszNewName );
-        
-        CPLFree(pszTableSpec);
-        CPLFree(pszGeometryFormat);
-        CPLFree(pszConnectionName);
-        CPLFree(pszDriver);
-        return FALSE;
-    }
-    
-    pszName = CPLStrdup(pszNewName);
-
-    char  **papszTableNames=NULL;
-    char  **papszSchemaNames=NULL;
-    char  **papszGeomColumnNames=NULL;
-    char  **papszCoordDimensions=NULL;
-    char  **papszSRIds=NULL;
-    char  **papszSRTexts=NULL;
-
-    /* Determine if the connection string contains the TABLES portion */
-    if( pszTableSpec != NULL )
-    {
-        char          **papszTableList;
-        int             i;
 
-        papszTableList = CSLTokenizeString2( pszTableSpec, ",", 0 );
-
-        for( i = 0; i < CSLCount(papszTableList); i++ )
-        {
-            char      **papszQualifiedParts;
-
-            // Get schema and table name
-            papszQualifiedParts = CSLTokenizeString2( papszTableList[i],
-                                                      ".", 0 );
-
-            /* Find the geometry column name if specified */
-            if( CSLCount( papszQualifiedParts ) >= 1 )
-            {
-                char* pszGeomColumnName = NULL;
-                char* pos = strchr(papszQualifiedParts[CSLCount( papszQualifiedParts ) - 1], '(');
-                if (pos != NULL)
-                {
-                    *pos = '\0';
-                    pszGeomColumnName = pos+1;
-                    int len = strlen(pszGeomColumnName);
-                    if (len > 0)
-                        pszGeomColumnName[len - 1] = '\0';
-                }
-                papszGeomColumnNames = CSLAddString( papszGeomColumnNames,
-                        pszGeomColumnName ? pszGeomColumnName : "");
-            }
-
-            if( CSLCount( papszQualifiedParts ) == 2 )
-            {
-                papszSchemaNames = CSLAddString( papszSchemaNames, 
-                                                papszQualifiedParts[0] );
-                papszTableNames = CSLAddString( papszTableNames,
-                                                papszQualifiedParts[1] );
-            }
-            else if( CSLCount( papszQualifiedParts ) == 1 )
-            {
-                papszSchemaNames = CSLAddString( papszSchemaNames, "dbo");
-                papszTableNames = CSLAddString( papszTableNames,
-                                                papszQualifiedParts[0] );
-            }
-
-            CSLDestroy(papszQualifiedParts);
-        }
-
-        CSLDestroy(papszTableList);
-    }
-
-    CPLFree(pszTableSpec);
-
-    /* Initialize the SQL Server connection. */
-    int nResult;
-    if ( pszDriver != NULL )
-    {
-        /* driver has been specified */
-        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
-        nResult = oSession.EstablishSession( pszConnectionName, "", "" );
-    }
-    else
-    {
-        /* no driver has been specified, defautls to SQL Server */
-        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
-        nResult = oSession.EstablishSession( CPLSPrintf("DRIVER=SQL Server;%s", pszConnectionName), "", "" );
-    }
-
-    CPLFree(pszDriver);
-
-    if( !nResult )
+    return NULL;
+}
+
+/************************************************************************/
+/*                            DeleteLayer()                             */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::DeleteLayer( int iLayer )
+
+{
+    if( iLayer < 0 || iLayer >= nLayers )
+        return OGRERR_FAILURE;
+
+/* -------------------------------------------------------------------- */
+/*      Blow away our OGR structures related to the layer.  This is     */
+/*      pretty dangerous if anything has a reference to this layer!     */
+/* -------------------------------------------------------------------- */
+    const char* pszTableName = papoLayers[iLayer]->GetTableName();
+    const char* pszSchemaName = papoLayers[iLayer]->GetSchemaName();
+
+    CPLODBCStatement oStmt( &oSession );
+    if (bUseGeometryColumns)
+        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' AND f_table_name = '%s'\n", 
+            pszSchemaName, pszTableName );
+    oStmt.Appendf("DROP TABLE [%s].[%s]", pszSchemaName, pszTableName );
+
+    CPLDebug( "MSSQLSpatial", "DeleteLayer(%s)", pszTableName );
+
+    delete papoLayers[iLayer];
+    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
+             sizeof(void *) * (nLayers - iLayer - 1) );
+    nLayers--;
+
+    if ( strlen(pszTableName) == 0 )
+        return OGRERR_NONE;
+
+/* -------------------------------------------------------------------- */
+/*      Remove from the database.                                       */
+/* -------------------------------------------------------------------- */
+
+    oSession.BeginTransaction();
+    
+    if( !oStmt.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                    "Error deleting layer: %s", GetSession()->GetLastError() );
+
+        return OGRERR_FAILURE;
+    }
+
+    oSession.CommitTransaction();
+
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                            CreateLayer()                             */
+/************************************************************************/
+
+OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
+                                          OGRSpatialReference *poSRS,
+                                          OGRwkbGeometryType eType,
+                                          char ** papszOptions )
+
+{
+    char                *pszTableName = NULL;
+    char                *pszSchemaName = NULL;
+    const char          *pszGeomType = NULL;
+    const char          *pszGeomColumn = NULL;
+    int                 nCoordDimension = 3;
+
+    /* determine the dimension */
+    if( eType == wkbFlatten(eType) )
+        nCoordDimension = 2;
+
+    if( CSLFetchNameValue( papszOptions, "DIM") != NULL )
+        nCoordDimension = atoi(CSLFetchNameValue( papszOptions, "DIM"));
+        
+    /* MSSQL Schema handling:
+       Extract schema name from input layer name or passed with -lco SCHEMA.
+       Set layer name to "schema.table" or to "table" if schema is not
+       specified
+    */
+    const char* pszDotPos = strstr(pszLayerName,".");
+    if ( pszDotPos != NULL )
+    {
+      int length = pszDotPos - pszLayerName;
+      pszSchemaName = (char*)CPLMalloc(length+1);
+      strncpy(pszSchemaName, pszLayerName, length);
+      pszSchemaName[length] = '\0';
+      
+      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
+          pszTableName = LaunderName( pszDotPos + 1 ); //skip "."
+      else
+          pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
+    }
+    else
+    {
+      pszSchemaName = NULL;
+      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
+          pszTableName = LaunderName( pszLayerName ); //skip "."
+      else
+          pszTableName = CPLStrdup( pszLayerName ); //skip "."
+    }
+
+    if( CSLFetchNameValue( papszOptions, "SCHEMA" ) != NULL )
+    {
+        CPLFree(pszSchemaName);
+        pszSchemaName = CPLStrdup(CSLFetchNameValue( papszOptions, "SCHEMA" ));
+    }
+
+    if (pszSchemaName == NULL)
+        pszSchemaName = CPLStrdup("dbo");
+
+/* -------------------------------------------------------------------- */
+/*      Do we already have this layer?  If so, should we blow it        */
+/*      away?                                                           */
+/* -------------------------------------------------------------------- */
+    int iLayer;
+
+    for( iLayer = 0; iLayer < nLayers; iLayer++ )
+    {
+        if( EQUAL(pszTableName,papoLayers[iLayer]->GetTableName()) && 
+            EQUAL(pszSchemaName,papoLayers[iLayer]->GetSchemaName()) )
+        {
+            if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
+                && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
+            {
+                if (!pszSchemaName)
+                    pszSchemaName = CPLStrdup(papoLayers[iLayer]->GetSchemaName());
+
+                DeleteLayer( iLayer );
+            }
+            else
+            {
+                CPLError( CE_Failure, CPLE_AppDefined, 
+                          "Layer %s already exists, CreateLayer failed.\n"
+                          "Use the layer creation option OVERWRITE=YES to "
+                          "replace it.",
+                          pszLayerName );
+
+                CPLFree( pszSchemaName );
+                CPLFree( pszTableName );
+                return NULL;
+            }
+        }
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Handle the GEOM_TYPE option.                                    */
+/* -------------------------------------------------------------------- */
+    if ( eType != wkbNone )
+    {
+        pszGeomType = CSLFetchNameValue( papszOptions, "GEOM_TYPE" );
+
+        if( !pszGeomType )
+            pszGeomType = "geometry";
+        
+        if( !EQUAL(pszGeomType, "geometry")
+            && !EQUAL(pszGeomType, "geography"))
+        {
+            CPLError( CE_Failure, CPLE_AppDefined, 
+                      "FORMAT=%s not recognised or supported.", 
+                      pszGeomType );
+
+            CPLFree( pszSchemaName );
+            CPLFree( pszTableName );
+            return NULL;
+        }
+
+        /* determine the geometry column name */
+        pszGeomColumn =  CSLFetchNameValue( papszOptions, "GEOM_NAME");
+        if (!pszGeomColumn)
+            pszGeomColumn = "ogr_geometry";
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Initialize the metadata tables                                  */
+/* -------------------------------------------------------------------- */
+
+    if (InitializeMetadataTables() != OGRERR_NONE)
+    {
+        CPLFree( pszSchemaName );
+        CPLFree( pszTableName );
+        return NULL;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Try to get the SRS Id of this spatial reference system,         */
+/*      adding to the srs table if needed.                              */
+/* -------------------------------------------------------------------- */
+    int nSRSId = 0;
+
+    if( CSLFetchNameValue( papszOptions, "SRID") != NULL )
+        nSRSId = atoi(CSLFetchNameValue( papszOptions, "SRID"));
+
+    if( nSRSId == 0 && poSRS != NULL )
+        nSRSId = FetchSRSId( poSRS );
+
+/* -------------------------------------------------------------------- */
+/*      Create a new table and create a new entry in the geometry,      */
+/*      geometry_columns metadata table.                                */
+/* -------------------------------------------------------------------- */
+
+    CPLODBCStatement oStmt( &oSession );
+
+    if( eType != wkbNone && bUseGeometryColumns)
+    {
+        const char *pszGeometryType = OGRToOGCGeomType(eType);
+      
+        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' "
+            "AND f_table_name = '%s'\n", pszSchemaName, pszTableName );
+    
+        oStmt.Appendf("INSERT INTO [geometry_columns] ([f_table_catalog], [f_table_schema] ,[f_table_name], "
+            "[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES ('%s', '%s', '%s', '%s', %d, %d, '%s')\n", 
+            pszCatalog, pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszGeometryType );
+    }
+
+    if (!EQUAL(pszSchemaName,"dbo"))
     {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "Unable to initialize connection to the server for %s,\n"
-                  "%s", pszNewName, oSession.GetLastError() );
-        
-        CSLDestroy( papszTableNames );
-        CSLDestroy( papszSchemaNames );
-        CSLDestroy( papszGeomColumnNames );
-        CSLDestroy( papszCoordDimensions );
-        CSLDestroy( papszSRIds );
-        CSLDestroy( papszSRTexts );
-        CPLFree(pszGeometryFormat);
-        CPLFree(pszConnectionName);
-        return FALSE;
-    }
-
-    char** papszTypes = NULL;
-
-    /* if requesting all user database table then this takes priority */ 
- 	if (papszTableNames == NULL && bListAllTables) 
- 	{ 
- 	    CPLODBCStatement oStmt( &oSession ); 
- 	         
- 	    oStmt.Append( "select sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects. [...]
- 	
- 	    if( oStmt.ExecuteSQL() ) 
- 	    { 
- 	        while( oStmt.Fetch() ) 
- 	        { 
- 	            papszSchemaNames =  
- 	                    CSLAddString( papszSchemaNames, oStmt.GetColData(0) ); 
- 	            papszTableNames =  
- 	                    CSLAddString( papszTableNames, oStmt.GetColData(1) ); 
- 	            papszGeomColumnNames =  
- 	                    CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) ); 
- 	        } 
- 	    } 
- 	} 
-
-    /* Determine the available tables if not specified. */
-    if (papszTableNames == NULL && bUseGeometryColumns)
-    {
-        CPLODBCStatement oStmt( &oSession );
-        
-        /* Use join to make sure the existence of the referred column/table */
-        oStmt.Append( "SELECT f_table_schema, f_table_name, f_geometry_column, coord_dimension, g.srid, srtext, geometry_type FROM dbo.geometry_columns g JOIN INFORMATION_SCHEMA.COLUMNS ON f_table_schema = TABLE_SCHEMA and f_table_name = TABLE_NAME and f_geometry_column = COLUMN_NAME left outer join dbo.spatial_ref_sys s on g.srid = s.srid");
-
-        if( oStmt.ExecuteSQL() )
-        {
-            while( oStmt.Fetch() )
-            {
+        // creating the schema if not exists
+        oStmt.Appendf("IF NOT EXISTS (SELECT name from sys.schemas WHERE name = '%s') EXEC sp_executesql N'CREATE SCHEMA [%s]'\n", pszSchemaName, pszSchemaName);
+    }
+
+    if( eType == wkbNone ) 
+    { 
+        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL"
+            "CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
+            pszSchemaName, pszTableName, pszTableName);
+    }
+    else
+    {
+        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL, "
+            "[%s] [%s] NULL, CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
+            pszSchemaName, pszTableName, pszGeomColumn, pszGeomType, pszTableName);
+    }
+    oSession.BeginTransaction();
+        
+    if( !oStmt.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                    "Error creating layer: %s", GetSession()->GetLastError() );
+
+        return NULL;
+    }
+
+    oSession.CommitTransaction();
+
+/* -------------------------------------------------------------------- */
+/*      Create the layer object.                                        */
+/* -------------------------------------------------------------------- */
+    OGRMSSQLSpatialTableLayer   *poLayer;
+
+    poLayer = new OGRMSSQLSpatialTableLayer( this );
+
+    poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) );
+    poLayer->SetPrecisionFlag( CSLFetchBoolean(papszOptions,"PRECISION",TRUE));
+
+    char *pszWKT = NULL;
+    if( poSRS && poSRS->exportToWkt( &pszWKT ) != OGRERR_NONE )
+    {
+        CPLFree(pszWKT);
+        pszWKT = NULL;
+    }
+    
+    if (poLayer->Initialize(pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszWKT, eType) == OGRERR_FAILURE)
+    {
+        CPLFree( pszSchemaName );
+        CPLFree( pszTableName );
+        CPLFree( pszWKT );
+        return NULL;
+    }
+
+    CPLFree( pszSchemaName );
+    CPLFree( pszTableName );
+    CPLFree( pszWKT );
+
+/* -------------------------------------------------------------------- */
+/*      Add layer to data source layer list.                            */
+/* -------------------------------------------------------------------- */
+    papoLayers = (OGRMSSQLSpatialTableLayer **)
+        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
+
+    papoLayers[nLayers++] = poLayer;
+
+
+    return poLayer;
+}
+
+/************************************************************************/
+/*                             OpenTable()                              */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::OpenTable( const char *pszSchemaName, const char *pszTableName, 
+                    const char *pszGeomCol, int nCoordDimension,
+                    int nSRID, const char *pszSRText, OGRwkbGeometryType eType, int bUpdate )
+
+{
+/* -------------------------------------------------------------------- */
+/*      Create the layer object.                                        */
+/* -------------------------------------------------------------------- */
+    OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
+
+    if( poLayer->Initialize( pszSchemaName, pszTableName, pszGeomCol, nCoordDimension, nSRID, pszSRText, eType ) )
+    {
+        delete poLayer;
+        return FALSE;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Add layer to data source layer list.                            */
+/* -------------------------------------------------------------------- */
+    papoLayers = (OGRMSSQLSpatialTableLayer **)
+        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
+    papoLayers[nLayers++] = poLayer;
+    
+    return TRUE;
+}
+
+
+/************************************************************************/
+/*                       GetLayerCount()                                */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::GetLayerCount() 
+{ 
+    return nLayers; 
+}
+
+/************************************************************************/
+/*                       ParseValue()                                   */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::ParseValue(char** pszValue, char* pszSource, const char* pszKey, int nStart, int nNext, int nTerm, int bRemove)
+{
+    int nLen = strlen(pszKey);
+    if ((*pszValue) == NULL && nStart + nLen < nNext && 
+            EQUALN(pszSource + nStart, pszKey, nLen))
+    {
+        *pszValue = (char*)CPLMalloc( sizeof(char) * (nNext - nStart - nLen + 1) );
+        if (*pszValue)
+            strncpy(*pszValue, pszSource + nStart + nLen, nNext - nStart - nLen);
+        (*pszValue)[nNext - nStart - nLen] = 0;
+
+        if (bRemove)
+        {
+            // remove the value from the source string
+            if (pszSource[nNext] == ';')
+                memmove( pszSource + nStart, pszSource + nNext + 1, nTerm - nNext);
+            else
+                memmove( pszSource + nStart, pszSource + nNext, nTerm - nNext + 1);
+        }
+        return TRUE;
+    }
+    return FALSE;
+}
+
+
+/************************************************************************/
+/*                                Open()                                */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::Open( const char * pszNewName, int bUpdate,
+                             int bTestOpen )
+
+{
+    CPLAssert( nLayers == 0 );
+
+    if( !EQUALN(pszNewName,"MSSQL:",6) )
+    {
+        if( !bTestOpen )
+            CPLError( CE_Failure, CPLE_AppDefined,
+                      "%s does not conform to MSSSQLSpatial naming convention,"
+                      " MSSQL:*\n", pszNewName );
+        return FALSE;
+    }
+
+    /* Determine if the connection string contains specific values */
+    char* pszTableSpec = NULL;
+    char* pszGeometryFormat = NULL;
+    char* pszConnectionName = CPLStrdup(pszNewName + 6);
+    char* pszDriver = NULL;
+    int nCurrent, nNext, nTerm;
+    nCurrent = nNext = nTerm = strlen(pszConnectionName);
+
+    while (nCurrent > 0)
+    {
+        --nCurrent;
+        if (pszConnectionName[nCurrent] == ';')
+        {
+            nNext = nCurrent;
+            continue;
+        }
+
+        if (ParseValue(&pszCatalog, pszConnectionName, "database=", 
+            nCurrent, nNext, nTerm, FALSE))
+            continue;
+
+        if (ParseValue(&pszTableSpec, pszConnectionName, "tables=", 
+            nCurrent, nNext, nTerm, TRUE))
+            continue;
+
+        if (ParseValue(&pszDriver, pszConnectionName, "driver=", 
+            nCurrent, nNext, nTerm, FALSE))
+            continue;
+
+        if (ParseValue(&pszGeometryFormat, pszConnectionName, 
+            "geometryformat=", nCurrent, nNext, nTerm, TRUE))
+        {
+            if (EQUALN(pszGeometryFormat,"wkbzm",5))
+                nGeometryFormat = MSSQLGEOMETRY_WKBZM;
+            else if (EQUALN(pszGeometryFormat, "wkb",3))
+                nGeometryFormat = MSSQLGEOMETRY_WKB;
+            else if (EQUALN(pszGeometryFormat,"wkt",3))
+                nGeometryFormat = MSSQLGEOMETRY_WKT;
+            else if (EQUALN(pszGeometryFormat,"native",6))
+                nGeometryFormat = MSSQLGEOMETRY_NATIVE;
+            else
+            {
+                CPLError( CE_Failure, CPLE_AppDefined,
+                    "Invalid geometry type specified: %s,"
+                      " MSSQL:*\n", pszGeometryFormat );
+                
+                CPLFree(pszTableSpec);
+                CPLFree(pszGeometryFormat);
+                CPLFree(pszConnectionName);
+                CPLFree(pszDriver);
+                return FALSE;
+            }
+
+            CPLFree(pszGeometryFormat);
+            pszGeometryFormat = NULL;
+            continue;
+        }
+    }
+
+    /* Determine if the connection string contains the catalog portion */
+    if( pszCatalog == NULL )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                      "'%s' does not contain the 'database' portion\n", pszNewName );
+        
+        CPLFree(pszTableSpec);
+        CPLFree(pszGeometryFormat);
+        CPLFree(pszConnectionName);
+        CPLFree(pszDriver);
+        return FALSE;
+    }
+    
+    pszName = CPLStrdup(pszNewName);
+
+    char  **papszTableNames=NULL;
+    char  **papszSchemaNames=NULL;
+    char  **papszGeomColumnNames=NULL;
+    char  **papszCoordDimensions=NULL;
+    char  **papszSRIds=NULL;
+    char  **papszSRTexts=NULL;
+
+    /* Determine if the connection string contains the TABLES portion */
+    if( pszTableSpec != NULL )
+    {
+        char          **papszTableList;
+        int             i;
+
+        papszTableList = CSLTokenizeString2( pszTableSpec, ",", 0 );
+
+        for( i = 0; i < CSLCount(papszTableList); i++ )
+        {
+            char      **papszQualifiedParts;
+
+            // Get schema and table name
+            papszQualifiedParts = CSLTokenizeString2( papszTableList[i],
+                                                      ".", 0 );
+
+            /* Find the geometry column name if specified */
+            if( CSLCount( papszQualifiedParts ) >= 1 )
+            {
+                char* pszGeomColumnName = NULL;
+                char* pos = strchr(papszQualifiedParts[CSLCount( papszQualifiedParts ) - 1], '(');
+                if (pos != NULL)
+                {
+                    *pos = '\0';
+                    pszGeomColumnName = pos+1;
+                    int len = strlen(pszGeomColumnName);
+                    if (len > 0)
+                        pszGeomColumnName[len - 1] = '\0';
+                }
+                papszGeomColumnNames = CSLAddString( papszGeomColumnNames,
+                        pszGeomColumnName ? pszGeomColumnName : "");
+            }
+
+            if( CSLCount( papszQualifiedParts ) == 2 )
+            {
+                papszSchemaNames = CSLAddString( papszSchemaNames, 
+                                                papszQualifiedParts[0] );
+                papszTableNames = CSLAddString( papszTableNames,
+                                                papszQualifiedParts[1] );
+            }
+            else if( CSLCount( papszQualifiedParts ) == 1 )
+            {
+                papszSchemaNames = CSLAddString( papszSchemaNames, "dbo");
+                papszTableNames = CSLAddString( papszTableNames,
+                                                papszQualifiedParts[0] );
+            }
+
+            CSLDestroy(papszQualifiedParts);
+        }
+
+        CSLDestroy(papszTableList);
+    }
+
+    CPLFree(pszTableSpec);
+
+    /* Initialize the SQL Server connection. */
+    int nResult;
+    if ( pszDriver != NULL )
+    {
+        /* driver has been specified */
+        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
+        nResult = oSession.EstablishSession( pszConnectionName, "", "" );
+    }
+    else
+    {
+        /* no driver has been specified, defautls to SQL Server */
+        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
+        nResult = oSession.EstablishSession( CPLSPrintf("DRIVER=SQL Server;%s", pszConnectionName), "", "" );
+    }
+
+    CPLFree(pszDriver);
+
+    if( !nResult )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "Unable to initialize connection to the server for %s,\n"
+                  "%s", pszNewName, oSession.GetLastError() );
+        
+        CSLDestroy( papszTableNames );
+        CSLDestroy( papszSchemaNames );
+        CSLDestroy( papszGeomColumnNames );
+        CSLDestroy( papszCoordDimensions );
+        CSLDestroy( papszSRIds );
+        CSLDestroy( papszSRTexts );
+        CPLFree(pszGeometryFormat);
+        CPLFree(pszConnectionName);
+        return FALSE;
+    }
+
+    char** papszTypes = NULL;
+
+    /* if requesting all user database table then this takes priority */ 
+ 	if (papszTableNames == NULL && bListAllTables) 
+ 	{ 
+ 	    CPLODBCStatement oStmt( &oSession ); 
+ 	         
+ 	    oStmt.Append( "select sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects. [...]
+ 	
+ 	    if( oStmt.ExecuteSQL() ) 
+ 	    { 
+ 	        while( oStmt.Fetch() ) 
+ 	        { 
+ 	            papszSchemaNames =  
+ 	                    CSLAddString( papszSchemaNames, oStmt.GetColData(0) ); 
+ 	            papszTableNames =  
+ 	                    CSLAddString( papszTableNames, oStmt.GetColData(1) ); 
+ 	            papszGeomColumnNames =  
+ 	                    CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) ); 
+ 	        } 
+ 	    } 
+ 	} 
+
+    /* Determine the available tables if not specified. */
+    if (papszTableNames == NULL && bUseGeometryColumns)
+    {
+        CPLODBCStatement oStmt( &oSession );
+        
+        /* Use join to make sure the existence of the referred column/table */
+        oStmt.Append( "SELECT f_table_schema, f_table_name, f_geometry_column, coord_dimension, g.srid, srtext, geometry_type FROM dbo.geometry_columns g JOIN INFORMATION_SCHEMA.COLUMNS ON f_table_schema = TABLE_SCHEMA and f_table_name = TABLE_NAME and f_geometry_column = COLUMN_NAME left outer join dbo.spatial_ref_sys s on g.srid = s.srid");
+
+        if( oStmt.ExecuteSQL() )
+        {
+            while( oStmt.Fetch() )
+            {
                 papszSchemaNames = 
-                        CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
+                        CSLAddString( papszSchemaNames, oStmt.GetColData(0, "dbo") );
                 papszTableNames = 
                         CSLAddString( papszTableNames, oStmt.GetColData(1) );
                 papszGeomColumnNames = 
                         CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
                 papszCoordDimensions = 
-                        CSLAddString( papszCoordDimensions, oStmt.GetColData(3) );
+                        CSLAddString( papszCoordDimensions, oStmt.GetColData(3, "2") );
                 papszSRIds = 
-                        CSLAddString( papszSRIds, oStmt.GetColData(4) );
+                        CSLAddString( papszSRIds, oStmt.GetColData(4, "0") );
                 papszSRTexts = 
-                        CSLAddString( papszSRTexts, oStmt.GetColData(5) );
+                    CSLAddString( papszSRTexts, oStmt.GetColData(5, "") );
                 papszTypes = 
-                        CSLAddString( papszTypes, oStmt.GetColData(6) );
-            }
-        }
-        else
-        {
-            /* probably the table is missing at all */
-            InitializeMetadataTables();
-        }
-    }
-
-    /* Query catalog for tables having geometry columns */
-    if (papszTableNames == NULL)
-    {
-        CPLODBCStatement oStmt( &oSession );
-            
-        oStmt.Append( "SELECT sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.object [...]
-
-        if( oStmt.ExecuteSQL() )
-        {
-            while( oStmt.Fetch() )
-            {
-                papszSchemaNames = 
-                        CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
-                papszTableNames = 
-                        CSLAddString( papszTableNames, oStmt.GetColData(1) );
-                papszGeomColumnNames = 
-                        CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
-            }
-        }
-    }
-
-    int nSRId, nCoordDimension;
-    OGRwkbGeometryType eType;
-        
-    for( int iTable = 0; 
-         papszTableNames != NULL && papszTableNames[iTable] != NULL; 
-         iTable++ )
-    {
-        if (papszSRIds != NULL)
-            nSRId = atoi(papszSRIds[iTable]);
-        else
-            nSRId = -1;
-
-        if (papszCoordDimensions != NULL)
-            nCoordDimension = atoi(papszCoordDimensions[iTable]);
-        else
-            nCoordDimension = 2;
-
-        if (papszTypes != NULL)
-            eType = OGRFromOGCGeomType(papszTypes[iTable]);
-        else
-            eType = wkbUnknown;
-
-        if( strlen(papszGeomColumnNames[iTable]) > 0 )
-            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], papszGeomColumnNames[iTable], 
-                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, eType, bUpdate );
-        else
-            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], NULL, 
-                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, wkbNone, bUpdate );
-    }
-
-    CSLDestroy( papszTableNames );
-    CSLDestroy( papszSchemaNames );
-    CSLDestroy( papszGeomColumnNames );
-    CSLDestroy( papszCoordDimensions );
-    CSLDestroy( papszSRIds );
-    CSLDestroy( papszSRTexts );
-    CSLDestroy( papszTypes );
-
-    CPLFree(pszGeometryFormat);
-    CPLFree(pszConnectionName);
-    
-    bDSUpdate = bUpdate;
-
-    return TRUE;
-}
-
-/************************************************************************/
-/*                             ExecuteSQL()                             */
-/************************************************************************/
-
-OGRLayer * OGRMSSQLSpatialDataSource::ExecuteSQL( const char *pszSQLCommand,
-                                          OGRGeometry *poSpatialFilter,
-                                          const char *pszDialect )
-
-{
-/* -------------------------------------------------------------------- */
-/*      Use generic implementation for recognized dialects              */
-/* -------------------------------------------------------------------- */
-    if( IsGenericSQLDialect(pszDialect) )
-        return OGRDataSource::ExecuteSQL( pszSQLCommand, 
-                                          poSpatialFilter, 
-                                          pszDialect );
-
-/* -------------------------------------------------------------------- */
-/*      Special case DELLAYER: command.                                 */
-/* -------------------------------------------------------------------- */
-    if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
-    {
-        const char *pszLayerName = pszSQLCommand + 9;
-
-        while( *pszLayerName == ' ' )
-            pszLayerName++;
-        
-        for( int iLayer = 0; iLayer < nLayers; iLayer++ )
-        {
-            if( EQUAL(papoLayers[iLayer]->GetName(), 
-                      pszLayerName ))
-            {
-                DeleteLayer( iLayer );
-                break;
-            }
-        }
-        return NULL;
-    }
-
-    CPLDebug( "MSSQLSpatial", "ExecuteSQL(%s) called.", pszSQLCommand );
-
-    if( EQUALN(pszSQLCommand, "DROP SPATIAL INDEX ON ", 22) )
-    {
-        /* Handle command to drop a spatial index. */
-        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
-
-        if (poLayer)
-        {
-            if( poLayer->Initialize( "dbo", pszSQLCommand + 22, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
-            {
-                CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Failed to initialize layer '%s'", pszSQLCommand + 22 );   
-            }
-            poLayer->DropSpatialIndex();
-            delete poLayer;
-        }
-        return NULL;
-    }
-    else if( EQUALN(pszSQLCommand, "CREATE SPATIAL INDEX ON ", 24) )
-    {
-        /* Handle command to create a spatial index. */
-        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
-
-        if (poLayer)
-        {
-            if( poLayer->Initialize( "dbo", pszSQLCommand + 24, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
-            {
-                CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Failed to initialize layer '%s'", pszSQLCommand + 24 );    
-            }
-            poLayer->CreateSpatialIndex();
-            delete poLayer;
-        }
-        return NULL;
-    }
-    
-    /* Execute the command natively */
-    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );
-    poStmt->Append( pszSQLCommand );
-
-    if( !poStmt->ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "%s", oSession.GetLastError() );
-        delete poStmt;
-        return NULL;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Are there result columns for this statement?                    */
-/* -------------------------------------------------------------------- */
-    if( poStmt->GetColCount() == 0 )
-    {
-        delete poStmt;
-        CPLErrorReset();
-        return NULL;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Create a results layer.  It will take ownership of the          */
-/*      statement.                                                      */
-/* -------------------------------------------------------------------- */
-    
-    OGRMSSQLSpatialSelectLayer *poLayer = NULL;
-        
-    poLayer = new OGRMSSQLSpatialSelectLayer( this, poStmt );
-
-    if( poSpatialFilter != NULL )
-        poLayer->SetSpatialFilter( poSpatialFilter );
-
-    return poLayer;
-}
-
-/************************************************************************/
-/*                          ReleaseResultSet()                          */
-/************************************************************************/
-
-void OGRMSSQLSpatialDataSource::ReleaseResultSet( OGRLayer * poLayer )
-
-{
-    delete poLayer;
-}
-
-/************************************************************************/
-/*                            LaunderName()                             */
-/************************************************************************/
-
-char *OGRMSSQLSpatialDataSource::LaunderName( const char *pszSrcName )
-
-{
-    char    *pszSafeName = CPLStrdup( pszSrcName );
-    int     i;
-
-    for( i = 0; pszSafeName[i] != '\0'; i++ )
-    {
-        pszSafeName[i] = (char) tolower( pszSafeName[i] );
-        if( pszSafeName[i] == '-' || pszSafeName[i] == '#' )
-            pszSafeName[i] = '_';
-    }
-
-    return pszSafeName;
-}
-
-/************************************************************************/
-/*                      InitializeMetadataTables()                      */
-/*                                                                      */
-/*      Create the metadata tables (SPATIAL_REF_SYS and                 */
-/*      GEOMETRY_COLUMNS).                                              */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialDataSource::InitializeMetadataTables()
-
-{
-    if (bUseGeometryColumns)
-    {
-        CPLODBCStatement oStmt( &oSession );
-
-        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects WHERE "
-            "object_id = OBJECT_ID(N'[dbo].[geometry_columns]') AND type in (N'U')) "
-            "CREATE TABLE geometry_columns (f_table_catalog varchar(128) not null, "
-            "f_table_schema varchar(128) not null, f_table_name varchar(256) not null, "
-            "f_geometry_column varchar(256) not null, coord_dimension integer not null, "
-            "srid integer not null, geometry_type varchar(30) not null, "
-            "CONSTRAINT geometry_columns_pk PRIMARY KEY (f_table_catalog, "
-            "f_table_schema, f_table_name, f_geometry_column));\n" );
-
-        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects "
-            "WHERE object_id = OBJECT_ID(N'[dbo].[spatial_ref_sys]') AND type in (N'U')) "
-            "CREATE TABLE spatial_ref_sys (srid integer not null "
-            "PRIMARY KEY, auth_name varchar(256), auth_srid integer, srtext varchar(2048), proj4text varchar(2048))" );
-
-        oSession.BeginTransaction();
-    
-        if( !oStmt.ExecuteSQL() )
-        {
-            CPLError( CE_Failure, CPLE_AppDefined,
-                        "Error initializing the metadata tables : %s", GetSession()->GetLastError() );
-            return OGRERR_FAILURE;
-        }
-
-        oSession.CommitTransaction();
-    }
-
-    return OGRERR_NONE;
-}
-
-
-/************************************************************************/
-/*                              FetchSRS()                              */
-/*                                                                      */
-/*      Return a SRS corresponding to a particular id.  Note that       */
-/*      reference counting should be honoured on the returned           */
-/*      OGRSpatialReference, as handles may be cached.                  */
-/************************************************************************/
-
-OGRSpatialReference *OGRMSSQLSpatialDataSource::FetchSRS( int nId )
-
-{
-    if( nId <= 0 )
-        return NULL;
-
-/* -------------------------------------------------------------------- */
-/*      First, we look through our SRID cache, is it there?             */
-/* -------------------------------------------------------------------- */
-    int  i;
-
-    for( i = 0; i < nKnownSRID; i++ )
-    {
-        if( panSRID[i] == nId )
-            return papoSRS[i];
-    }
-
-    OGRSpatialReference *poSRS = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Try looking up in spatial_ref_sys table                         */
-/* -------------------------------------------------------------------- */
-    if (bUseGeometryColumns)
-    {
-        CPLODBCStatement oStmt( GetSession() );
-        oStmt.Appendf( "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId );
-
-        if( oStmt.ExecuteSQL() && oStmt.Fetch() )
-        {
-            if ( oStmt.GetColData( 0 ) )
-            {
-                poSRS = new OGRSpatialReference();
-                char* pszWKT = (char*)oStmt.GetColData( 0 );
-                if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
-                {
-                    delete poSRS;
-                    poSRS = NULL;
-                }    
-            }
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Try looking up the EPSG list                                    */
-/* -------------------------------------------------------------------- */
-    if (!poSRS)
-    {
-        poSRS = new OGRSpatialReference();
-        if( poSRS->importFromEPSG( nId ) != OGRERR_NONE )
-        {
-            delete poSRS;
-            poSRS = NULL;
-        } 
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Add to the cache.                                               */
-/* -------------------------------------------------------------------- */
-    if (poSRS)
-    {
-        panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
-        papoSRS = (OGRSpatialReference **)
-            CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
-        panSRID[nKnownSRID] = nId;
-        papoSRS[nKnownSRID] = poSRS;
-        nKnownSRID++;
-    }
-
-    return poSRS;
-}
-
-/************************************************************************/
-/*                             FetchSRSId()                             */
-/*                                                                      */
-/*      Fetch the id corresponding to an SRS, and if not found, add     */
-/*      it to the table.                                                */
-/************************************************************************/
-
-int OGRMSSQLSpatialDataSource::FetchSRSId( OGRSpatialReference * poSRS)
-
-{
-    char                *pszWKT = NULL;
-    int                 nSRSId = 0;
-    const char*         pszAuthorityName;
-
-    if( poSRS == NULL )
-        return 0;
-
-    OGRSpatialReference oSRS(*poSRS);
-    poSRS = NULL;
-
-    pszAuthorityName = oSRS.GetAuthorityName(NULL);
-
-    if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 )
-    {
-/* -------------------------------------------------------------------- */
-/*      Try to identify an EPSG code                                    */
-/* -------------------------------------------------------------------- */
-        oSRS.AutoIdentifyEPSG();
-
-        pszAuthorityName = oSRS.GetAuthorityName(NULL);
-        if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG"))
-        {
-            const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL);
-            if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 )
-            {
-                /* Import 'clean' SRS */
-                oSRS.importFromEPSG( atoi(pszAuthorityCode) );
-
-                pszAuthorityName = oSRS.GetAuthorityName(NULL);
-            }
-        }
-    }
-/* -------------------------------------------------------------------- */
-/*      Check whether the EPSG authority code is already mapped to a    */
-/*      SRS ID.                                                         */
-/* -------------------------------------------------------------------- */
-    int  nAuthorityCode = 0;
-    if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) )
-    {
-        /* For the root authority name 'EPSG', the authority code
-         * should always be integral
-         */
-        nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) );
-
-        CPLODBCStatement oStmt( &oSession );
-        oStmt.Appendf("SELECT srid FROM spatial_ref_sys WHERE "
-                         "auth_name = '%s' AND auth_srid = %d",
-                         pszAuthorityName,
-                         nAuthorityCode );
-
-        if( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
-        {
-            nSRSId = atoi(oStmt.GetColData( 0 ));
-            return nSRSId;
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Translate SRS to WKT.                                           */
-/* -------------------------------------------------------------------- */
-    if( oSRS.exportToWkt( &pszWKT ) != OGRERR_NONE )
-    {
-        CPLFree(pszWKT);
-        return 0;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Try to find in the existing table.                              */
-/* -------------------------------------------------------------------- */
-    CPLODBCStatement oStmt( &oSession );
-
-    oStmt.Append( "SELECT srid FROM spatial_ref_sys WHERE srtext = ");
-    OGRMSSQLAppendEscaped(&oStmt, pszWKT);
-
-/* -------------------------------------------------------------------- */
-/*      We got it!  Return it.                                          */
-/* -------------------------------------------------------------------- */
-    if( oStmt.ExecuteSQL() )
-    {
-        if ( oStmt.Fetch() && oStmt.GetColData( 0 ) )
-        {
-            nSRSId = atoi(oStmt.GetColData( 0 ));
-            CPLFree(pszWKT);
-            return nSRSId;
-        }
-    }
-    else
-    {
-        /* probably the table is missing at all */
-        if( InitializeMetadataTables() != OGRERR_NONE )
-        {
-            CPLFree(pszWKT);
-            return 0;
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Try adding the SRS to the SRS table.                            */
-/* -------------------------------------------------------------------- */
-    char    *pszProj4 = NULL;
-    if( oSRS.exportToProj4( &pszProj4 ) != OGRERR_NONE )
-    {
-        CPLFree( pszProj4 );
-        CPLFree(pszWKT);
-        return 0;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Check whether the auth_code can be used as srid.                */
-/* -------------------------------------------------------------------- */
-    nSRSId = nAuthorityCode;
-
-    oStmt.Clear();
-    oSession.BeginTransaction();
-    if (nAuthorityCode > 0)
-    {
-        oStmt.Appendf("SELECT srid FROM spatial_ref_sys where srid = %d", nAuthorityCode);
-        if ( oStmt.ExecuteSQL() && oStmt.Fetch())
-        {
-            nSRSId = 0;
-        }
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Get the current maximum srid in the srs table.                  */
-/* -------------------------------------------------------------------- */
-    
-    if (nSRSId == 0)
-    {
-        oStmt.Clear();
-        oStmt.Append("SELECT COALESCE(MAX(srid) + 1, 32768) FROM spatial_ref_sys where srid between 32768 and 65536");
-
-        if ( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
-        {
-            nSRSId = atoi(oStmt.GetColData( 0 ));
-        }
-    }
-
-    if (nSRSId == 0)
-    {
-        /* unable to allocate srid */
-        oSession.RollbackTransaction();
-        CPLFree( pszProj4 );
-        CPLFree(pszWKT);
-        return 0;
-    }
-    
-    oStmt.Clear();
-    if( nAuthorityCode > 0 )
-    {
-        oStmt.Appendf(
-                 "INSERT INTO spatial_ref_sys (srid, auth_srid, auth_name, srtext, proj4text) "
-                 "VALUES (%d, %d, ", nSRSId, nAuthorityCode );
-        OGRMSSQLAppendEscaped(&oStmt, pszAuthorityName);
-        oStmt.Append(", ");
-        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
-        oStmt.Append(", ");
-        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
-        oStmt.Append(")");
-    }
-    else
-    {
-        oStmt.Appendf(
-                 "INSERT INTO spatial_ref_sys (srid,srtext,proj4text) VALUES (%d, ", nSRSId);
-        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
-        oStmt.Append(", ");
-        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
-        oStmt.Append(")");
-    }
-
-    /* Free everything that was allocated. */
-    CPLFree( pszProj4 );
-    CPLFree( pszWKT);
-
-    if ( oStmt.ExecuteSQL() )
-        oSession.CommitTransaction();
-    else
-        oSession.RollbackTransaction();
-
-    return nSRSId;
-}
-
+                        CSLAddString( papszTypes, oStmt.GetColData(6, "GEOMETRY") );
+            }
+        }
+        else
+        {
+            /* probably the table is missing at all */
+            InitializeMetadataTables();
+        }
+    }
+
+    /* Query catalog for tables having geometry columns */
+    if (papszTableNames == NULL)
+    {
+        CPLODBCStatement oStmt( &oSession );
+            
+        oStmt.Append( "SELECT sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.object [...]
+
+        if( oStmt.ExecuteSQL() )
+        {
+            while( oStmt.Fetch() )
+            {
+                papszSchemaNames = 
+                        CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
+                papszTableNames = 
+                        CSLAddString( papszTableNames, oStmt.GetColData(1) );
+                papszGeomColumnNames = 
+                        CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
+            }
+        }
+    }
+
+    int nSRId, nCoordDimension;
+    OGRwkbGeometryType eType;
+        
+    for( int iTable = 0; 
+         papszTableNames != NULL && papszTableNames[iTable] != NULL; 
+         iTable++ )
+    {
+        if (papszSRIds != NULL)
+            nSRId = atoi(papszSRIds[iTable]);
+        else
+            nSRId = -1;
+
+        if (papszCoordDimensions != NULL)
+            nCoordDimension = atoi(papszCoordDimensions[iTable]);
+        else
+            nCoordDimension = 2;
+
+        if (papszTypes != NULL)
+            eType = OGRFromOGCGeomType(papszTypes[iTable]);
+        else
+            eType = wkbUnknown;
+
+        if( strlen(papszGeomColumnNames[iTable]) > 0 )
+            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], papszGeomColumnNames[iTable], 
+                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, eType, bUpdate );
+        else
+            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], NULL, 
+                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, wkbNone, bUpdate );
+    }
+
+    CSLDestroy( papszTableNames );
+    CSLDestroy( papszSchemaNames );
+    CSLDestroy( papszGeomColumnNames );
+    CSLDestroy( papszCoordDimensions );
+    CSLDestroy( papszSRIds );
+    CSLDestroy( papszSRTexts );
+    CSLDestroy( papszTypes );
+
+    CPLFree(pszGeometryFormat);
+    CPLFree(pszConnectionName);
+    
+    bDSUpdate = bUpdate;
+
+    return TRUE;
+}
+
+/************************************************************************/
+/*                             ExecuteSQL()                             */
+/************************************************************************/
+
+OGRLayer * OGRMSSQLSpatialDataSource::ExecuteSQL( const char *pszSQLCommand,
+                                          OGRGeometry *poSpatialFilter,
+                                          const char *pszDialect )
+
+{
+/* -------------------------------------------------------------------- */
+/*      Use generic implementation for recognized dialects              */
+/* -------------------------------------------------------------------- */
+    if( IsGenericSQLDialect(pszDialect) )
+        return OGRDataSource::ExecuteSQL( pszSQLCommand, 
+                                          poSpatialFilter, 
+                                          pszDialect );
+
+/* -------------------------------------------------------------------- */
+/*      Special case DELLAYER: command.                                 */
+/* -------------------------------------------------------------------- */
+    if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
+    {
+        const char *pszLayerName = pszSQLCommand + 9;
+
+        while( *pszLayerName == ' ' )
+            pszLayerName++;
+
+        OGRLayer* poLayer = GetLayerByName(pszLayerName);
+        
+        for( int iLayer = 0; iLayer < nLayers; iLayer++ )
+        {
+            if( papoLayers[iLayer] == poLayer )
+            {
+                DeleteLayer( iLayer );
+                break;
+            }
+        }
+        return NULL;
+    }
+
+    CPLDebug( "MSSQLSpatial", "ExecuteSQL(%s) called.", pszSQLCommand );
+
+    if( EQUALN(pszSQLCommand, "DROP SPATIAL INDEX ON ", 22) )
+    {
+        /* Handle command to drop a spatial index. */
+        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
+
+        if (poLayer)
+        {
+            if( poLayer->Initialize( "dbo", pszSQLCommand + 22, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
+            {
+                CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Failed to initialize layer '%s'", pszSQLCommand + 22 );   
+            }
+            poLayer->DropSpatialIndex();
+            delete poLayer;
+        }
+        return NULL;
+    }
+    else if( EQUALN(pszSQLCommand, "CREATE SPATIAL INDEX ON ", 24) )
+    {
+        /* Handle command to create a spatial index. */
+        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );
+
+        if (poLayer)
+        {
+            if( poLayer->Initialize( "dbo", pszSQLCommand + 24, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
+            {
+                CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Failed to initialize layer '%s'", pszSQLCommand + 24 );    
+            }
+            poLayer->CreateSpatialIndex();
+            delete poLayer;
+        }
+        return NULL;
+    }
+    
+    /* Execute the command natively */
+    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );
+    poStmt->Append( pszSQLCommand );
+
+    if( !poStmt->ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "%s", oSession.GetLastError() );
+        delete poStmt;
+        return NULL;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Are there result columns for this statement?                    */
+/* -------------------------------------------------------------------- */
+    if( poStmt->GetColCount() == 0 )
+    {
+        delete poStmt;
+        CPLErrorReset();
+        return NULL;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Create a results layer.  It will take ownership of the          */
+/*      statement.                                                      */
+/* -------------------------------------------------------------------- */
+    
+    OGRMSSQLSpatialSelectLayer *poLayer = NULL;
+        
+    poLayer = new OGRMSSQLSpatialSelectLayer( this, poStmt );
+
+    if( poSpatialFilter != NULL )
+        poLayer->SetSpatialFilter( poSpatialFilter );
+
+    return poLayer;
+}
+
+/************************************************************************/
+/*                          ReleaseResultSet()                          */
+/************************************************************************/
+
+void OGRMSSQLSpatialDataSource::ReleaseResultSet( OGRLayer * poLayer )
+
+{
+    delete poLayer;
+}
+
+/************************************************************************/
+/*                            LaunderName()                             */
+/************************************************************************/
+
+char *OGRMSSQLSpatialDataSource::LaunderName( const char *pszSrcName )
+
+{
+    char    *pszSafeName = CPLStrdup( pszSrcName );
+    int     i;
+
+    for( i = 0; pszSafeName[i] != '\0'; i++ )
+    {
+        pszSafeName[i] = (char) tolower( pszSafeName[i] );
+        if( pszSafeName[i] == '-' || pszSafeName[i] == '#' )
+            pszSafeName[i] = '_';
+    }
+
+    return pszSafeName;
+}
+
+/************************************************************************/
+/*                      InitializeMetadataTables()                      */
+/*                                                                      */
+/*      Create the metadata tables (SPATIAL_REF_SYS and                 */
+/*      GEOMETRY_COLUMNS).                                              */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialDataSource::InitializeMetadataTables()
+
+{
+    if (bUseGeometryColumns)
+    {
+        CPLODBCStatement oStmt( &oSession );
+
+        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects WHERE "
+            "object_id = OBJECT_ID(N'[dbo].[geometry_columns]') AND type in (N'U')) "
+            "CREATE TABLE geometry_columns (f_table_catalog varchar(128) not null, "
+            "f_table_schema varchar(128) not null, f_table_name varchar(256) not null, "
+            "f_geometry_column varchar(256) not null, coord_dimension integer not null, "
+            "srid integer not null, geometry_type varchar(30) not null, "
+            "CONSTRAINT geometry_columns_pk PRIMARY KEY (f_table_catalog, "
+            "f_table_schema, f_table_name, f_geometry_column));\n" );
+
+        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects "
+            "WHERE object_id = OBJECT_ID(N'[dbo].[spatial_ref_sys]') AND type in (N'U')) "
+            "CREATE TABLE spatial_ref_sys (srid integer not null "
+            "PRIMARY KEY, auth_name varchar(256), auth_srid integer, srtext varchar(2048), proj4text varchar(2048))" );
+
+        oSession.BeginTransaction();
+    
+        if( !oStmt.ExecuteSQL() )
+        {
+            CPLError( CE_Failure, CPLE_AppDefined,
+                        "Error initializing the metadata tables : %s", GetSession()->GetLastError() );
+            return OGRERR_FAILURE;
+        }
+
+        oSession.CommitTransaction();
+    }
+
+    return OGRERR_NONE;
+}
+
+
+/************************************************************************/
+/*                              FetchSRS()                              */
+/*                                                                      */
+/*      Return a SRS corresponding to a particular id.  Note that       */
+/*      reference counting should be honoured on the returned           */
+/*      OGRSpatialReference, as handles may be cached.                  */
+/************************************************************************/
+
+OGRSpatialReference *OGRMSSQLSpatialDataSource::FetchSRS( int nId )
+
+{
+    if( nId <= 0 )
+        return NULL;
+
+/* -------------------------------------------------------------------- */
+/*      First, we look through our SRID cache, is it there?             */
+/* -------------------------------------------------------------------- */
+    int  i;
+
+    for( i = 0; i < nKnownSRID; i++ )
+    {
+        if( panSRID[i] == nId )
+            return papoSRS[i];
+    }
+
+    OGRSpatialReference *poSRS = NULL;
+
+/* -------------------------------------------------------------------- */
+/*      Try looking up in spatial_ref_sys table                         */
+/* -------------------------------------------------------------------- */
+    if (bUseGeometryColumns)
+    {
+        CPLODBCStatement oStmt( GetSession() );
+        oStmt.Appendf( "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId );
+
+        if( oStmt.ExecuteSQL() && oStmt.Fetch() )
+        {
+            if ( oStmt.GetColData( 0 ) )
+            {
+                poSRS = new OGRSpatialReference();
+                char* pszWKT = (char*)oStmt.GetColData( 0 );
+                if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
+                {
+                    delete poSRS;
+                    poSRS = NULL;
+                }    
+            }
+        }
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Try looking up the EPSG list                                    */
+/* -------------------------------------------------------------------- */
+    if (!poSRS)
+    {
+        poSRS = new OGRSpatialReference();
+        if( poSRS->importFromEPSG( nId ) != OGRERR_NONE )
+        {
+            delete poSRS;
+            poSRS = NULL;
+        } 
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Add to the cache.                                               */
+/* -------------------------------------------------------------------- */
+    if (poSRS)
+    {
+        panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
+        papoSRS = (OGRSpatialReference **)
+            CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
+        panSRID[nKnownSRID] = nId;
+        papoSRS[nKnownSRID] = poSRS;
+        nKnownSRID++;
+    }
+
+    return poSRS;
+}
+
+/************************************************************************/
+/*                             FetchSRSId()                             */
+/*                                                                      */
+/*      Fetch the id corresponding to an SRS, and if not found, add     */
+/*      it to the table.                                                */
+/************************************************************************/
+
+int OGRMSSQLSpatialDataSource::FetchSRSId( OGRSpatialReference * poSRS)
+
+{
+    char                *pszWKT = NULL;
+    int                 nSRSId = 0;
+    const char*         pszAuthorityName;
+
+    if( poSRS == NULL )
+        return 0;
+
+    OGRSpatialReference oSRS(*poSRS);
+    poSRS = NULL;
+
+    pszAuthorityName = oSRS.GetAuthorityName(NULL);
+
+    if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 )
+    {
+/* -------------------------------------------------------------------- */
+/*      Try to identify an EPSG code                                    */
+/* -------------------------------------------------------------------- */
+        oSRS.AutoIdentifyEPSG();
+
+        pszAuthorityName = oSRS.GetAuthorityName(NULL);
+        if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG"))
+        {
+            const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL);
+            if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 )
+            {
+                /* Import 'clean' SRS */
+                oSRS.importFromEPSG( atoi(pszAuthorityCode) );
+
+                pszAuthorityName = oSRS.GetAuthorityName(NULL);
+            }
+        }
+    }
+/* -------------------------------------------------------------------- */
+/*      Check whether the EPSG authority code is already mapped to a    */
+/*      SRS ID.                                                         */
+/* -------------------------------------------------------------------- */
+    int  nAuthorityCode = 0;
+    if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) )
+    {
+        /* For the root authority name 'EPSG', the authority code
+         * should always be integral
+         */
+        nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) );
+
+        CPLODBCStatement oStmt( &oSession );
+        oStmt.Appendf("SELECT srid FROM spatial_ref_sys WHERE "
+                         "auth_name = '%s' AND auth_srid = %d",
+                         pszAuthorityName,
+                         nAuthorityCode );
+
+        if( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
+        {
+            nSRSId = atoi(oStmt.GetColData( 0 ));
+            return nSRSId;
+        }
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Translate SRS to WKT.                                           */
+/* -------------------------------------------------------------------- */
+    if( oSRS.exportToWkt( &pszWKT ) != OGRERR_NONE )
+    {
+        CPLFree(pszWKT);
+        return 0;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Try to find in the existing table.                              */
+/* -------------------------------------------------------------------- */
+    CPLODBCStatement oStmt( &oSession );
+
+    oStmt.Append( "SELECT srid FROM spatial_ref_sys WHERE srtext = ");
+    OGRMSSQLAppendEscaped(&oStmt, pszWKT);
+
+/* -------------------------------------------------------------------- */
+/*      We got it!  Return it.                                          */
+/* -------------------------------------------------------------------- */
+    if( oStmt.ExecuteSQL() )
+    {
+        if ( oStmt.Fetch() && oStmt.GetColData( 0 ) )
+        {
+            nSRSId = atoi(oStmt.GetColData( 0 ));
+            CPLFree(pszWKT);
+            return nSRSId;
+        }
+    }
+    else
+    {
+        /* probably the table is missing at all */
+        if( InitializeMetadataTables() != OGRERR_NONE )
+        {
+            CPLFree(pszWKT);
+            return 0;
+        }
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Try adding the SRS to the SRS table.                            */
+/* -------------------------------------------------------------------- */
+    char    *pszProj4 = NULL;
+    if( oSRS.exportToProj4( &pszProj4 ) != OGRERR_NONE )
+    {
+        CPLFree( pszProj4 );
+        CPLFree(pszWKT);
+        return 0;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Check whether the auth_code can be used as srid.                */
+/* -------------------------------------------------------------------- */
+    nSRSId = nAuthorityCode;
+
+    oStmt.Clear();
+    oSession.BeginTransaction();
+    if (nAuthorityCode > 0)
+    {
+        oStmt.Appendf("SELECT srid FROM spatial_ref_sys where srid = %d", nAuthorityCode);
+        if ( oStmt.ExecuteSQL() && oStmt.Fetch())
+        {
+            nSRSId = 0;
+        }
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Get the current maximum srid in the srs table.                  */
+/* -------------------------------------------------------------------- */
+    
+    if (nSRSId == 0)
+    {
+        oStmt.Clear();
+        oStmt.Append("SELECT COALESCE(MAX(srid) + 1, 32768) FROM spatial_ref_sys where srid between 32768 and 65536");
+
+        if ( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
+        {
+            nSRSId = atoi(oStmt.GetColData( 0 ));
+        }
+    }
+
+    if (nSRSId == 0)
+    {
+        /* unable to allocate srid */
+        oSession.RollbackTransaction();
+        CPLFree( pszProj4 );
+        CPLFree(pszWKT);
+        return 0;
+    }
+    
+    oStmt.Clear();
+    if( nAuthorityCode > 0 )
+    {
+        oStmt.Appendf(
+                 "INSERT INTO spatial_ref_sys (srid, auth_srid, auth_name, srtext, proj4text) "
+                 "VALUES (%d, %d, ", nSRSId, nAuthorityCode );
+        OGRMSSQLAppendEscaped(&oStmt, pszAuthorityName);
+        oStmt.Append(", ");
+        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
+        oStmt.Append(", ");
+        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
+        oStmt.Append(")");
+    }
+    else
+    {
+        oStmt.Appendf(
+                 "INSERT INTO spatial_ref_sys (srid,srtext,proj4text) VALUES (%d, ", nSRSId);
+        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
+        oStmt.Append(", ");
+        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
+        oStmt.Append(")");
+    }
+
+    /* Free everything that was allocated. */
+    CPLFree( pszProj4 );
+    CPLFree( pszWKT);
+
+    if ( oStmt.ExecuteSQL() )
+        oSession.CommitTransaction();
+    else
+        oSession.RollbackTransaction();
+
+    return nSRSId;
+}
+
diff --git a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialselectlayer.cpp b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialselectlayer.cpp
index d344eda..06656dd 100644
--- a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialselectlayer.cpp
+++ b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialselectlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmssqlspatialselectlayer.cpp 25989 2013-05-05 19:35:01Z tamas $
+ * $Id: ogrmssqlspatialselectlayer.cpp 27361 2014-05-18 12:11:28Z tamas $
  *
  * Project:  MSSQL Spatial driver
  * Purpose:  Implements OGRMSSQLSpatialSelectLayer class, layer access to the results
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "ogr_mssqlspatial.h"
 
-CPL_CVSID("$Id: ogrmssqlspatialselectlayer.cpp 25989 2013-05-05 19:35:01Z tamas $");
+CPL_CVSID("$Id: ogrmssqlspatialselectlayer.cpp 27361 2014-05-18 12:11:28Z tamas $");
 /************************************************************************/
 /*                     OGRMSSQLSpatialSelectLayer()                     */
 /************************************************************************/
@@ -91,6 +91,9 @@ OGRMSSQLSpatialSelectLayer::OGRMSSQLSpatialSelectLayer( OGRMSSQLSpatialDataSourc
     }
 
     BuildFeatureDefn( "SELECT", poStmt );
+
+    if ( GetSpatialRef() && poFeatureDefn->GetGeomFieldCount() == 1)
+        poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef( poSRS );
 }
 
 /************************************************************************/
diff --git a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialtablelayer.cpp b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialtablelayer.cpp
index be6a80f..19941ce 100644
--- a/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialtablelayer.cpp
+++ b/ogr/ogrsf_frmts/mssqlspatial/ogrmssqlspatialtablelayer.cpp
@@ -1,1239 +1,1249 @@
-/******************************************************************************
- * $Id: ogrmssqlspatialtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $
- *
- * Project:  MSSQL Spatial driver
- * Purpose:  Implements OGRMSSQLSpatialTableLayer class, access to an existing table.
- * Author:   Tamas Szekeres, szekerest at gmail.com
- *
- ******************************************************************************
- * Copyright (c) 2010, Tamas Szekeres
+/******************************************************************************
+ * $Id: ogrmssqlspatialtablelayer.cpp 27361 2014-05-18 12:11:28Z tamas $
+ *
+ * Project:  MSSQL Spatial driver
+ * Purpose:  Implements OGRMSSQLSpatialTableLayer class, access to an existing table.
+ * Author:   Tamas Szekeres, szekerest at gmail.com
+ *
+ ******************************************************************************
+ * Copyright (c) 2010, Tamas Szekeres
  * Copyright (c) 2010-2012, Even Rouault <even dot rouault at mines-paris dot org>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- ****************************************************************************/
-
-#include "cpl_conv.h"
-#include "ogr_mssqlspatial.h"
-
-CPL_CVSID("$Id: ogrmssqlspatialtablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
-
-/************************************************************************/
-/*                         OGRMSSQLAppendEscaped( )                     */
-/************************************************************************/
-
-void OGRMSSQLAppendEscaped( CPLODBCStatement* poStatement, const char* pszStrValue)
-{
-    if (!pszStrValue)
-        poStatement->Append("null");
-    
-    size_t  iIn, iOut , nTextLen = strlen(pszStrValue);
-    char    *pszEscapedText = (char *) VSIMalloc(nTextLen*2 + 3);
-
-    pszEscapedText[0] = '\'';
-    
-    for( iIn = 0, iOut = 1; iIn < nTextLen; iIn++ )
-    {
-        switch( pszStrValue[iIn] )
-        {
-            case '\'':
-                pszEscapedText[iOut++] = '\''; // double quote
-                pszEscapedText[iOut++] = pszStrValue[iIn];
-                break;
-
-            default:
-                pszEscapedText[iOut++] = pszStrValue[iIn];
-                break;
-        }
-    }
-
-    pszEscapedText[iOut++] = '\'';
-
-    pszEscapedText[iOut] = '\0';
-
-    poStatement->Append(pszEscapedText);
-
-    CPLFree( pszEscapedText );
-}
-
-/************************************************************************/
-/*                          OGRMSSQLSpatialTableLayer()                 */
-/************************************************************************/
-
-OGRMSSQLSpatialTableLayer::OGRMSSQLSpatialTableLayer( OGRMSSQLSpatialDataSource *poDSIn )
-
-{
-    poDS = poDSIn;
-
-    pszQuery = NULL;
-
-    bUpdateAccess = TRUE;
-
-    iNextShapeId = 0;
-
-    nSRSId = -1;
-
-    poFeatureDefn = NULL;
-    
-    pszTableName = NULL;
-    pszLayerName = NULL;
-    pszSchemaName = NULL;
-}
-
-/************************************************************************/
-/*                          ~OGRMSSQLSpatialTableLayer()                */
-/************************************************************************/
-
-OGRMSSQLSpatialTableLayer::~OGRMSSQLSpatialTableLayer()
-
-{
-    CPLFree( pszTableName );
-    CPLFree( pszLayerName );
-    CPLFree( pszSchemaName );
-
-    CPLFree( pszQuery );
-    ClearStatement();
-}
-
-/************************************************************************/
-/*                               GetName()                              */
-/************************************************************************/
-
-const char *OGRMSSQLSpatialTableLayer::GetName()
-
-{
-    return pszLayerName;
-}
-
-/************************************************************************/
-/*                             GetLayerDefn()                           */
-/************************************************************************/
-OGRFeatureDefn* OGRMSSQLSpatialTableLayer::GetLayerDefn() 
-{ 
-    if (poFeatureDefn)
-        return poFeatureDefn;
-    
-    CPLODBCSession *poSession = poDS->GetSession();
-/* -------------------------------------------------------------------- */
-/*      Do we have a simple primary key?                                */
-/* -------------------------------------------------------------------- */
-    CPLODBCStatement oGetKey( poSession );
-    
-    if( oGetKey.GetPrimaryKeys( pszTableName, poDS->GetCatalog(), pszSchemaName ) 
-        && oGetKey.Fetch() )
-    {
-        pszFIDColumn = CPLStrdup(oGetKey.GetColData( 3 ));
-        
-        if( oGetKey.Fetch() ) // more than one field in key! 
-        {
-            oGetKey.Clear();
-            CPLFree( pszFIDColumn );
-            pszFIDColumn = NULL;
-
-            CPLDebug( "OGR_MSSQLSpatial", "Table %s has multiple primary key fields, "
-                      "ignoring them all.", pszTableName );
-        }
-    }
-
-    
-/* -------------------------------------------------------------------- */
-/*      Get the column definitions for this table.                      */
-/* -------------------------------------------------------------------- */
-    CPLODBCStatement oGetCol( poSession );
-    CPLErr eErr;
-
-    if( !oGetCol.GetColumns( pszTableName, poDS->GetCatalog(), pszSchemaName ) )
-        return NULL;
-
-    eErr = BuildFeatureDefn( pszLayerName, &oGetCol );
-    if( eErr != CE_None )
-        return NULL;
-        
-    poFeatureDefn->SetGeomType(eGeomType);
-
-    if( poFeatureDefn->GetFieldCount() == 0 &&
-        pszFIDColumn == NULL && pszGeomColumn == NULL )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "No column definitions found for table '%s', layer not usable.", 
-                  pszLayerName );
-        return NULL;
-    }
-        
-/* -------------------------------------------------------------------- */
-/*      If we got a geometry column, does it exist?  Is it binary?      */
-/* -------------------------------------------------------------------- */
-    if( pszGeomColumn != NULL )
-    {
-        int iColumn = oGetCol.GetColId( pszGeomColumn );
-        if( iColumn < 0 )
-        {
-            CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Column %s requested for geometry, but it does not exist.", 
-                      pszGeomColumn );
-            CPLFree( pszGeomColumn );
-            pszGeomColumn = NULL;
-        }
-        else
-        {
-            if ( nGeomColumnType < 0 )
-            {
-                /* last attempt to identify the geometry column type */
-                if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "geometry") )
-                    nGeomColumnType = MSSQLCOLTYPE_GEOMETRY;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "geography") )
-                    nGeomColumnType = MSSQLCOLTYPE_GEOGRAPHY;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "varchar") )
-                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "nvarchar") )
-                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "text") )
-                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "ntext") )
-                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
-                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "image") )
-                    nGeomColumnType = MSSQLCOLTYPE_BINARY; 
-                else
-                {
-                    CPLError( CE_Failure, CPLE_AppDefined, 
-                          "Column type %s is not supported for geometry column.", 
-                          oGetCol.GetColTypeName( iColumn ) );
-                    CPLFree( pszGeomColumn );
-                    pszGeomColumn = NULL;
-                }
-            }
-        }
-    }
-
-    return poFeatureDefn; 
-}
-
-/************************************************************************/
-/*                             Initialize()                             */
-/************************************************************************/
-
-CPLErr OGRMSSQLSpatialTableLayer::Initialize( const char *pszSchema,
-                                              const char *pszLayerName, 
-                                              const char *pszGeomCol,
-                                              int nCoordDimension, 
-                                              int nSRId,
-                                              const char *pszSRText,
-                                              OGRwkbGeometryType eType )
-
-{
-    CPLFree( pszFIDColumn );
-    pszFIDColumn = NULL;
-
-/* -------------------------------------------------------------------- */
-/*      Parse out schema name if present in layer.  We assume a         */
-/*      schema is provided if there is a dot in the name, and that      */
-/*      it is in the form <schema>.<tablename>                          */
-/* -------------------------------------------------------------------- */
-    this->pszLayerName = CPLStrdup(pszLayerName);
-    const char *pszDot = strstr(pszLayerName,".");
-    if( pszDot != NULL )
-    {
-        pszTableName = CPLStrdup(pszDot + 1);
-        pszSchemaName = CPLStrdup(pszLayerName);
-        pszSchemaName[pszDot - pszLayerName] = '\0';
-    }
-    else
-    {
-        pszTableName = CPLStrdup(pszLayerName);
-        pszSchemaName = CPLStrdup(pszSchema);
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Have we been provided a geometry column?                        */
-/* -------------------------------------------------------------------- */
-    CPLFree( pszGeomColumn );
-    if( pszGeomCol == NULL )
-        pszGeomColumn = NULL;
-    else
-        pszGeomColumn = CPLStrdup( pszGeomCol );
-
-    eGeomType = eType;
-
-
-/* -------------------------------------------------------------------- */
-/*             Try to find out the spatial reference                    */
-/* -------------------------------------------------------------------- */
-
-    nSRSId = nSRId;
-
-    if (pszSRText)
-    {
-        /* Process srtext directly if specified */
-        poSRS = new OGRSpatialReference();
-        if( poSRS->importFromWkt( (char**)&pszSRText ) != OGRERR_NONE )
-        {
-            delete poSRS;
-            poSRS = NULL;
-        }
-    }
-    
-    if (!poSRS)
-    {
-        if (nSRSId < 0)
-            nSRSId = FetchSRSId();
-
-        GetSpatialRef();
-    }
-
-    return CE_None;
-}
-
-/************************************************************************/
-/*                         FetchSRSId()                                 */
-/************************************************************************/
-
-int OGRMSSQLSpatialTableLayer::FetchSRSId()
-{
-    if ( poDS->UseGeometryColumns() )
-    {
-        CPLODBCStatement oStatement = CPLODBCStatement( poDS->GetSession() );
-        oStatement.Appendf( "select srid from geometry_columns "
-                        "where f_table_schema = '%s' and f_table_name = '%s'", 
-                        pszSchemaName, pszTableName );
-
-        if( oStatement.ExecuteSQL() && oStatement.Fetch() )
-        {
-            if ( oStatement.GetColData( 0 ) )
-                nSRSId = atoi( oStatement.GetColData( 0 ) );
-        }
-    }
-        
-    return nSRSId;
-}
-
-/************************************************************************/
-/*                       CreateSpatialIndex()                           */
-/*                                                                      */
-/*      Create a spatial index on the geometry column of the layer      */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::CreateSpatialIndex()
-{
-    GetLayerDefn();
-
-    CPLODBCStatement oStatement( poDS->GetSession() );
-
-    if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY)
-    {
-        OGREnvelope oExt;
-        if (GetExtent(&oExt, TRUE) != OGRERR_NONE)
-        {
-            CPLError( CE_Failure, CPLE_AppDefined, 
-                          "Failed to get extent for spatial index." );
-            return OGRERR_FAILURE;
-        }
-
-        oStatement.Appendf("CREATE SPATIAL INDEX [ogr_%s_sidx] ON [dbo].[%s] ( [%s] ) "
-            "USING GEOMETRY_GRID WITH (BOUNDING_BOX =(%.15g, %.15g, %.15g, %.15g))",
-                           pszGeomColumn, poFeatureDefn->GetName(), pszGeomColumn, 
-                           oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY );
-    }
-    else if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-    {
-        oStatement.Appendf("CREATE SPATIAL INDEX [ogr_%s_sidx] ON [dbo].[%s] ( [%s] ) "
-            "USING GEOGRAPHY_GRID",
-                           pszGeomColumn, poFeatureDefn->GetName(), pszGeomColumn );
-    }
-    else
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-            "Spatial index is not supported on the geometry column '%s'", pszGeomColumn);
-        return OGRERR_FAILURE;
-    }
-
-    //poDS->GetSession()->BeginTransaction();
-    
-    if( !oStatement.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Failed to create the spatial index, %s.", 
-                      poDS->GetSession()->GetLastError());
-        return OGRERR_FAILURE;
-    } 
-
-    //poDS->GetSession()->CommitTransaction();
-
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                       DropSpatialIndex()                             */
-/*                                                                      */
-/*      Drop the spatial index on the geometry column of the layer      */
-/************************************************************************/
-
-void OGRMSSQLSpatialTableLayer::DropSpatialIndex()
-{
-    GetLayerDefn();
-
-    CPLODBCStatement oStatement( poDS->GetSession() );
-
-    oStatement.Appendf("IF  EXISTS (SELECT * FROM sys.indexes "
-        "WHERE object_id = OBJECT_ID(N'[dbo].[%s]') AND name = N'ogr_%s_sidx') "
-        "DROP INDEX [ogr_%s_sidx] ON [dbo].[%s]",
-                       poFeatureDefn->GetName(), pszGeomColumn, 
-                       pszGeomColumn, poFeatureDefn->GetName() );
-    
-    //poDS->GetSession()->BeginTransaction();
-
-    if( !oStatement.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Failed to drop the spatial index, %s.", 
-                      poDS->GetSession()->GetLastError());
-        return;
-    } 
-
-    //poDS->GetSession()->CommitTransaction();
-}
-
-/************************************************************************/
-/*                            BuildFields()                             */
-/*                                                                      */
-/*      Build list of fields to fetch, performing any required          */
-/*      transformations (such as on geometry).                          */
-/************************************************************************/
-
-CPLString OGRMSSQLSpatialTableLayer::BuildFields()
-
-{
-    int i = 0;
-    int nColumn = 0;
-    CPLString osFieldList;
-
-    if( pszFIDColumn && poFeatureDefn->GetFieldIndex( pszFIDColumn ) == -1 )
-    {
-        /* Always get the FID column */
-        osFieldList += "[";
-        osFieldList += pszFIDColumn;
-        osFieldList += "]";
-        ++nColumn;
-    }
-
-    if( pszGeomColumn && !poFeatureDefn->IsGeometryIgnored())
-    {
-        if( nColumn > 0 )
-            osFieldList += ", ";
-
-        osFieldList += "[";
-        osFieldList += pszGeomColumn;
-        if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY || 
-                            nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-        {
-            if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKB )
-            {
-                osFieldList += "].STAsBinary() as [";
-                osFieldList += pszGeomColumn;
-            }
-            else if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKT )
-            {
-                osFieldList += "].AsTextZM() as [";
-                osFieldList += pszGeomColumn;
-            }
-            else if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKBZM )
-            {
-                /* SQL Server 2012 */
-                osFieldList += "].AsBinaryZM() as [";
-                osFieldList += pszGeomColumn;
-            }
-        }
-        osFieldList += "]";
-
-        ++nColumn;
-    }
-
-    if (poFeatureDefn->GetFieldCount() > 0)
-    {
-        /* need to reconstruct the field ordinals list */
-        CPLFree(panFieldOrdinals);
-        panFieldOrdinals = (int *) CPLMalloc( sizeof(int) * poFeatureDefn->GetFieldCount() );
-
-        for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
-        {
-            if ( poFeatureDefn->GetFieldDefn(i)->IsIgnored() )
-                continue;
-            
-            const char *pszName = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
-
-            if( nColumn > 0 )
-                osFieldList += ", ";
-        
-            osFieldList += "[";
-            osFieldList += pszName;
-            osFieldList += "]";
-
-            panFieldOrdinals[i] = nColumn;
-
-            ++nColumn;
-        }
-    }
-
-    return osFieldList;
-}
-
-/************************************************************************/
-/*                           ClearStatement()                           */
-/************************************************************************/
-
-void OGRMSSQLSpatialTableLayer::ClearStatement()
-
-{
-    if( poStmt != NULL )
-    {
-        delete poStmt;
-        poStmt = NULL;
-    }
-}
-
-/************************************************************************/
-/*                            GetStatement()                            */
-/************************************************************************/
-
-CPLODBCStatement *OGRMSSQLSpatialTableLayer::GetStatement()
-
-{
-    if( poStmt == NULL )
-    {
-        poStmt = BuildStatement(BuildFields());
-        iNextShapeId = 0;
-    }
-
-    return poStmt;
-}
-
-
-/************************************************************************/
-/*                           BuildStatement()                           */
-/************************************************************************/
-
-CPLODBCStatement* OGRMSSQLSpatialTableLayer::BuildStatement(const char* pszColumns)
-
-{
-    CPLODBCStatement* poStatement = new CPLODBCStatement( poDS->GetSession() );
-    poStatement->Append( "select " );
-    poStatement->Append( pszColumns );
-    poStatement->Append( " from " );
-    poStatement->Append( pszSchemaName );
-    poStatement->Append( "." );
-    poStatement->Append( pszTableName );
-
-    /* Append attribute query if we have it */
-    if( pszQuery != NULL )
-        poStatement->Appendf( " where (%s)", pszQuery );
-
-    /* If we have a spatial filter, query on it */
-    if ( m_poFilterGeom != NULL )
-    {
-        if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
-            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-        {
-            if( pszQuery == NULL )
-                poStatement->Append( " where" );
-            else
-                poStatement->Append( " and" );
-
-            poStatement->Appendf(" [%s].STIntersects(", pszGeomColumn );
-
-            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-                poStatement->Append( "geography::" );
-            else
-                poStatement->Append( "geometry::" );
-            
-            if ( m_sFilterEnvelope.MinX == m_sFilterEnvelope.MaxX || 
-                 m_sFilterEnvelope.MinY == m_sFilterEnvelope.MaxY)
-                poStatement->Appendf("STGeomFromText('POINT(%.15g %.15g)',%d)) = 1", 
-                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY, nSRSId >= 0? nSRSId : 0);
-            else
-                poStatement->Appendf( "STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%d)) = 1", 
-                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY,
-                                            m_sFilterEnvelope.MaxX, m_sFilterEnvelope.MinY, 
-                                            m_sFilterEnvelope.MaxX, m_sFilterEnvelope.MaxY,
-                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MaxY,
-                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY,
-                                            nSRSId >= 0? nSRSId : 0 );
-        }
-        else
-        {
-            CPLError( CE_Failure, CPLE_AppDefined, 
-                      "Spatial filter is supported only on geometry and geography column types." );
-            
-            delete poStatement;
-            return NULL;
-        }
-    }
-
-    CPLDebug( "OGR_MSSQLSpatial", "ExecuteSQL(%s)", poStatement->GetCommand() );
-    if( poStatement->ExecuteSQL() )
-        return poStatement;
-    else
-    {
-        delete poStatement;
-        return NULL;
-    }
-}
-
-/************************************************************************/
-/*                            ResetReading()                            */
-/************************************************************************/
-
-void OGRMSSQLSpatialTableLayer::ResetReading()
-
-{
-    ClearStatement();
-    OGRMSSQLSpatialLayer::ResetReading();
-}
-
-/************************************************************************/
-/*                             GetFeature()                             */
-/************************************************************************/
-
-OGRFeature *OGRMSSQLSpatialTableLayer::GetFeature( long nFeatureId )
-
-{
-    if( pszFIDColumn == NULL )
-        return OGRMSSQLSpatialLayer::GetFeature( nFeatureId );
-
-    ClearStatement();
-
-    iNextShapeId = nFeatureId;
-
-    poStmt = new CPLODBCStatement( poDS->GetSession() );
-    CPLString osFields = BuildFields();
-    poStmt->Appendf( "select %s from %s where %s = %ld", osFields.c_str(), 
-        poFeatureDefn->GetName(), pszFIDColumn, nFeatureId );
-
-    if( !poStmt->ExecuteSQL() )
-    {
-        delete poStmt;
-        poStmt = NULL;
-        return NULL;
-    }
-
-    return GetNextRawFeature();
-}
-
-/************************************************************************/
-/*                         SetAttributeFilter()                         */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::SetAttributeFilter( const char *pszQuery )
-
-{
-    CPLFree(m_pszAttrQueryString);
-    m_pszAttrQueryString = (pszQuery) ? CPLStrdup(pszQuery) : NULL;
-
-    if( (pszQuery == NULL && this->pszQuery == NULL)
-        || (pszQuery != NULL && this->pszQuery != NULL 
-            && EQUAL(pszQuery,this->pszQuery)) )
-        return OGRERR_NONE;
-
-    CPLFree( this->pszQuery );
-    this->pszQuery = (pszQuery) ? CPLStrdup( pszQuery ) : NULL;
-
-    ClearStatement();
-
-    return OGRERR_NONE;
-}
-
-
-/************************************************************************/
-/*                           TestCapability()                           */
-/************************************************************************/
-
-int OGRMSSQLSpatialTableLayer::TestCapability( const char * pszCap )
-
-{
-    if ( bUpdateAccess )
-    {
-        if( EQUAL(pszCap,OLCSequentialWrite) || EQUAL(pszCap,OLCCreateField)
-            || EQUAL(pszCap,OLCDeleteFeature) )
-            return TRUE;
-
-        else if( EQUAL(pszCap,OLCRandomWrite) )
-            return (pszFIDColumn != NULL);
-    }
-
-#if (ODBCVER >= 0x0300)
-    if( EQUAL(pszCap,OLCTransactions) )
-        return TRUE;
-#else
-    if( EQUAL(pszCap,OLCTransactions) )
-        return FALSE;
-#endif
-
-    if( EQUAL(pszCap,OLCIgnoreFields) )
-        return TRUE; 
-    
-    if( EQUAL(pszCap,OLCRandomRead) )
-        return (pszFIDColumn != NULL);
-    else if( EQUAL(pszCap,OLCFastFeatureCount) )
-        return TRUE;
-    else 
-        return OGRMSSQLSpatialLayer::TestCapability( pszCap );
-}
-
-/************************************************************************/
-/*                          GetFeatureCount()                           */
-/************************************************************************/
-
-int OGRMSSQLSpatialTableLayer::GetFeatureCount( int bForce )
-
-{
-    GetLayerDefn();
-
-    if( TestCapability(OLCFastFeatureCount) == FALSE )
-        return OGRMSSQLSpatialLayer::GetFeatureCount( bForce );
-
-    ClearStatement();
-        
-    CPLODBCStatement* poStatement = BuildStatement( "count(*)" );
-
-    if (poStatement == NULL || !poStatement->Fetch())
-    {
-        delete poStatement;
-        return OGRMSSQLSpatialLayer::GetFeatureCount( bForce );
-    }
-
-    int nRet = atoi(poStatement->GetColData( 0 ));
-    delete poStatement;
-    return nRet;
-}
-
-
-/************************************************************************/
-/*                            CreateField()                             */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::CreateField( OGRFieldDefn *poFieldIn, 
-                                         int bApproxOK )
-
-{
-    char                szFieldType[256];
-    OGRFieldDefn        oField( poFieldIn );
-
-    GetLayerDefn();
-
-/* -------------------------------------------------------------------- */
-/*      Do we want to "launder" the column names into MSSQL             */
-/*      friendly format?                                                */
-/* -------------------------------------------------------------------- */
-    if( bLaunderColumnNames )
-    {
-        char    *pszSafeName = poDS->LaunderName( oField.GetNameRef() );
-
-        oField.SetName( pszSafeName );
-        CPLFree( pszSafeName );
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Identify the MSSQL type.                                        */
-/* -------------------------------------------------------------------- */
-    
-    if( oField.GetType() == OFTInteger )
-    {
-        if( oField.GetWidth() > 0 && bPreservePrecision )
-            sprintf( szFieldType, "numeric(%d,0)", oField.GetWidth() );
-        else
-            strcpy( szFieldType, "int" );
-    }
-    else if( oField.GetType() == OFTReal )
-    {
-        if( oField.GetWidth() > 0 && oField.GetPrecision() > 0
-            && bPreservePrecision )
-            sprintf( szFieldType, "numeric(%d,%d)",
-                     oField.GetWidth(), oField.GetPrecision() );
-        else
-            strcpy( szFieldType, "float" );
-    }
-    else if( oField.GetType() == OFTString )
-    {
-        if( oField.GetWidth() == 0 || !bPreservePrecision )
-            strcpy( szFieldType, "varchar(MAX)" );
-        else
-            sprintf( szFieldType, "varchar(%d)", oField.GetWidth() );
-    }
-    else if( oField.GetType() == OFTDate )
-    {
-        strcpy( szFieldType, "date" );
-    }
-    else if( oField.GetType() == OFTTime )
-    {
-        strcpy( szFieldType, "time(7)" );
-    }
-    else if( oField.GetType() == OFTDateTime )
-    {
-        strcpy( szFieldType, "datetime" );
-    }
-    else if( oField.GetType() == OFTBinary )
-    {
-        strcpy( szFieldType, "image" );
-    }
-    else if( bApproxOK )
-    {
-        CPLError( CE_Warning, CPLE_NotSupported,
-                  "Can't create field %s with type %s on MSSQL layers.  Creating as varchar.",
-                  oField.GetNameRef(),
-                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
-        strcpy( szFieldType, "varchar" );
-    }
-    else
-    {
-        CPLError( CE_Failure, CPLE_NotSupported,
-                  "Can't create field %s with type %s on MSSQL layers.",
-                  oField.GetNameRef(),
-                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
-
-        return OGRERR_FAILURE;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Create the new field.                                           */
-/* -------------------------------------------------------------------- */
-    
-    CPLODBCStatement oStmt( poDS->GetSession() );
-            
-    oStmt.Appendf( "ALTER TABLE [%s].[%s] ADD [%s] %s", 
-        pszSchemaName, pszTableName, oField.GetNameRef(), szFieldType);
-
-    if( !oStmt.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                    "Error creating field %s, %s", oField.GetNameRef(), 
-                    poDS->GetSession()->GetLastError() );
-
-        return OGRERR_FAILURE;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Add the field to the OGRFeatureDefn.                            */
-/* -------------------------------------------------------------------- */
-
-    poFeatureDefn->AddFieldDefn( &oField );
-
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                             SetFeature()                             */
-/*                                                                      */
-/*      SetFeature() is implemented by an UPDATE SQL command            */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::SetFeature( OGRFeature *poFeature )
-
-{
-    OGRErr              eErr = OGRERR_FAILURE;
-
-    GetLayerDefn();
-
-    if( NULL == poFeature )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                  "NULL pointer to OGRFeature passed to SetFeature()." );
-        return eErr;
-    }
-
-    if( poFeature->GetFID() == OGRNullFID )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                  "FID required on features given to SetFeature()." );
-        return eErr;
-    }
-
-    if( !pszFIDColumn )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                  "Unable to update features in tables without\n"
-                  "a recognised FID column.");
-        return eErr;
-
-    }
-    
-    ClearStatement();
-
-/* -------------------------------------------------------------------- */
-/*      Form the UPDATE command.                                        */
-/* -------------------------------------------------------------------- */
-    CPLODBCStatement oStmt( poDS->GetSession() );
-            
-    oStmt.Appendf( "UPDATE [%s].[%s] SET ", pszSchemaName, pszTableName);
-
-    OGRMSSQLGeometryValidator oValidator(poFeature->GetGeometryRef());
-    OGRGeometry *poGeom = oValidator.GetValidGeometryRef();
-
-    if (poFeature->GetGeometryRef() != poGeom)
-    {
-        CPLError( CE_Warning, CPLE_NotSupported,
-                  "Geometry with FID = %ld has been modified.", poFeature->GetFID() );
-    }
-
-    int bNeedComma = FALSE;
-    if(pszGeomColumn != NULL)
-    {
-        char    *pszWKT = NULL;
-
-        if (poGeom != NULL)
-            poGeom->exportToWkt( &pszWKT );
-
-        oStmt.Appendf( "[%s] = ", pszGeomColumn );
-
-        if( pszWKT != NULL && (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
-            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY))
-        {
-            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-            {
-                oStmt.Append( "geography::STGeomFromText(" );
-                OGRMSSQLAppendEscaped(&oStmt, pszWKT);
-                oStmt.Appendf(",%d)", nSRSId );
-            }
-            else
-            {
-                oStmt.Append( "geometry::STGeomFromText(" );
-                OGRMSSQLAppendEscaped(&oStmt, pszWKT);
-                oStmt.Appendf(",%d).MakeValid()", nSRSId );
-            }
-        }
-        else
-            oStmt.Append( "null" );
-
-        bNeedComma = TRUE;
-        CPLFree(pszWKT);
-    }
-
-    int nFieldCount = poFeatureDefn->GetFieldCount();
-    int i;
-    for( i = 0; i < nFieldCount; i++ )
-    {
-        if (bNeedComma)
-            oStmt.Appendf( ", [%s] = ", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
-        else
-        {
-            oStmt.Appendf( "[%s] = ", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
-            bNeedComma = TRUE;
-        }
-
-        if( !poFeature->IsFieldSet( i ) )
-            oStmt.Append( "null" );
-        else
-            AppendFieldValue(&oStmt, poFeature, i);
-    }
-
-    /* Add the WHERE clause */
-    oStmt.Appendf( " WHERE [%s] = %ld" , pszFIDColumn, poFeature->GetFID());
-
-/* -------------------------------------------------------------------- */
-/*      Execute the update.                                             */
-/* -------------------------------------------------------------------- */
-
-    if( !oStmt.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-            "Error updating feature with FID:%ld, %s", poFeature->GetFID(), 
-                    poDS->GetSession()->GetLastError() );
-
-        return OGRERR_FAILURE;
-    }
-    
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                          DeleteFeature()                             */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::DeleteFeature( long nFID )
-
-{
-    GetLayerDefn();
-    
-    if( pszFIDColumn == NULL )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "DeleteFeature() without any FID column." );
-        return OGRERR_FAILURE;
-    }
-    
-    if( nFID == OGRNullFID )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "DeleteFeature() with unset FID fails." );
-        return OGRERR_FAILURE;
-    }
-    
-    ClearStatement();
-
-/* -------------------------------------------------------------------- */
-/*      Drop the record with this FID.                                  */
-/* -------------------------------------------------------------------- */
-    CPLODBCStatement oStatement( poDS->GetSession() );
-
-    oStatement.Appendf("DELETE FROM [%s] WHERE [%s] = %ld", 
-            poFeatureDefn->GetName(), pszFIDColumn, nFID);
-    
-    if( !oStatement.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "Attempt to delete feature with FID %ld failed. %s", 
-                  nFID, poDS->GetSession()->GetLastError() );
-
-        return OGRERR_FAILURE;
-    }
-    
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                           CreateFeature()                            */
-/************************************************************************/
-
-OGRErr OGRMSSQLSpatialTableLayer::CreateFeature( OGRFeature *poFeature )
-
-{
-    GetLayerDefn();
-
-    if( NULL == poFeature )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined,
-                  "NULL pointer to OGRFeature passed to CreateFeature()." );
-        return OGRERR_FAILURE;
-    }
-    
-    ClearStatement();
-
-    CPLODBCStatement oStatement( poDS->GetSession() );
-
-    /* the fid values are retieved from the source layer */
-    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL && bIsIdentityFid )
-        oStatement.Appendf("SET IDENTITY_INSERT [%s].[%s] ON;", pszSchemaName, pszTableName );
-
-/* -------------------------------------------------------------------- */
-/*      Form the INSERT command.                                        */
-/* -------------------------------------------------------------------- */
-
-    oStatement.Appendf( "INSERT INTO [%s].[%s] (", pszSchemaName, pszTableName );
-
-    OGRMSSQLGeometryValidator oValidator(poFeature->GetGeometryRef());
-    OGRGeometry *poGeom = oValidator.GetValidGeometryRef();
-
-    if (poFeature->GetGeometryRef() != poGeom)
-    {
-        CPLError( CE_Warning, CPLE_NotSupported,
-                  "Geometry with FID = %ld has been modified.", poFeature->GetFID() );
-    }
-
-    int bNeedComma = FALSE;
-
-    if (poGeom != NULL && pszGeomColumn != NULL)
-    {
-        oStatement.Append( pszGeomColumn );
-        bNeedComma = TRUE;
-    }
-
-    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
-    {
-        if (bNeedComma)
-            oStatement.Appendf( ", [%s]", pszFIDColumn );
-        else
-        {
-            oStatement.Appendf( "[%s]", pszFIDColumn );
-            bNeedComma = TRUE;
-        }
-    }
-
-    int nFieldCount = poFeatureDefn->GetFieldCount();
-    int i;
-    for( i = 0; i < nFieldCount; i++ )
-    {
-        if( !poFeature->IsFieldSet( i ) )
-            continue;
-
-        if (bNeedComma)
-            oStatement.Appendf( ", [%s]", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
-        else
-        {
-            oStatement.Appendf( "[%s]", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
-            bNeedComma = TRUE;
-        }
-    }
-
-    oStatement.Appendf( ") VALUES (" );
-
-    /* Set the geometry */
-    bNeedComma = FALSE;
-    if(poGeom != NULL && pszGeomColumn != NULL)
-    {
-        char    *pszWKT = NULL;
-    
-        //poGeom->setCoordinateDimension( nCoordDimension );
-
-        poGeom->exportToWkt( &pszWKT );
-
-        if( pszWKT != NULL && (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
-            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY))
-        {
-            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
-            {
-                oStatement.Append( "geography::STGeomFromText(" );
-                OGRMSSQLAppendEscaped(&oStatement, pszWKT);
-                oStatement.Appendf(",%d)", nSRSId );
-            }
-            else
-            {
-                oStatement.Append( "geometry::STGeomFromText(" );
-                OGRMSSQLAppendEscaped(&oStatement, pszWKT);
-                oStatement.Appendf(",%d).MakeValid()", nSRSId );
-            }     
-        }
-        else
-            oStatement.Append( "null" );
-
-        bNeedComma = TRUE;
-        CPLFree(pszWKT);
-    }
-
-    /* Set the FID */
-    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
-    {
-        if (bNeedComma)
-            oStatement.Appendf( ", %ld", poFeature->GetFID() );
-        else
-        {
-            oStatement.Appendf( "%ld", poFeature->GetFID() );
-            bNeedComma = TRUE;
-        }
-    }
-
-    for( i = 0; i < nFieldCount; i++ )
-    {
-        if( !poFeature->IsFieldSet( i ) )
-            continue;
-
-        if (bNeedComma)
-            oStatement.Append( ", " );
-        else
-            bNeedComma = TRUE;
-
-        AppendFieldValue(&oStatement, poFeature, i);
-    }
-
-    oStatement.Append( ");" );
-
-    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL && bIsIdentityFid )
-        oStatement.Appendf("SET IDENTITY_INSERT [%s].[%s] OFF;", pszSchemaName, pszTableName );
-
-/* -------------------------------------------------------------------- */
-/*      Execute the insert.                                             */
-/* -------------------------------------------------------------------- */
-    
-    if( !oStatement.ExecuteSQL() )
-    {
-        CPLError( CE_Failure, CPLE_AppDefined, 
-                  "INSERT command for new feature failed. %s", 
-                   poDS->GetSession()->GetLastError() );
-
-        return OGRERR_FAILURE;
-    }
-
-    return OGRERR_NONE;
-}
-
-/************************************************************************/
-/*                          AppendFieldValue()                          */
-/*                                                                      */
-/* Used by CreateFeature() and SetFeature() to format a                 */
-/* non-empty field value                                                */
-/************************************************************************/
-
-void OGRMSSQLSpatialTableLayer::AppendFieldValue(CPLODBCStatement *poStatement,
-                                       OGRFeature* poFeature, int i)
-{
-    int nOGRFieldType = poFeatureDefn->GetFieldDefn(i)->GetType();
-
-    // We need special formatting for integer list values.
-    if(  nOGRFieldType == OFTIntegerList )
-    {
-        //TODO
-        poStatement->Append( "null" );
-        return;
-    }
-
-    // We need special formatting for real list values.
-    else if( nOGRFieldType == OFTRealList )
-    {
-        //TODO
-        poStatement->Append( "null" );
-        return;
-    }
-
-    // We need special formatting for string list values.
-    else if( nOGRFieldType == OFTStringList )
-    {
-        //TODO
-        poStatement->Append( "null" );
-        return;
-    }
-
-    // Binary formatting
-    if( nOGRFieldType == OFTBinary )
-    {
-        int nLen = 0;
-        GByte* pabyData = poFeature->GetFieldAsBinary( i, &nLen );
-        char* pszBytes = GByteArrayToHexString( pabyData, nLen);
-        poStatement->Append( pszBytes );
-        CPLFree(pszBytes);
-        return;
-    }
-
-    // Flag indicating NULL or not-a-date date value
-    // e.g. 0000-00-00 - there is no year 0
-    OGRBoolean bIsDateNull = FALSE;
-
-    const char *pszStrValue = poFeature->GetFieldAsString(i);
-
-    // Check if date is NULL: 0000-00-00
-    if( nOGRFieldType == OFTDate )
-    {
-        if( EQUALN( pszStrValue, "0000", 4 ) )
-        {
-            pszStrValue = "null";
-            bIsDateNull = TRUE;
-        }
-    }
-    else if ( nOGRFieldType == OFTReal )
-    {
-        char* pszComma = strchr((char*)pszStrValue, ',');
-        if (pszComma)
-            *pszComma = '.';
-    }
-
-    if( nOGRFieldType != OFTInteger && nOGRFieldType != OFTReal
-        && !bIsDateNull )
-    {
-        OGRMSSQLAppendEscaped(poStatement, pszStrValue);
-    }
-    else
-    {
-        poStatement->Append( pszStrValue );
-    }
-}
-
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ ****************************************************************************/
+
+#include "cpl_conv.h"
+#include "ogr_mssqlspatial.h"
+
+CPL_CVSID("$Id: ogrmssqlspatialtablelayer.cpp 27361 2014-05-18 12:11:28Z tamas $");
+
+/************************************************************************/
+/*                         OGRMSSQLAppendEscaped( )                     */
+/************************************************************************/
+
+void OGRMSSQLAppendEscaped( CPLODBCStatement* poStatement, const char* pszStrValue)
+{
+    if (!pszStrValue)
+        poStatement->Append("null");
+    
+    size_t  iIn, iOut , nTextLen = strlen(pszStrValue);
+    char    *pszEscapedText = (char *) VSIMalloc(nTextLen*2 + 3);
+
+    pszEscapedText[0] = '\'';
+    
+    for( iIn = 0, iOut = 1; iIn < nTextLen; iIn++ )
+    {
+        switch( pszStrValue[iIn] )
+        {
+            case '\'':
+                pszEscapedText[iOut++] = '\''; // double quote
+                pszEscapedText[iOut++] = pszStrValue[iIn];
+                break;
+
+            default:
+                pszEscapedText[iOut++] = pszStrValue[iIn];
+                break;
+        }
+    }
+
+    pszEscapedText[iOut++] = '\'';
+
+    pszEscapedText[iOut] = '\0';
+
+    poStatement->Append(pszEscapedText);
+
+    CPLFree( pszEscapedText );
+}
+
+/************************************************************************/
+/*                          OGRMSSQLSpatialTableLayer()                 */
+/************************************************************************/
+
+OGRMSSQLSpatialTableLayer::OGRMSSQLSpatialTableLayer( OGRMSSQLSpatialDataSource *poDSIn )
+
+{
+    poDS = poDSIn;
+
+    pszQuery = NULL;
+
+    bUpdateAccess = TRUE;
+
+    iNextShapeId = 0;
+
+    nSRSId = -1;
+
+    poFeatureDefn = NULL;
+    
+    pszTableName = NULL;
+    pszLayerName = NULL;
+    pszSchemaName = NULL;
+
+    eGeomType = wkbNone;
+}
+
+/************************************************************************/
+/*                          ~OGRMSSQLSpatialTableLayer()                */
+/************************************************************************/
+
+OGRMSSQLSpatialTableLayer::~OGRMSSQLSpatialTableLayer()
+
+{
+    CPLFree( pszTableName );
+    CPLFree( pszLayerName );
+    CPLFree( pszSchemaName );
+
+    CPLFree( pszQuery );
+    ClearStatement();
+}
+
+/************************************************************************/
+/*                               GetName()                              */
+/************************************************************************/
+
+const char *OGRMSSQLSpatialTableLayer::GetName()
+
+{
+    return pszLayerName;
+}
+
+/************************************************************************/
+/*                             GetLayerDefn()                           */
+/************************************************************************/
+OGRFeatureDefn* OGRMSSQLSpatialTableLayer::GetLayerDefn() 
+{ 
+    if (poFeatureDefn)
+        return poFeatureDefn;
+    
+    CPLODBCSession *poSession = poDS->GetSession();
+/* -------------------------------------------------------------------- */
+/*      Do we have a simple primary key?                                */
+/* -------------------------------------------------------------------- */
+    CPLODBCStatement oGetKey( poSession );
+    
+    if( oGetKey.GetPrimaryKeys( pszTableName, poDS->GetCatalog(), pszSchemaName ) 
+        && oGetKey.Fetch() )
+    {
+        pszFIDColumn = CPLStrdup(oGetKey.GetColData( 3 ));
+        
+        if( oGetKey.Fetch() ) // more than one field in key! 
+        {
+            oGetKey.Clear();
+            CPLFree( pszFIDColumn );
+            pszFIDColumn = NULL;
+
+            CPLDebug( "OGR_MSSQLSpatial", "Table %s has multiple primary key fields, "
+                      "ignoring them all.", pszTableName );
+        }
+    }
+
+    
+/* -------------------------------------------------------------------- */
+/*      Get the column definitions for this table.                      */
+/* -------------------------------------------------------------------- */
+    CPLODBCStatement oGetCol( poSession );
+    CPLErr eErr;
+
+    if( !oGetCol.GetColumns( pszTableName, poDS->GetCatalog(), pszSchemaName ) )
+        return NULL;
+
+    eErr = BuildFeatureDefn( pszLayerName, &oGetCol );
+    if( eErr != CE_None )
+        return NULL;
+
+    if (eGeomType != wkbNone)
+        poFeatureDefn->SetGeomType(eGeomType);
+    
+    if ( GetSpatialRef() && poFeatureDefn->GetGeomFieldCount() == 1)
+        poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef( poSRS );
+
+    if( poFeatureDefn->GetFieldCount() == 0 &&
+        pszFIDColumn == NULL && pszGeomColumn == NULL )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "No column definitions found for table '%s', layer not usable.", 
+                  pszLayerName );
+        return NULL;
+    }
+        
+/* -------------------------------------------------------------------- */
+/*      If we got a geometry column, does it exist?  Is it binary?      */
+/* -------------------------------------------------------------------- */
+    if( pszGeomColumn != NULL )
+    {
+        int iColumn = oGetCol.GetColId( pszGeomColumn );
+        if( iColumn < 0 )
+        {
+            CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Column %s requested for geometry, but it does not exist.", 
+                      pszGeomColumn );
+            CPLFree( pszGeomColumn );
+            pszGeomColumn = NULL;
+        }
+        else
+        {
+            if ( nGeomColumnType < 0 )
+            {
+                /* last attempt to identify the geometry column type */
+                if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "geometry") )
+                    nGeomColumnType = MSSQLCOLTYPE_GEOMETRY;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "geography") )
+                    nGeomColumnType = MSSQLCOLTYPE_GEOGRAPHY;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "varchar") )
+                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "nvarchar") )
+                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "text") )
+                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "ntext") )
+                    nGeomColumnType = MSSQLCOLTYPE_TEXT;
+                else if ( EQUAL(oGetCol.GetColTypeName( iColumn ), "image") )
+                    nGeomColumnType = MSSQLCOLTYPE_BINARY; 
+                else
+                {
+                    CPLError( CE_Failure, CPLE_AppDefined, 
+                          "Column type %s is not supported for geometry column.", 
+                          oGetCol.GetColTypeName( iColumn ) );
+                    CPLFree( pszGeomColumn );
+                    pszGeomColumn = NULL;
+                }
+            }
+        }
+    }
+
+    return poFeatureDefn; 
+}
+
+/************************************************************************/
+/*                             Initialize()                             */
+/************************************************************************/
+
+CPLErr OGRMSSQLSpatialTableLayer::Initialize( const char *pszSchema,
+                                              const char *pszLayerName, 
+                                              const char *pszGeomCol,
+                                              int nCoordDimension, 
+                                              int nSRId,
+                                              const char *pszSRText,
+                                              OGRwkbGeometryType eType )
+
+{
+    CPLFree( pszFIDColumn );
+    pszFIDColumn = NULL;
+
+/* -------------------------------------------------------------------- */
+/*      Parse out schema name if present in layer.  We assume a         */
+/*      schema is provided if there is a dot in the name, and that      */
+/*      it is in the form <schema>.<tablename>                          */
+/* -------------------------------------------------------------------- */
+    const char *pszDot = strstr(pszLayerName,".");
+    if( pszDot != NULL )
+    {
+        pszTableName = CPLStrdup(pszDot + 1);
+        pszSchemaName = CPLStrdup(pszLayerName);
+        pszSchemaName[pszDot - pszLayerName] = '\0';
+        this->pszLayerName = CPLStrdup(pszLayerName);
+    }
+    else
+    {
+        pszTableName = CPLStrdup(pszLayerName);
+        pszSchemaName = CPLStrdup(pszSchema);
+        if ( EQUAL(pszSchemaName, "dbo") )
+            this->pszLayerName = CPLStrdup(pszLayerName);
+        else
+            this->pszLayerName = CPLStrdup(CPLSPrintf("%s.%s", pszSchemaName, pszTableName));
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Have we been provided a geometry column?                        */
+/* -------------------------------------------------------------------- */
+    CPLFree( pszGeomColumn );
+    if( pszGeomCol == NULL )
+        GetLayerDefn(); /* fetch geom colum if not specified */
+    else
+        pszGeomColumn = CPLStrdup( pszGeomCol );
+
+    if (eType != wkbNone)
+        eGeomType = eType;
+
+/* -------------------------------------------------------------------- */
+/*             Try to find out the spatial reference                    */
+/* -------------------------------------------------------------------- */
+
+    nSRSId = nSRId;
+
+    if (pszSRText)
+    {
+        /* Process srtext directly if specified */
+        poSRS = new OGRSpatialReference();
+        if( poSRS->importFromWkt( (char**)&pszSRText ) != OGRERR_NONE )
+        {
+            delete poSRS;
+            poSRS = NULL;
+        }
+    }
+    
+    if (!poSRS)
+    {
+        if (nSRSId < 0)
+            nSRSId = FetchSRSId();
+
+        GetSpatialRef();
+    }
+
+    return CE_None;
+}
+
+/************************************************************************/
+/*                         FetchSRSId()                                 */
+/************************************************************************/
+
+int OGRMSSQLSpatialTableLayer::FetchSRSId()
+{
+    if ( poDS->UseGeometryColumns() )
+    {
+        CPLODBCStatement oStatement = CPLODBCStatement( poDS->GetSession() );
+        oStatement.Appendf( "select srid from geometry_columns "
+                        "where f_table_schema = '%s' and f_table_name = '%s'", 
+                        pszSchemaName, pszTableName );
+
+        if( oStatement.ExecuteSQL() && oStatement.Fetch() )
+        {
+            if ( oStatement.GetColData( 0 ) )
+                nSRSId = atoi( oStatement.GetColData( 0 ) );
+        }
+    }
+        
+    return nSRSId;
+}
+
+/************************************************************************/
+/*                       CreateSpatialIndex()                           */
+/*                                                                      */
+/*      Create a spatial index on the geometry column of the layer      */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::CreateSpatialIndex()
+{
+    GetLayerDefn();
+
+    CPLODBCStatement oStatement( poDS->GetSession() );
+
+    if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY)
+    {
+        OGREnvelope oExt;
+        if (GetExtent(&oExt, TRUE) != OGRERR_NONE)
+        {
+            CPLError( CE_Failure, CPLE_AppDefined, 
+                          "Failed to get extent for spatial index." );
+            return OGRERR_FAILURE;
+        }
+
+        oStatement.Appendf("CREATE SPATIAL INDEX [ogr_%s_sidx] ON [%s].[%s] ( [%s] ) "
+            "USING GEOMETRY_GRID WITH (BOUNDING_BOX =(%.15g, %.15g, %.15g, %.15g))",
+                           pszGeomColumn, pszSchemaName, pszTableName, pszGeomColumn, 
+                           oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY );
+    }
+    else if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+    {
+        oStatement.Appendf("CREATE SPATIAL INDEX [ogr_%s_sidx] ON [%s].[%s] ( [%s] ) "
+            "USING GEOGRAPHY_GRID",
+                           pszGeomColumn, pszSchemaName, pszTableName, pszGeomColumn );
+    }
+    else
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+            "Spatial index is not supported on the geometry column '%s'", pszGeomColumn);
+        return OGRERR_FAILURE;
+    }
+
+    //poDS->GetSession()->BeginTransaction();
+    
+    if( !oStatement.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Failed to create the spatial index, %s.", 
+                      poDS->GetSession()->GetLastError());
+        return OGRERR_FAILURE;
+    } 
+
+    //poDS->GetSession()->CommitTransaction();
+
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                       DropSpatialIndex()                             */
+/*                                                                      */
+/*      Drop the spatial index on the geometry column of the layer      */
+/************************************************************************/
+
+void OGRMSSQLSpatialTableLayer::DropSpatialIndex()
+{
+    GetLayerDefn();
+
+    CPLODBCStatement oStatement( poDS->GetSession() );
+
+    oStatement.Appendf("IF  EXISTS (SELECT * FROM sys.indexes "
+        "WHERE object_id = OBJECT_ID(N'[%s].[%s]') AND name = N'ogr_%s_sidx') "
+        "DROP INDEX [ogr_%s_sidx] ON [%s].[%s]",
+                       pszSchemaName, pszTableName, pszGeomColumn, 
+                       pszGeomColumn, pszSchemaName, pszTableName );
+    
+    //poDS->GetSession()->BeginTransaction();
+
+    if( !oStatement.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Failed to drop the spatial index, %s.", 
+                      poDS->GetSession()->GetLastError());
+        return;
+    } 
+
+    //poDS->GetSession()->CommitTransaction();
+}
+
+/************************************************************************/
+/*                            BuildFields()                             */
+/*                                                                      */
+/*      Build list of fields to fetch, performing any required          */
+/*      transformations (such as on geometry).                          */
+/************************************************************************/
+
+CPLString OGRMSSQLSpatialTableLayer::BuildFields()
+
+{
+    int i = 0;
+    int nColumn = 0;
+    CPLString osFieldList;
+
+    if( pszFIDColumn && poFeatureDefn->GetFieldIndex( pszFIDColumn ) == -1 )
+    {
+        /* Always get the FID column */
+        osFieldList += "[";
+        osFieldList += pszFIDColumn;
+        osFieldList += "]";
+        ++nColumn;
+    }
+
+    if( pszGeomColumn && !poFeatureDefn->IsGeometryIgnored())
+    {
+        if( nColumn > 0 )
+            osFieldList += ", ";
+
+        osFieldList += "[";
+        osFieldList += pszGeomColumn;
+        if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY || 
+                            nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+        {
+            if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKB )
+            {
+                osFieldList += "].STAsBinary() as [";
+                osFieldList += pszGeomColumn;
+            }
+            else if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKT )
+            {
+                osFieldList += "].AsTextZM() as [";
+                osFieldList += pszGeomColumn;
+            }
+            else if ( poDS->GetGeometryFormat() == MSSQLGEOMETRY_WKBZM )
+            {
+                /* SQL Server 2012 */
+                osFieldList += "].AsBinaryZM() as [";
+                osFieldList += pszGeomColumn;
+            }
+        }
+        osFieldList += "]";
+
+        ++nColumn;
+    }
+
+    if (poFeatureDefn->GetFieldCount() > 0)
+    {
+        /* need to reconstruct the field ordinals list */
+        CPLFree(panFieldOrdinals);
+        panFieldOrdinals = (int *) CPLMalloc( sizeof(int) * poFeatureDefn->GetFieldCount() );
+
+        for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
+        {
+            if ( poFeatureDefn->GetFieldDefn(i)->IsIgnored() )
+                continue;
+            
+            const char *pszName = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
+
+            if( nColumn > 0 )
+                osFieldList += ", ";
+        
+            osFieldList += "[";
+            osFieldList += pszName;
+            osFieldList += "]";
+
+            panFieldOrdinals[i] = nColumn;
+
+            ++nColumn;
+        }
+    }
+
+    return osFieldList;
+}
+
+/************************************************************************/
+/*                           ClearStatement()                           */
+/************************************************************************/
+
+void OGRMSSQLSpatialTableLayer::ClearStatement()
+
+{
+    if( poStmt != NULL )
+    {
+        delete poStmt;
+        poStmt = NULL;
+    }
+}
+
+/************************************************************************/
+/*                            GetStatement()                            */
+/************************************************************************/
+
+CPLODBCStatement *OGRMSSQLSpatialTableLayer::GetStatement()
+
+{
+    if( poStmt == NULL )
+    {
+        poStmt = BuildStatement(BuildFields());
+        iNextShapeId = 0;
+    }
+
+    return poStmt;
+}
+
+
+/************************************************************************/
+/*                           BuildStatement()                           */
+/************************************************************************/
+
+CPLODBCStatement* OGRMSSQLSpatialTableLayer::BuildStatement(const char* pszColumns)
+
+{
+    CPLODBCStatement* poStatement = new CPLODBCStatement( poDS->GetSession() );
+    poStatement->Append( "select " );
+    poStatement->Append( pszColumns );
+    poStatement->Append( " from " );
+    poStatement->Append( pszSchemaName );
+    poStatement->Append( "." );
+    poStatement->Append( pszTableName );
+
+    /* Append attribute query if we have it */
+    if( pszQuery != NULL )
+        poStatement->Appendf( " where (%s)", pszQuery );
+
+    /* If we have a spatial filter, query on it */
+    if ( m_poFilterGeom != NULL )
+    {
+        if (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
+            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+        {
+            if( pszQuery == NULL )
+                poStatement->Append( " where" );
+            else
+                poStatement->Append( " and" );
+
+            poStatement->Appendf(" [%s].STIntersects(", pszGeomColumn );
+
+            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+                poStatement->Append( "geography::" );
+            else
+                poStatement->Append( "geometry::" );
+            
+            if ( m_sFilterEnvelope.MinX == m_sFilterEnvelope.MaxX || 
+                 m_sFilterEnvelope.MinY == m_sFilterEnvelope.MaxY)
+                poStatement->Appendf("STGeomFromText('POINT(%.15g %.15g)',%d)) = 1", 
+                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY, nSRSId >= 0? nSRSId : 0);
+            else
+                poStatement->Appendf( "STGeomFromText('POLYGON((%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g,%.15g %.15g))',%d)) = 1", 
+                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY,
+                                            m_sFilterEnvelope.MaxX, m_sFilterEnvelope.MinY, 
+                                            m_sFilterEnvelope.MaxX, m_sFilterEnvelope.MaxY,
+                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MaxY,
+                                            m_sFilterEnvelope.MinX, m_sFilterEnvelope.MinY,
+                                            nSRSId >= 0? nSRSId : 0 );
+        }
+        else
+        {
+            CPLError( CE_Failure, CPLE_AppDefined, 
+                      "Spatial filter is supported only on geometry and geography column types." );
+            
+            delete poStatement;
+            return NULL;
+        }
+    }
+
+    CPLDebug( "OGR_MSSQLSpatial", "ExecuteSQL(%s)", poStatement->GetCommand() );
+    if( poStatement->ExecuteSQL() )
+        return poStatement;
+    else
+    {
+        delete poStatement;
+        return NULL;
+    }
+}
+
+/************************************************************************/
+/*                            ResetReading()                            */
+/************************************************************************/
+
+void OGRMSSQLSpatialTableLayer::ResetReading()
+
+{
+    ClearStatement();
+    OGRMSSQLSpatialLayer::ResetReading();
+}
+
+/************************************************************************/
+/*                             GetFeature()                             */
+/************************************************************************/
+
+OGRFeature *OGRMSSQLSpatialTableLayer::GetFeature( long nFeatureId )
+
+{
+    if( pszFIDColumn == NULL )
+        return OGRMSSQLSpatialLayer::GetFeature( nFeatureId );
+
+    ClearStatement();
+
+    iNextShapeId = nFeatureId;
+
+    poStmt = new CPLODBCStatement( poDS->GetSession() );
+    CPLString osFields = BuildFields();
+    poStmt->Appendf( "select %s from %s where %s = %ld", osFields.c_str(), 
+        poFeatureDefn->GetName(), pszFIDColumn, nFeatureId );
+
+    if( !poStmt->ExecuteSQL() )
+    {
+        delete poStmt;
+        poStmt = NULL;
+        return NULL;
+    }
+
+    return GetNextRawFeature();
+}
+
+/************************************************************************/
+/*                         SetAttributeFilter()                         */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::SetAttributeFilter( const char *pszQuery )
+
+{
+    CPLFree(m_pszAttrQueryString);
+    m_pszAttrQueryString = (pszQuery) ? CPLStrdup(pszQuery) : NULL;
+
+    if( (pszQuery == NULL && this->pszQuery == NULL)
+        || (pszQuery != NULL && this->pszQuery != NULL 
+            && EQUAL(pszQuery,this->pszQuery)) )
+        return OGRERR_NONE;
+
+    CPLFree( this->pszQuery );
+    this->pszQuery = (pszQuery) ? CPLStrdup( pszQuery ) : NULL;
+
+    ClearStatement();
+
+    return OGRERR_NONE;
+}
+
+
+/************************************************************************/
+/*                           TestCapability()                           */
+/************************************************************************/
+
+int OGRMSSQLSpatialTableLayer::TestCapability( const char * pszCap )
+
+{
+    if ( bUpdateAccess )
+    {
+        if( EQUAL(pszCap,OLCSequentialWrite) || EQUAL(pszCap,OLCCreateField)
+            || EQUAL(pszCap,OLCDeleteFeature) )
+            return TRUE;
+
+        else if( EQUAL(pszCap,OLCRandomWrite) )
+            return (pszFIDColumn != NULL);
+    }
+
+#if (ODBCVER >= 0x0300)
+    if( EQUAL(pszCap,OLCTransactions) )
+        return TRUE;
+#else
+    if( EQUAL(pszCap,OLCTransactions) )
+        return FALSE;
+#endif
+
+    if( EQUAL(pszCap,OLCIgnoreFields) )
+        return TRUE; 
+    
+    if( EQUAL(pszCap,OLCRandomRead) )
+        return (pszFIDColumn != NULL);
+    else if( EQUAL(pszCap,OLCFastFeatureCount) )
+        return TRUE;
+    else 
+        return OGRMSSQLSpatialLayer::TestCapability( pszCap );
+}
+
+/************************************************************************/
+/*                          GetFeatureCount()                           */
+/************************************************************************/
+
+int OGRMSSQLSpatialTableLayer::GetFeatureCount( int bForce )
+
+{
+    GetLayerDefn();
+
+    if( TestCapability(OLCFastFeatureCount) == FALSE )
+        return OGRMSSQLSpatialLayer::GetFeatureCount( bForce );
+
+    ClearStatement();
+        
+    CPLODBCStatement* poStatement = BuildStatement( "count(*)" );
+
+    if (poStatement == NULL || !poStatement->Fetch())
+    {
+        delete poStatement;
+        return OGRMSSQLSpatialLayer::GetFeatureCount( bForce );
+    }
+
+    int nRet = atoi(poStatement->GetColData( 0 ));
+    delete poStatement;
+    return nRet;
+}
+
+
+/************************************************************************/
+/*                            CreateField()                             */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::CreateField( OGRFieldDefn *poFieldIn, 
+                                         int bApproxOK )
+
+{
+    char                szFieldType[256];
+    OGRFieldDefn        oField( poFieldIn );
+
+    GetLayerDefn();
+
+/* -------------------------------------------------------------------- */
+/*      Do we want to "launder" the column names into MSSQL             */
+/*      friendly format?                                                */
+/* -------------------------------------------------------------------- */
+    if( bLaunderColumnNames )
+    {
+        char    *pszSafeName = poDS->LaunderName( oField.GetNameRef() );
+
+        oField.SetName( pszSafeName );
+        CPLFree( pszSafeName );
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Identify the MSSQL type.                                        */
+/* -------------------------------------------------------------------- */
+    
+    if( oField.GetType() == OFTInteger )
+    {
+        if( oField.GetWidth() > 0 && bPreservePrecision )
+            sprintf( szFieldType, "numeric(%d,0)", oField.GetWidth() );
+        else
+            strcpy( szFieldType, "int" );
+    }
+    else if( oField.GetType() == OFTReal )
+    {
+        if( oField.GetWidth() > 0 && oField.GetPrecision() > 0
+            && bPreservePrecision )
+            sprintf( szFieldType, "numeric(%d,%d)",
+                     oField.GetWidth(), oField.GetPrecision() );
+        else
+            strcpy( szFieldType, "float" );
+    }
+    else if( oField.GetType() == OFTString )
+    {
+        if( oField.GetWidth() == 0 || !bPreservePrecision )
+            strcpy( szFieldType, "varchar(MAX)" );
+        else
+            sprintf( szFieldType, "varchar(%d)", oField.GetWidth() );
+    }
+    else if( oField.GetType() == OFTDate )
+    {
+        strcpy( szFieldType, "date" );
+    }
+    else if( oField.GetType() == OFTTime )
+    {
+        strcpy( szFieldType, "time(7)" );
+    }
+    else if( oField.GetType() == OFTDateTime )
+    {
+        strcpy( szFieldType, "datetime" );
+    }
+    else if( oField.GetType() == OFTBinary )
+    {
+        strcpy( szFieldType, "image" );
+    }
+    else if( bApproxOK )
+    {
+        CPLError( CE_Warning, CPLE_NotSupported,
+                  "Can't create field %s with type %s on MSSQL layers.  Creating as varchar.",
+                  oField.GetNameRef(),
+                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
+        strcpy( szFieldType, "varchar" );
+    }
+    else
+    {
+        CPLError( CE_Failure, CPLE_NotSupported,
+                  "Can't create field %s with type %s on MSSQL layers.",
+                  oField.GetNameRef(),
+                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
+
+        return OGRERR_FAILURE;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Create the new field.                                           */
+/* -------------------------------------------------------------------- */
+    
+    CPLODBCStatement oStmt( poDS->GetSession() );
+            
+    oStmt.Appendf( "ALTER TABLE [%s].[%s] ADD [%s] %s", 
+        pszSchemaName, pszTableName, oField.GetNameRef(), szFieldType);
+
+    if( !oStmt.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                    "Error creating field %s, %s", oField.GetNameRef(), 
+                    poDS->GetSession()->GetLastError() );
+
+        return OGRERR_FAILURE;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Add the field to the OGRFeatureDefn.                            */
+/* -------------------------------------------------------------------- */
+
+    poFeatureDefn->AddFieldDefn( &oField );
+
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                             SetFeature()                             */
+/*                                                                      */
+/*      SetFeature() is implemented by an UPDATE SQL command            */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::SetFeature( OGRFeature *poFeature )
+
+{
+    OGRErr              eErr = OGRERR_FAILURE;
+
+    GetLayerDefn();
+
+    if( NULL == poFeature )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                  "NULL pointer to OGRFeature passed to SetFeature()." );
+        return eErr;
+    }
+
+    if( poFeature->GetFID() == OGRNullFID )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                  "FID required on features given to SetFeature()." );
+        return eErr;
+    }
+
+    if( !pszFIDColumn )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                  "Unable to update features in tables without\n"
+                  "a recognised FID column.");
+        return eErr;
+
+    }
+    
+    ClearStatement();
+
+/* -------------------------------------------------------------------- */
+/*      Form the UPDATE command.                                        */
+/* -------------------------------------------------------------------- */
+    CPLODBCStatement oStmt( poDS->GetSession() );
+            
+    oStmt.Appendf( "UPDATE [%s].[%s] SET ", pszSchemaName, pszTableName);
+
+    OGRMSSQLGeometryValidator oValidator(poFeature->GetGeometryRef());
+    OGRGeometry *poGeom = oValidator.GetValidGeometryRef();
+
+    if (poFeature->GetGeometryRef() != poGeom)
+    {
+        CPLError( CE_Warning, CPLE_NotSupported,
+                  "Geometry with FID = %ld has been modified.", poFeature->GetFID() );
+    }
+
+    int bNeedComma = FALSE;
+    if(pszGeomColumn != NULL)
+    {
+        char    *pszWKT = NULL;
+
+        if (poGeom != NULL)
+            poGeom->exportToWkt( &pszWKT );
+
+        oStmt.Appendf( "[%s] = ", pszGeomColumn );
+
+        if( pszWKT != NULL && (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
+            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY))
+        {
+            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+            {
+                oStmt.Append( "geography::STGeomFromText(" );
+                OGRMSSQLAppendEscaped(&oStmt, pszWKT);
+                oStmt.Appendf(",%d)", nSRSId );
+            }
+            else
+            {
+                oStmt.Append( "geometry::STGeomFromText(" );
+                OGRMSSQLAppendEscaped(&oStmt, pszWKT);
+                oStmt.Appendf(",%d).MakeValid()", nSRSId );
+            }
+        }
+        else
+            oStmt.Append( "null" );
+
+        bNeedComma = TRUE;
+        CPLFree(pszWKT);
+    }
+
+    int nFieldCount = poFeatureDefn->GetFieldCount();
+    int i;
+    for( i = 0; i < nFieldCount; i++ )
+    {
+        if (bNeedComma)
+            oStmt.Appendf( ", [%s] = ", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
+        else
+        {
+            oStmt.Appendf( "[%s] = ", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
+            bNeedComma = TRUE;
+        }
+
+        if( !poFeature->IsFieldSet( i ) )
+            oStmt.Append( "null" );
+        else
+            AppendFieldValue(&oStmt, poFeature, i);
+    }
+
+    /* Add the WHERE clause */
+    oStmt.Appendf( " WHERE [%s] = %ld" , pszFIDColumn, poFeature->GetFID());
+
+/* -------------------------------------------------------------------- */
+/*      Execute the update.                                             */
+/* -------------------------------------------------------------------- */
+
+    if( !oStmt.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+            "Error updating feature with FID:%ld, %s", poFeature->GetFID(), 
+                    poDS->GetSession()->GetLastError() );
+
+        return OGRERR_FAILURE;
+    }
+    
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                          DeleteFeature()                             */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::DeleteFeature( long nFID )
+
+{
+    GetLayerDefn();
+    
+    if( pszFIDColumn == NULL )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "DeleteFeature() without any FID column." );
+        return OGRERR_FAILURE;
+    }
+    
+    if( nFID == OGRNullFID )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "DeleteFeature() with unset FID fails." );
+        return OGRERR_FAILURE;
+    }
+    
+    ClearStatement();
+
+/* -------------------------------------------------------------------- */
+/*      Drop the record with this FID.                                  */
+/* -------------------------------------------------------------------- */
+    CPLODBCStatement oStatement( poDS->GetSession() );
+
+    oStatement.Appendf("DELETE FROM [%s] WHERE [%s] = %ld", 
+            poFeatureDefn->GetName(), pszFIDColumn, nFID);
+    
+    if( !oStatement.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "Attempt to delete feature with FID %ld failed. %s", 
+                  nFID, poDS->GetSession()->GetLastError() );
+
+        return OGRERR_FAILURE;
+    }
+    
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                           CreateFeature()                            */
+/************************************************************************/
+
+OGRErr OGRMSSQLSpatialTableLayer::CreateFeature( OGRFeature *poFeature )
+
+{
+    GetLayerDefn();
+
+    if( NULL == poFeature )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined,
+                  "NULL pointer to OGRFeature passed to CreateFeature()." );
+        return OGRERR_FAILURE;
+    }
+    
+    ClearStatement();
+
+    CPLODBCStatement oStatement( poDS->GetSession() );
+
+    /* the fid values are retieved from the source layer */
+    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL && bIsIdentityFid )
+        oStatement.Appendf("SET IDENTITY_INSERT [%s].[%s] ON;", pszSchemaName, pszTableName );
+
+/* -------------------------------------------------------------------- */
+/*      Form the INSERT command.                                        */
+/* -------------------------------------------------------------------- */
+
+    oStatement.Appendf( "INSERT INTO [%s].[%s] (", pszSchemaName, pszTableName );
+
+    OGRMSSQLGeometryValidator oValidator(poFeature->GetGeometryRef());
+    OGRGeometry *poGeom = oValidator.GetValidGeometryRef();
+
+    if (poFeature->GetGeometryRef() != poGeom)
+    {
+        CPLError( CE_Warning, CPLE_NotSupported,
+                  "Geometry with FID = %ld has been modified.", poFeature->GetFID() );
+    }
+
+    int bNeedComma = FALSE;
+
+    if (poGeom != NULL && pszGeomColumn != NULL)
+    {
+        oStatement.Append( pszGeomColumn );
+        bNeedComma = TRUE;
+    }
+
+    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
+    {
+        if (bNeedComma)
+            oStatement.Appendf( ", [%s]", pszFIDColumn );
+        else
+        {
+            oStatement.Appendf( "[%s]", pszFIDColumn );
+            bNeedComma = TRUE;
+        }
+    }
+
+    int nFieldCount = poFeatureDefn->GetFieldCount();
+    int i;
+    for( i = 0; i < nFieldCount; i++ )
+    {
+        if( !poFeature->IsFieldSet( i ) )
+            continue;
+
+        if (bNeedComma)
+            oStatement.Appendf( ", [%s]", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
+        else
+        {
+            oStatement.Appendf( "[%s]", poFeatureDefn->GetFieldDefn(i)->GetNameRef() );
+            bNeedComma = TRUE;
+        }
+    }
+
+    oStatement.Appendf( ") VALUES (" );
+
+    /* Set the geometry */
+    bNeedComma = FALSE;
+    if(poGeom != NULL && pszGeomColumn != NULL)
+    {
+        char    *pszWKT = NULL;
+    
+        //poGeom->setCoordinateDimension( nCoordDimension );
+
+        poGeom->exportToWkt( &pszWKT );
+
+        if( pszWKT != NULL && (nGeomColumnType == MSSQLCOLTYPE_GEOMETRY 
+            || nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY))
+        {
+            if (nGeomColumnType == MSSQLCOLTYPE_GEOGRAPHY)
+            {
+                oStatement.Append( "geography::STGeomFromText(" );
+                OGRMSSQLAppendEscaped(&oStatement, pszWKT);
+                oStatement.Appendf(",%d)", nSRSId );
+            }
+            else
+            {
+                oStatement.Append( "geometry::STGeomFromText(" );
+                OGRMSSQLAppendEscaped(&oStatement, pszWKT);
+                oStatement.Appendf(",%d).MakeValid()", nSRSId );
+            }     
+        }
+        else
+            oStatement.Append( "null" );
+
+        bNeedComma = TRUE;
+        CPLFree(pszWKT);
+    }
+
+    /* Set the FID */
+    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
+    {
+        if (bNeedComma)
+            oStatement.Appendf( ", %ld", poFeature->GetFID() );
+        else
+        {
+            oStatement.Appendf( "%ld", poFeature->GetFID() );
+            bNeedComma = TRUE;
+        }
+    }
+
+    for( i = 0; i < nFieldCount; i++ )
+    {
+        if( !poFeature->IsFieldSet( i ) )
+            continue;
+
+        if (bNeedComma)
+            oStatement.Append( ", " );
+        else
+            bNeedComma = TRUE;
+
+        AppendFieldValue(&oStatement, poFeature, i);
+    }
+
+    oStatement.Append( ");" );
+
+    if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL && bIsIdentityFid )
+        oStatement.Appendf("SET IDENTITY_INSERT [%s].[%s] OFF;", pszSchemaName, pszTableName );
+
+/* -------------------------------------------------------------------- */
+/*      Execute the insert.                                             */
+/* -------------------------------------------------------------------- */
+    
+    if( !oStatement.ExecuteSQL() )
+    {
+        CPLError( CE_Failure, CPLE_AppDefined, 
+                  "INSERT command for new feature failed. %s", 
+                   poDS->GetSession()->GetLastError() );
+
+        return OGRERR_FAILURE;
+    }
+
+    return OGRERR_NONE;
+}
+
+/************************************************************************/
+/*                          AppendFieldValue()                          */
+/*                                                                      */
+/* Used by CreateFeature() and SetFeature() to format a                 */
+/* non-empty field value                                                */
+/************************************************************************/
+
+void OGRMSSQLSpatialTableLayer::AppendFieldValue(CPLODBCStatement *poStatement,
+                                       OGRFeature* poFeature, int i)
+{
+    int nOGRFieldType = poFeatureDefn->GetFieldDefn(i)->GetType();
+
+    // We need special formatting for integer list values.
+    if(  nOGRFieldType == OFTIntegerList )
+    {
+        //TODO
+        poStatement->Append( "null" );
+        return;
+    }
+
+    // We need special formatting for real list values.
+    else if( nOGRFieldType == OFTRealList )
+    {
+        //TODO
+        poStatement->Append( "null" );
+        return;
+    }
+
+    // We need special formatting for string list values.
+    else if( nOGRFieldType == OFTStringList )
+    {
+        //TODO
+        poStatement->Append( "null" );
+        return;
+    }
+
+    // Binary formatting
+    if( nOGRFieldType == OFTBinary )
+    {
+        int nLen = 0;
+        GByte* pabyData = poFeature->GetFieldAsBinary( i, &nLen );
+        char* pszBytes = GByteArrayToHexString( pabyData, nLen);
+        poStatement->Append( pszBytes );
+        CPLFree(pszBytes);
+        return;
+    }
+
+    // Flag indicating NULL or not-a-date date value
+    // e.g. 0000-00-00 - there is no year 0
+    OGRBoolean bIsDateNull = FALSE;
+
+    const char *pszStrValue = poFeature->GetFieldAsString(i);
+
+    // Check if date is NULL: 0000-00-00
+    if( nOGRFieldType == OFTDate )
+    {
+        if( EQUALN( pszStrValue, "0000", 4 ) )
+        {
+            pszStrValue = "null";
+            bIsDateNull = TRUE;
+        }
+    }
+    else if ( nOGRFieldType == OFTReal )
+    {
+        char* pszComma = strchr((char*)pszStrValue, ',');
+        if (pszComma)
+            *pszComma = '.';
+    }
+
+    if( nOGRFieldType != OFTInteger && nOGRFieldType != OFTReal
+        && !bIsDateNull )
+    {
+        OGRMSSQLAppendEscaped(poStatement, pszStrValue);
+    }
+    else
+    {
+        poStatement->Append( pszStrValue );
+    }
+}
+
diff --git a/ogr/ogrsf_frmts/mysql/GNUmakefile b/ogr/ogrsf_frmts/mysql/GNUmakefile
index e78398d..292ae45 100644
--- a/ogr/ogrsf_frmts/mysql/GNUmakefile
+++ b/ogr/ogrsf_frmts/mysql/GNUmakefile
@@ -7,11 +7,6 @@ OBJ	=	ogrmysqldriver.o ogrmysqldatasource.o \
 
 CPPFLAGS	:=	-I.. -I../.. $(GDAL_INCLUDE) $(MYSQL_INC) $(CPPFLAGS)
 
-ifeq ($(MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION),yes)
-CPPFLAGS +=   -DMYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION
-endif
-
-
 default:	$(O_OBJ:.o=.$(OBJ_EXT))
 
 clean:
diff --git a/ogr/ogrsf_frmts/mysql/ogrmysqldatasource.cpp b/ogr/ogrsf_frmts/mysql/ogrmysqldatasource.cpp
index 749a299..a9055a8 100644
--- a/ogr/ogrsf_frmts/mysql/ogrmysqldatasource.cpp
+++ b/ogr/ogrsf_frmts/mysql/ogrmysqldatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmysqldatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrmysqldatasource.cpp 27506 2014-07-07 19:49:05Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRMySQLDataSource class.
@@ -37,17 +37,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-/* Recent versions of mysql no longer declare load_defaults() in my_sys.h */
-/* but they still have it in the lib. Very fragile... */
-#ifdef MYSQL_NEEDS_LOAD_DEFAULTS_DECLARATION
-extern "C" {
-int load_defaults(const char *conf_file, const char **groups,
-                  int *argc, char ***argv);
-void free_defaults(char **argv);
-}
-#endif
-
-CPL_CVSID("$Id: ogrmysqldatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrmysqldatasource.cpp 27506 2014-07-07 19:49:05Z rouault $");
 /************************************************************************/
 /*                         OGRMySQLDataSource()                         */
 /************************************************************************/
@@ -144,28 +134,6 @@ int OGRMySQLDataSource::Open( const char * pszNewName, int bUpdate,
     int nPort = 0, i;
     char **papszTableNames=NULL;
     std::string oHost, oPassword, oUser, oDB;
-    char *apszArgv[2] = { (char*) "org", NULL };
-    char **papszArgv = apszArgv;
-    int  nArgc = 1;
-    const char *client_groups[] = {"client", "ogr", NULL };
-
-    my_init(); // I hope there is no problem with calling this multiple times!
-    load_defaults( "my", client_groups, &nArgc, &papszArgv );
-
-    for( i = 0; i < nArgc; i++ )
-    {
-        if( EQUALN(papszArgv[i],"--user=",7) )
-            oUser = papszArgv[i] + 7;
-        else if( EQUALN(papszArgv[i],"--host=",7) )
-            oHost = papszArgv[i] + 7;
-        else if( EQUALN(papszArgv[i],"--password=",11) )
-            oPassword = papszArgv[i] + 11;
-        else if( EQUALN(papszArgv[i],"--port=",7) )
-            nPort = atoi(papszArgv[i] + 7);
-    }
-
-    // cleanup
-    free_defaults( papszArgv );
 
 /* -------------------------------------------------------------------- */
 /*      Parse out connection information.                               */
diff --git a/ogr/ogrsf_frmts/mysql/ogrmysqldriver.cpp b/ogr/ogrsf_frmts/mysql/ogrmysqldriver.cpp
index b2002df..6ed5381 100644
--- a/ogr/ogrsf_frmts/mysql/ogrmysqldriver.cpp
+++ b/ogr/ogrsf_frmts/mysql/ogrmysqldriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrmysqldriver.cpp 12396 2007-10-13 10:02:17Z rouault $
+ * $Id: ogrmysqldriver.cpp 27506 2014-07-07 19:49:05Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRMySQLDriver class.
@@ -29,8 +29,12 @@
 
 #include "ogr_mysql.h"
 #include "cpl_conv.h"
+#include "cpl_multiproc.h"
 
-CPL_CVSID("$Id: ogrmysqldriver.cpp 12396 2007-10-13 10:02:17Z rouault $");
+CPL_CVSID("$Id: ogrmysqldriver.cpp 27506 2014-07-07 19:49:05Z rouault $");
+
+static void* hMutex = NULL;
+static int   bInitialized = FALSE;
 
 /************************************************************************/
 /*                          ~OGRMySQLDriver()                           */
@@ -39,6 +43,16 @@ CPL_CVSID("$Id: ogrmysqldriver.cpp 12396 2007-10-13 10:02:17Z rouault $");
 OGRMySQLDriver::~OGRMySQLDriver()
 
 {
+    if( bInitialized )
+    {
+        mysql_library_end();
+        bInitialized = FALSE;
+    }
+    if( hMutex != NULL )
+    {
+        CPLDestroyMutex(hMutex);
+        hMutex = NULL;
+    }
 }
 
 /************************************************************************/
@@ -60,6 +74,21 @@ OGRDataSource *OGRMySQLDriver::Open( const char * pszFilename,
 
 {
     OGRMySQLDataSource     *poDS;
+ 
+    if( !EQUALN(pszFilename,"MYSQL:",6) )
+        return NULL;
+    {
+        CPLMutexHolderD(&hMutex);
+        if( !bInitialized )
+        {
+            if ( mysql_library_init( 0, NULL, NULL ) )
+            {
+                CPLError( CE_Failure, CPLE_AppDefined, "Could not initialize MySQL library" );
+                return NULL;
+            }
+            bInitialized = TRUE;
+        }
+    }
 
     poDS = new OGRMySQLDataSource();
 
diff --git a/ogr/ogrsf_frmts/nas/drv_nas.html b/ogr/ogrsf_frmts/nas/drv_nas.html
index 50e3161..af833aa 100644
--- a/ogr/ogrsf_frmts/nas/drv_nas.html
+++ b/ogr/ogrsf_frmts/nas/drv_nas.html
@@ -1,6 +1,6 @@
 <html>
 <head>
-<title>NAS - Geography Markup Language</title>
+<title>NAS - Normbasierte AustauschSchnittstelle</title>
 </head>
 
 <body bgcolor="#ffffff">
@@ -11,7 +11,7 @@ The NAS reader reads the NAS/ALKIS format used for cadastral data in Germany.
 The format is a GML profile with fairly complex GML3 objects not easily read
 with the general OGR GML driver. <p>
 
-This driver depends on GDAL/OGR being built with the Xerces XML parsing 
+This driver depends on GDAL/OGR being built with the Xerces XML parsing
 library.<p>
 
 This driver was implemented within the context of the PostNAS project
diff --git a/ogr/ogrsf_frmts/nas/nashandler.cpp b/ogr/ogrsf_frmts/nas/nashandler.cpp
index 2589148..ef701ec 100644
--- a/ogr/ogrsf_frmts/nas/nashandler.cpp
+++ b/ogr/ogrsf_frmts/nas/nashandler.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: nashandler.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nashandler.cpp 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  NAS Reader
  * Purpose:  Implementation of NASHandler class.
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
 
@@ -35,6 +35,42 @@
 
 #define MAX_TOKEN_SIZE  1000
 
+/*
+  Update modes:
+
+       <geaenderteObjekte>
+                <wfs:Transaction version="1.0.0" service="WFS">
+                        <wfs:Delete typeName="AX_BesondereFlurstuecksgrenze">
+                                <ogc:Filter>
+                                        <ogc:FeatureId fid="DENW18AL0000nANA20120117T130819Z" />
+                                </ogc:Filter>
+                        </wfs:Delete>
+                        <wfsext:Replace vendorId="AdV" safeToIgnore="false">
+                                <AP_PTO gml:id="DENW18AL0000pewY20131011T071138Z">
+                                       [...]
+                                </AP_PTO>
+                                <ogc:Filter>
+                                        <ogc:FeatureId fid="DENW18AL0000pewY20120117T143330Z" />
+                                </ogc:Filter>
+                        </wfsext:Replace>
+                        <wfs:Update typeName="AX_KommunalesGebiet">
+                                <wfs:Property>
+                                        <wfs:Name>adv:lebenszeitintervall/adv:AA_Lebenszeitintervall/adv:endet</wfs:Name>
+                                        <wfs:Value>2012-08-14T12:32:30Z</wfs:Value>
+                                </wfs:Property>
+                                <wfs:Property>
+                                        <wfs:Name>adv:anlass</wfs:Name>
+                                        <wfs:Value>000000</wfs:Value>
+                                </wfs:Property>
+                                <ogc:Filter>
+                                        <ogc:FeatureId fid="DENW11AL000062WD20111016T122010Z" />
+                                </ogc:Filter>
+                        </wfs:Update>
+                </wfs:Transaction>
+        </geaenderteObjekte>
+*/
+
+
 /************************************************************************/
 /*                             NASHandler()                             */
 /************************************************************************/
@@ -48,6 +84,8 @@ NASHandler::NASHandler( NASReader *poReader )
     m_nGeomAlloc = m_nGeomLen = 0;
     m_nDepthFeature = m_nDepthElement = m_nDepth = 0;
     m_bIgnoreFeature = FALSE;
+    m_bInUpdate = FALSE;
+    m_bInUpdateProperty = FALSE;
 }
 
 /************************************************************************/
@@ -178,13 +216,13 @@ void NASHandler::startElement(const XMLCh* const    uri,
     }
 
 /* -------------------------------------------------------------------- */
-/*      Is this the ogc:Filter element in a wfs:Delete or               */
-/*      wfsext:Replace operation?  If so we translate it as a           */
+/*      Is this the ogc:Filter element in a update operation            */
+/*      (wfs:Delete, wfsext:Replace or wfs:Update)?                     */
 /*      specialized sort of feature.                                    */
 /* -------------------------------------------------------------------- */
     else if( EQUAL(szElementName,"Filter")
              && (pszLast = m_poReader->GetState()->GetLastComponent()) != NULL
-             && (EQUAL(pszLast,"Delete") || EQUAL(pszLast,"Replace")) )
+             && (EQUAL(pszLast,"Delete") || EQUAL(pszLast,"Replace") || EQUAL(pszLast,"Update")) )
     {
         const char* pszFilteredClassName = m_poReader->GetFilteredClassName();
         if ( pszFilteredClassName != NULL &&
@@ -215,6 +253,15 @@ void NASHandler::startElement(const XMLCh* const    uri,
             m_poReader->SetFeaturePropertyDirectly( "replacedBy", CPLStrdup(m_osLastReplacingFID) );
             m_poReader->SetFeaturePropertyDirectly( "safeToIgnore", CPLStrdup(m_osLastSafeToIgnore) );
         }
+        else if( EQUAL( pszLast, "Update" ) )
+        {
+            CPLAssert( m_osLastEnded != "" );
+            CPLAssert( m_osLastOccasion != "" );
+            m_poReader->SetFeaturePropertyDirectly( "endet", CPLStrdup(m_osLastEnded) );
+            m_poReader->SetFeaturePropertyDirectly( "anlass", CPLStrdup(m_osLastOccasion) );
+            m_osLastEnded = "";
+            m_osLastOccasion = "";
+        }
 
         return;
     }
@@ -272,11 +319,11 @@ void NASHandler::startElement(const XMLCh* const    uri,
     }
 
 /* -------------------------------------------------------------------- */
-/*      If it is the wfs:Delete element, then remember the typeName     */
-/*      attribute so we can assign it to the feature that will be       */
-/*      produced when we process the Filter element.                    */
+/*      If it is the wfs:Delete or wfs:Update element, then remember    */
+/*      the typeName attribute so we can assign it to the feature that  */
+/*      will be produced when we process the Filter element.            */
 /* -------------------------------------------------------------------- */
-    else if( EQUAL(szElementName,"Delete") )
+    else if( EQUAL(szElementName,"Delete") || EQUAL(szElementName,"Update") )
     {
         int nIndex;
         XMLCh  Name[100];
@@ -293,6 +340,23 @@ void NASHandler::startElement(const XMLCh* const    uri,
 
         m_osLastSafeToIgnore = "";
         m_osLastReplacingFID = "";
+
+        if( EQUAL(szElementName,"Update") )
+        {
+            m_bInUpdate = TRUE;
+        }
+    }
+
+    else if ( m_bInUpdate && EQUAL(szElementName, "Property") )
+    {
+        m_bInUpdateProperty = TRUE;
+    }
+
+    else if ( m_bInUpdateProperty && ( EQUAL(szElementName, "Name" ) || EQUAL(szElementName, "Value" ) ) )
+    {
+        // collect attribute name or value
+        CPLFree( m_pszCurField );
+        m_pszCurField = CPLStrdup("");
     }
 
 /* -------------------------------------------------------------------- */
@@ -333,7 +397,7 @@ void NASHandler::startElement(const XMLCh* const    uri,
         m_pszCurField = CPLStrdup("");
 
         // Capture href as OB property.
-        m_poReader->CheckForRelations( szElementName, attrs );
+        m_poReader->CheckForRelations( szElementName, attrs, &m_pszCurField );
 
         // Capture "fid" attribute as part of the property value -
         // primarily this is for wfs:Delete operation's FeatureId attribute.
@@ -359,6 +423,7 @@ void NASHandler::endElement(const   XMLCh* const    uri,
 {
     char        szElementName[MAX_TOKEN_SIZE];
     GMLReadState *poState = m_poReader->GetState();
+    const char  *pszLast;
 
     tr_strcpy( szElementName, localname );
 
@@ -394,6 +459,54 @@ void NASHandler::endElement(const   XMLCh* const    uri,
             );
 #endif
 
+   if( m_bInUpdateProperty )
+   {
+       if( EQUAL( szElementName, "Name" ) )
+       {
+           CPLAssert( m_osLastPropertyName == "" );
+           m_osLastPropertyName = m_pszCurField;
+           m_pszCurField = NULL;
+       }
+       else if( EQUAL( szElementName, "Value" ) )
+       {
+           CPLAssert( m_osLastPropertyValue == "" );
+           m_osLastPropertyValue = m_pszCurField;
+           m_pszCurField = NULL;
+       }
+       else if( EQUAL( szElementName, "Property" ) )
+       {
+           if( EQUAL( m_osLastPropertyName, "adv:lebenszeitintervall/adv:AA_Lebenszeitintervall/adv:endet" ) )
+           {
+               CPLAssert( m_osLastPropertyValue != "" );
+               m_osLastEnded = m_osLastPropertyValue;
+           }
+           else if( EQUAL( m_osLastPropertyName, "adv:anlass" ) )
+           {
+               CPLAssert( m_osLastPropertyValue != "" );
+               m_osLastOccasion = m_osLastPropertyValue;
+           }
+           else
+           {
+               CPLError( CE_Warning, CPLE_AppDefined,
+                         "NAS: Expected property name or value instead of %s",
+                         m_osLastPropertyName.c_str() );
+           }
+
+           m_osLastPropertyName = "";
+           m_osLastPropertyValue = "";
+           m_bInUpdateProperty = FALSE;
+       }
+
+       poState->PopPath();
+
+       return;
+   }
+
+   if ( m_bInUpdate && EQUAL( szElementName, "Update" ) )
+   {
+       m_bInUpdate = FALSE;
+   }
+
 /* -------------------------------------------------------------------- */
 /*      Is this closing off an attribute value?  We assume so if        */
 /*      we are collecting an attribute value and got to this point.     */
@@ -437,7 +550,7 @@ void NASHandler::endElement(const   XMLCh* const    uri,
                 CPLXMLNode* psNode = CPLParseXMLString(m_pszGeometry);
                 if (psNode)
                 {
-                    /* workaround common malformed gml:pos with just a
+                    /* workaround for common malformed gml:pos with just a
                      * elevation value instead of a full 3D coordinate:
                      *
                      * <gml:Point gml:id="BII2H">
@@ -468,7 +581,7 @@ void NASHandler::endElement(const   XMLCh* const    uri,
 
                         CPLFree( pszOldGeom );
 #else
-            		CPLError( CE_Warning, CPLE_AppDefined, "NAS: Overwriting other geometry (%s)",
+                        CPLError( CE_Warning, CPLE_AppDefined, "NAS: Overwriting other geometry (%s)",
                                  poIdProp && poIdProp->nSubProperties>0 && poIdProp->papszSubProperties[0] ? poIdProp->papszSubProperties[0] : "(null)" );
 #endif
                     }
@@ -501,14 +614,14 @@ void NASHandler::endElement(const   XMLCh* const    uri,
     }
 
 /* -------------------------------------------------------------------- */
-/*      Ends of a wfs:Delete should be triggered on the close of the    */
-/*      <Filter> element.                                               */
+/*      Ends of a wfs:Delete or wfs:Update should be triggered on the   */
+/*      close of the <Filter> element.                                  */
 /* -------------------------------------------------------------------- */
     else if( m_nDepth == m_nDepthFeature
              && poState->m_poFeature != NULL
              && EQUAL(szElementName,"Filter")
-             && EQUAL(poState->m_poFeature->GetClass()->GetElementName(),
-                      "Delete") )
+             && (pszLast=poState->m_poFeature->GetClass()->GetElementName()) != NULL
+             && ( EQUAL(pszLast, "Delete") || EQUAL(pszLast, "Update") ) )
     {
         m_nDepthFeature = 0;
         m_poReader->PopState();
@@ -632,3 +745,5 @@ int NASHandler::IsGeometryElement( const char *pszElement )
         || strcmp(pszElement,"PolygonPatch") == 0
         || strcmp(pszElement,"LineString") == 0;
 }
+
+// vim: set sw=4 expandtab :
diff --git a/ogr/ogrsf_frmts/nas/nasreader.cpp b/ogr/ogrsf_frmts/nas/nasreader.cpp
index b3abc61..2e1dcdd 100644
--- a/ogr/ogrsf_frmts/nas/nasreader.cpp
+++ b/ogr/ogrsf_frmts/nas/nasreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nasreader.cpp 27132 2014-04-05 21:48:58Z rouault $
+ * $Id: nasreader.cpp 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  NAS Reader
  * Purpose:  Implementation of NASReader class.
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
 
@@ -76,7 +76,7 @@ NASReader::NASReader()
     m_poNASHandler = NULL;
     m_poSAXReader = NULL;
     m_bReadStarted = FALSE;
-    
+
     m_poState = NULL;
     m_poCompleteFeature = NULL;
 
@@ -141,11 +141,11 @@ int NASReader::SetupParser()
         {
             XMLPlatformUtils::Initialize();
         }
-        
+
         catch (const XMLException& toCatch)
         {
             CPLError( CE_Warning, CPLE_AppDefined,
-                      "Exception initializing Xerces based GML reader.\n%s", 
+                      "Exception initializing Xerces based GML reader.\n%s",
                       tr_strdup(toCatch.getMessage()) );
             bXercesInitialized = FALSE;
             return FALSE;
@@ -166,7 +166,7 @@ int NASReader::SetupParser()
 
     try{
         m_poSAXReader = XMLReaderFactory::createXMLReader();
-    
+
         m_poNASHandler = new NASHandler( this );
 
         m_poSAXReader->setContentHandler( m_poNASHandler );
@@ -264,7 +264,7 @@ GMLFeature *NASReader::NextFeature()
             m_bReadStarted = TRUE;
         }
 
-        while( m_poCompleteFeature == NULL 
+        while( m_poCompleteFeature == NULL
                && m_poSAXReader->parseNext( m_oToFill ) ) {}
 
         poReturn = m_poCompleteFeature;
@@ -273,8 +273,8 @@ GMLFeature *NASReader::NextFeature()
     }
     catch (const XMLException& toCatch)
     {
-        CPLDebug( "NAS", 
-                  "Error during NextFeature()! Message:\n%s", 
+        CPLDebug( "NAS",
+                  "Error during NextFeature()! Message:\n%s",
                   tr_strdup( toCatch.getMessage() ) );
     }
 
@@ -291,7 +291,7 @@ GMLFeature *NASReader::NextFeature()
 /*      pushed onto the readstate stack.                                */
 /************************************************************************/
 
-void NASReader::PushFeature( const char *pszElement, 
+void NASReader::PushFeature( const char *pszElement,
                              const Attributes &attrs )
 
 {
@@ -365,10 +365,10 @@ int NASReader::IsFeatureElement( const char *pszElement )
     const char *pszLast = m_poState->GetLastComponent();
     int        nLen = strlen(pszLast);
 
-    // There seem to be two major NAS classes of feature identifiers 
-    // -- either a wfs:Insert or a gml:featureMember. 
+    // There seem to be two major NAS classes of feature identifiers
+    // -- either a wfs:Insert or a gml:featureMember.
 
-    if( (nLen < 6 || !EQUAL(pszLast+nLen-6,"Insert")) 
+    if( (nLen < 6 || !EQUAL(pszLast+nLen-6,"Insert"))
         && (nLen < 13 || !EQUAL(pszLast+nLen-13,"featureMember"))
         && (nLen < 7 || !EQUAL(pszLast+nLen-7,"Replace")) )
         return FALSE;
@@ -830,7 +830,7 @@ int NASReader::SaveClasses( const char *pszFile )
     char        *pszWholeText = CPLSerializeXMLTree( psRoot );
 
     CPLDestroyXMLNode( psRoot );
- 
+
     fp = VSIFOpen( pszFile, "wb" );
 
     if( fp == NULL )
@@ -898,7 +898,7 @@ int NASReader::PrescanForSchema( int bGetExtents, int bAnalyzeSRSPerFeature )
                 if( poClass->GetGeometryPropertyCount() == 0 )
                     poClass->AddGeometryProperty( new GMLGeometryPropertyDefn( "", "", wkbUnknown ) );
 
-                OGRwkbGeometryType eGType = (OGRwkbGeometryType) 
+                OGRwkbGeometryType eGType = (OGRwkbGeometryType)
                     poClass->GetGeometryProperty(0)->GetType();
 
                 // Merge SRSName into layer.
@@ -1000,7 +1000,8 @@ void NASReader::CheckForFID( const Attributes &attrs,
 /************************************************************************/
 
 void NASReader::CheckForRelations( const char *pszElement,
-                                   const Attributes &attrs )
+                                   const Attributes &attrs,
+                                   char **ppszCurField )
 
 {
     GMLFeature *poFeature = GetState()->m_poFeature;
@@ -1018,7 +1019,12 @@ void NASReader::CheckForRelations( const char *pszElement,
         char *pszHRef = tr_strdup( attrs.getValue( nIndex ) );
 
         if( EQUALN(pszHRef,"urn:adv:oid:", 12 ) )
+        {
             poFeature->AddOBProperty( pszElement, pszHRef );
+            if( ppszCurField && *ppszCurField )
+                CPLFree( *ppszCurField );
+            *ppszCurField = CPLStrdup( pszHRef + 12 );
+        }
 
         CPLFree( pszHRef );
     }
diff --git a/ogr/ogrsf_frmts/nas/nasreaderp.h b/ogr/ogrsf_frmts/nas/nasreaderp.h
index 5bd38df..605c3c3 100644
--- a/ogr/ogrsf_frmts/nas/nasreaderp.h
+++ b/ogr/ogrsf_frmts/nas/nasreaderp.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: nasreaderp.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: nasreaderp.h 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  NAS Reader
  * Purpose:  Private Declarations for OGR NAS Reader code.
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
 
@@ -48,7 +48,7 @@ CPL_C_END
 /************************************************************************/
 /*                              NASHandler                              */
 /************************************************************************/
-class NASHandler : public DefaultHandler 
+class NASHandler : public DefaultHandler
 {
     NASReader  *m_poReader;
 
@@ -64,17 +64,23 @@ class NASHandler : public DefaultHandler
     int        m_nDepth;
     int        m_nDepthFeature;
     int        m_bIgnoreFeature;
+    int        m_bInUpdate;
+    int        m_bInUpdateProperty;
     int        m_nDepthElement;
     CPLString  m_osIgnoredElement;
 
     CPLString  m_osLastTypeName;
     CPLString  m_osLastReplacingFID;
     CPLString  m_osLastSafeToIgnore;
+    CPLString  m_osLastPropertyName;
+    CPLString  m_osLastPropertyValue;
+    CPLString  m_osLastEnded;
+    CPLString  m_osLastOccasion;
 
 public:
     NASHandler( NASReader *poReader );
     virtual ~NASHandler();
-    
+
     void startElement(
         const   XMLCh* const    uri,
         const   XMLCh* const    localname,
@@ -104,7 +110,7 @@ public:
 /************************************************************************/
 
 // for now, use existing gmlreadstate.
-#ifdef notdef 
+#ifdef notdef
 class GMLReadState
 {
     void        RebuildPath();
@@ -134,7 +140,7 @@ public:
 /*                              NASReader                               */
 /************************************************************************/
 
-class NASReader : public IGMLReader 
+class NASReader : public IGMLReader
 {
 private:
     int           m_bClassListLocked;
@@ -196,7 +202,7 @@ public:
                                        int bSqliteIsTempFile,
                                        int iSqliteCacheMB );
 
-// --- 
+// ---
 
     GMLReadState     *GetState() const { return m_poState; }
     void             PopState();
@@ -205,7 +211,7 @@ public:
     int         IsFeatureElement( const char *pszElement );
     int         IsAttributeElement( const char *pszElement );
 
-    void        PushFeature( const char *pszElement, 
+    void        PushFeature( const char *pszElement,
                              const Attributes &attrs );
 
     void        SetFeaturePropertyDirectly( const char *pszElement,
@@ -214,8 +220,9 @@ public:
     int         HasStoppedParsing() { return FALSE; }
 
     void        CheckForFID( const Attributes &attrs, char **ppszCurField );
-    void        CheckForRelations( const char *pszElement, 
-                                   const Attributes &attrs );
+    void        CheckForRelations( const char *pszElement,
+                                   const Attributes &attrs,
+                                   char **ppszCurField );
 
     virtual const char* GetGlobalSRSName() { return NULL; }
 
diff --git a/ogr/ogrsf_frmts/nas/ogr_nas.h b/ogr/ogrsf_frmts/nas/ogr_nas.h
index 0e6e4cf..a4515c7 100644
--- a/ogr/ogrsf_frmts/nas/ogr_nas.h
+++ b/ogr/ogrsf_frmts/nas/ogr_nas.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_nas.h 26466 2013-09-14 09:07:46Z rouault $
+ * $Id: ogr_nas.h 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  NAS Reader
  * Purpose:  Declarations for OGR wrapper classes for NAS, and NAS<->OGR
@@ -15,16 +15,16 @@
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  * DEALINGS IN THE SOFTWARE.
  ****************************************************************************/
 
@@ -55,8 +55,8 @@ class OGRNASLayer : public OGRLayer
     GMLFeatureClass     *poFClass;
 
   public:
-                        OGRNASLayer( const char * pszName, 
-                                     OGRSpatialReference *poSRS, 
+                        OGRNASLayer( const char * pszName,
+                                     OGRSpatialReference *poSRS,
                                      OGRwkbGeometryType eType,
                                      OGRNASDataSource *poDS );
 
@@ -98,8 +98,8 @@ class OGRNASRelationLayer : public OGRLayer
     int                 TestCapability( const char * );
 
     // For use populating.
-    void                AddRelation( const char *pszFromID, 
-                                     const char *pszType, 
+    void                AddRelation( const char *pszFromID,
+                                     const char *pszType,
                                      const char *pszToID );
     void                MarkRelationsPopulated() { bPopulated = TRUE; }
 };
@@ -112,11 +112,11 @@ class OGRNASDataSource : public OGRDataSource
 {
     OGRLayer          **papoLayers;
     int                 nLayers;
-    
+
     OGRNASRelationLayer *poRelationLayer;
 
     char                *pszName;
-    
+
     OGRNASLayer         *TranslateNASSchema( GMLFeatureClass * );
 
     // input related parameters.
@@ -152,7 +152,7 @@ class OGRNASDriver : public OGRSFDriver
 {
   public:
                 ~OGRNASDriver();
-                
+
     const char *GetName();
     OGRDataSource *Open( const char *, int );
 
diff --git a/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp b/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp
index bb59202..67e22ed 100644
--- a/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp
+++ b/ogr/ogrsf_frmts/nas/ogrnasdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrnasdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrnasdatasource.cpp 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  OGR
  * Purpose:  Implements OGRNASDataSource class.
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrnasdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrnasdatasource.cpp 27713 2014-09-21 15:51:47Z jef $");
 
 static const char *apszURNNames[] =
 {
@@ -269,7 +269,7 @@ OGRNASLayer *OGRNASDataSource::TranslateNASSchema( GMLFeatureClass *poClass )
 {
     OGRNASLayer *poLayer;
     OGRwkbGeometryType eGType = wkbNone;
-    
+
     if( poClass->GetGeometryPropertyCount() != 0 )
     {
         eGType = (OGRwkbGeometryType) poClass->GetGeometryProperty(0)->GetType();
diff --git a/ogr/ogrsf_frmts/nas/ogrnaslayer.cpp b/ogr/ogrsf_frmts/nas/ogrnaslayer.cpp
index e7a69e1..64a89fa 100644
--- a/ogr/ogrsf_frmts/nas/ogrnaslayer.cpp
+++ b/ogr/ogrsf_frmts/nas/ogrnaslayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrnaslayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrnaslayer.cpp 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  OGR
  * Purpose:  Implements OGRNASLayer class.
@@ -33,7 +33,7 @@
 #include "cpl_port.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrnaslayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrnaslayer.cpp 27713 2014-09-21 15:51:47Z jef $");
 
 /************************************************************************/
 /*                           OGRNASLayer()                              */
@@ -254,7 +254,7 @@ OGRFeature *OGRNASLayer::GetNextFeature()
             int iId = poNASFeature->GetClass()->GetPropertyIndex( "gml_id" );
             const GMLProperty *poIdProp = poNASFeature->GetProperty(iId);
             CPLError( CE_Warning, CPLE_AppDefined, "NAS: could not set geometry (gml_id:%s)",
-		      poIdProp && poIdProp->nSubProperties>0 && poIdProp->papszSubProperties[0] ? poIdProp->papszSubProperties[0] : "(null)" );
+                      poIdProp && poIdProp->nSubProperties>0 && poIdProp->papszSubProperties[0] ? poIdProp->papszSubProperties[0] : "(null)" );
         }
 
         delete poNASFeature;
@@ -290,7 +290,7 @@ OGRErr OGRNASLayer::GetExtent(OGREnvelope *psExtent, int bForce )
 {
     double dfXMin, dfXMax, dfYMin, dfYMax;
 
-    if( poFClass != NULL && 
+    if( poFClass != NULL &&
         poFClass->GetExtents( &dfXMin, &dfXMax, &dfYMin, &dfYMax ) )
     {
         psExtent->MinX = dfXMin;
@@ -300,7 +300,7 @@ OGRErr OGRNASLayer::GetExtent(OGREnvelope *psExtent, int bForce )
 
         return OGRERR_NONE;
     }
-    else 
+    else
         return OGRLayer::GetExtent( psExtent, bForce );
 }
 
@@ -323,8 +323,8 @@ int OGRNASLayer::TestCapability( const char * pszCap )
 
     else if( EQUAL(pszCap,OLCFastFeatureCount) )
     {
-        if( poFClass == NULL 
-            || m_poFilterGeom != NULL 
+        if( poFClass == NULL
+            || m_poFilterGeom != NULL
             || m_poAttrQuery != NULL )
             return FALSE;
 
@@ -334,6 +334,6 @@ int OGRNASLayer::TestCapability( const char * pszCap )
     else if( EQUAL(pszCap,OLCStringsAsUTF8) )
         return TRUE;
 
-    else 
+    else
         return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/nas/ogrnasrelationlayer.cpp b/ogr/ogrsf_frmts/nas/ogrnasrelationlayer.cpp
index df1a603..f93015c 100644
--- a/ogr/ogrsf_frmts/nas/ogrnasrelationlayer.cpp
+++ b/ogr/ogrsf_frmts/nas/ogrnasrelationlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrnasrelationlayer.cpp 24105 2012-03-10 12:08:04Z rouault $
+ * $Id: ogrnasrelationlayer.cpp 27713 2014-09-21 15:51:47Z jef $
  *
  * Project:  OGR
  * Purpose:  Implements OGRNASRelationLayer class, a special layer holding all
@@ -33,7 +33,7 @@
 #include "cpl_port.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrnasrelationlayer.cpp 24105 2012-03-10 12:08:04Z rouault $");
+CPL_CVSID("$Id: ogrnasrelationlayer.cpp 27713 2014-09-21 15:51:47Z jef $");
 
 /************************************************************************/
 /*                        OGRNASRelationLayer()                         */
@@ -175,7 +175,7 @@ int OGRNASRelationLayer::TestCapability( const char * pszCap )
     else if( EQUAL(pszCap,OLCStringsAsUTF8) )
         return TRUE;
 
-    else 
+    else
         return FALSE;
 }
 
@@ -190,7 +190,7 @@ void OGRNASRelationLayer::AddRelation( const char *pszFromID,
 {
     int nMergedLen = strlen(pszFromID) + strlen(pszType) + strlen(pszToID) + 3;
     char *pszMerged = (char *) CPLMalloc(nMergedLen);
-    
+
     strcpy( pszMerged, pszFromID );
     strcpy( pszMerged + strlen(pszFromID) + 1, pszType );
     strcpy( pszMerged + strlen(pszFromID) + strlen(pszType) + 2, pszToID );
diff --git a/ogr/ogrsf_frmts/ntf/ntf_estlayers.cpp b/ogr/ogrsf_frmts/ntf/ntf_estlayers.cpp
index 67cb36b..6a4fcc9 100644
--- a/ogr/ogrsf_frmts/ntf/ntf_estlayers.cpp
+++ b/ogr/ogrsf_frmts/ntf/ntf_estlayers.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ntf_estlayers.cpp 26466 2013-09-14 09:07:46Z rouault $
+ * $Id: ntf_estlayers.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NTF Translator
  * Purpose:  NTFFileReader methods related to establishing the schemas
@@ -33,7 +33,7 @@
 #include "ntf.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ntf_estlayers.cpp 26466 2013-09-14 09:07:46Z rouault $");
+CPL_CVSID("$Id: ntf_estlayers.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define MAX_LINK        5000
 
@@ -312,7 +312,7 @@ static OGRFeature *TranslateOscarRouteLine( NTFFileReader *poReader,
 /*                       TranslateOscarComment()                        */
 /************************************************************************/
 
-static OGRFeature *TranslateOscarComment( NTFFileReader *poReader,
+static OGRFeature *TranslateOscarComment( CPL_UNUSED NTFFileReader *poReader,
                                           OGRNTFLayer *poLayer,
                                           NTFRecord **papoGroup )
 
@@ -1144,7 +1144,7 @@ static OGRFeature *TranslateMeridian2Line( NTFFileReader *poReader,
 /*      Also used for Meridian, Oscar and BaseData.GB nodes.            */
 /************************************************************************/
 
-static OGRFeature *TranslateStrategiNode( NTFFileReader *poReader,
+static OGRFeature *TranslateStrategiNode( CPL_UNUSED NTFFileReader *poReader,
                                           OGRNTFLayer *poLayer,
                                           NTFRecord **papoGroup )
 
diff --git a/ogr/ogrsf_frmts/ntf/ntf_raster.cpp b/ogr/ogrsf_frmts/ntf/ntf_raster.cpp
index 2633824..8f5155c 100644
--- a/ogr/ogrsf_frmts/ntf/ntf_raster.cpp
+++ b/ogr/ogrsf_frmts/ntf/ntf_raster.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ntf_raster.cpp 26466 2013-09-14 09:07:46Z rouault $
+ * $Id: ntf_raster.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  NTF Translator
  * Purpose:  Handle UK Ordnance Survey Raster DTM products.  Includes some
@@ -31,7 +31,7 @@
 
 #include "ntf.h"
 
-CPL_CVSID("$Id: ntf_raster.cpp 26466 2013-09-14 09:07:46Z rouault $");
+CPL_CVSID("$Id: ntf_raster.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -401,8 +401,7 @@ OGRFeature *OGRNTFRasterLayer::GetFeature( long nFeatureId )
 /*      way of counting features matching a spatial query.              */
 /************************************************************************/
 
-int OGRNTFRasterLayer::GetFeatureCount( int bForce )
-
+int OGRNTFRasterLayer::GetFeatureCount( CPL_UNUSED int bForce )
 {
     return nFeatureCount;
 }
diff --git a/ogr/ogrsf_frmts/ntf/ogrntffeatureclasslayer.cpp b/ogr/ogrsf_frmts/ntf/ogrntffeatureclasslayer.cpp
index 611af64..65634b6 100644
--- a/ogr/ogrsf_frmts/ntf/ogrntffeatureclasslayer.cpp
+++ b/ogr/ogrsf_frmts/ntf/ogrntffeatureclasslayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrntffeatureclasslayer.cpp 10645 2007-01-18 02:22:39Z warmerdam $
+ * $Id: ogrntffeatureclasslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  UK NTF Reader
  * Purpose:  Implements OGRNTFFeatureClassLayer class.
@@ -30,7 +30,7 @@
 #include "ntf.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrntffeatureclasslayer.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
+CPL_CVSID("$Id: ogrntffeatureclasslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                      OGRNTFFeatureClassLayer()                       */
@@ -155,8 +155,7 @@ OGRFeature *OGRNTFFeatureClassLayer::GetFeature( long nFeatureId )
 /*      way of counting features matching a spatial query.              */
 /************************************************************************/
 
-int OGRNTFFeatureClassLayer::GetFeatureCount( int bForce )
-
+int OGRNTFFeatureClassLayer::GetFeatureCount( CPL_UNUSED int bForce )
 {
     return poDS->GetFCCount();
 }
diff --git a/ogr/ogrsf_frmts/oci/ogrocisession.cpp b/ogr/ogrsf_frmts/oci/ogrocisession.cpp
index d256147..9e2b2c9 100644
--- a/ogr/ogrsf_frmts/oci/ogrocisession.cpp
+++ b/ogr/ogrsf_frmts/oci/ogrocisession.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrocisession.cpp 22346 2011-05-10 03:02:15Z warmerdam $
+ * $Id: ogrocisession.cpp 27575 2014-08-06 19:40:30Z ilucena $
  *
  * Project:  Oracle Spatial Driver
  * Purpose:  Implementation of OGROCISession, which encapsulates much of the
@@ -31,7 +31,7 @@
 #include "ogr_oci.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrocisession.cpp 22346 2011-05-10 03:02:15Z warmerdam $");
+CPL_CVSID("$Id: ogrocisession.cpp 27575 2014-08-06 19:40:30Z ilucena $");
 
 /************************************************************************/
 /*                          OGRGetOCISession()                          */
@@ -103,6 +103,9 @@ OGROCISession::~OGROCISession()
 
         if( hSession )
             OCIHandleFree((dvoid *) hSession, (ub4) OCI_HTYPE_SESSION);
+
+        if( hEnv )
+            OCIHandleFree((dvoid *) hEnv, (ub4) OCI_HTYPE_ENV);
     }
 
     CPLFree( pszUserid );
diff --git a/ogr/ogrsf_frmts/oci/ogrocistroke.cpp b/ogr/ogrsf_frmts/oci/ogrocistroke.cpp
index 373e273..5d0e21d 100644
--- a/ogr/ogrsf_frmts/oci/ogrocistroke.cpp
+++ b/ogr/ogrsf_frmts/oci/ogrocistroke.cpp
@@ -1,271 +1,271 @@
-/******************************************************************************
- *
- * Purpose:  Oracle curve to linestring stroking (approximation).
- * Author:   Frank Warmerdam, warmerdam at pobox.com
- *
- ******************************************************************************
- * Copyright (c) 2008, Frank Warmerdam
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- ****************************************************************************/
-
-#include <stdarg.h>
-#include "ogr_oci.h"
-#include "cpl_conv.h"
-#include "cpl_string.h"
-
-CPL_CVSID("$Id: ntfstroke.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
-
-#ifndef PI
-#define PI  3.14159265358979323846
-#endif 
-
-/************************************************************************/
-/*                   OGROCIArcCenterFromEdgePoints()                    */
-/*                                                                      */
-/*      Compute the center of an arc/circle from three edge points.     */
-/************************************************************************/
-
-static int 
-OGROCIArcCenterFromEdgePoints( double x_c0, double y_c0,
-                               double x_c1, double y_c1, 
-                               double x_c2, double y_c2, 
-                               double *x_center, double *y_center )
-    
-{
-
-/* -------------------------------------------------------------------- */
-/*      Handle a degenerate case that occurs in OSNI products by        */
-/*      making some assumptions.  If the first and third points are     */
-/*      the same assume they are intended to define a full circle,      */
-/*      and that the second point is on the opposite side of the        */
-/*      circle.                                                         */
-/* -------------------------------------------------------------------- */
-    if( x_c0 == x_c2 && y_c0 == y_c2 )
-    {
-        *x_center = (x_c0 + x_c1) * 0.5;
-        *y_center = (y_c0 + y_c1) * 0.5;
-
-        return TRUE;
-    }
-
-/* -------------------------------------------------------------------- */
-/*      Compute the inverse of the slopes connecting the first and      */
-/*      second points.  Also compute the center point of the two        */
-/*      lines ... the point our crossing line will go through.          */
-/* -------------------------------------------------------------------- */
-    double m1, x1, y1;
-
-    if( (y_c1 - y_c0) != 0.0 )
-        m1 = (x_c0 - x_c1) / (y_c1 - y_c0);
-    else
-        m1 = 1e+10;
-
-    x1 = (x_c0 + x_c1) * 0.5;
-    y1 = (y_c0 + y_c1) * 0.5;
-
-/* -------------------------------------------------------------------- */
-/*      Compute the same for the second point compared to the third     */
-/*      point.                                                          */
-/* -------------------------------------------------------------------- */
-    double m2, x2, y2;
-
-    if( (y_c2 - y_c1) != 0.0 )
-        m2 = (x_c1 - x_c2) / (y_c2 - y_c1);
-    else
-        m2 = 1e+10;
-
-    x2 = (x_c1 + x_c2) * 0.5;
-    y2 = (y_c1 + y_c2) * 0.5;
-
-/* -------------------------------------------------------------------- */
-/*      Turn these into the Ax+By+C = 0 form of the lines.              */
-/* -------------------------------------------------------------------- */
-    double      a1, a2, b1, b2, c1, c2;
-
-    a1 = m1;
-    a2 = m2;
-
-    b1 = -1.0;
-    b2 = -1.0;
-    
-    c1 = (y1 - m1*x1);
-    c2 = (y2 - m2*x2);
-    
-/* -------------------------------------------------------------------- */
-/*      Compute the intersection of the two lines through the center    */
-/*      of the circle, using Kramers rule.                              */
-/* -------------------------------------------------------------------- */
-    double      det_inv;
-
-    if( a1*b2 - a2*b1 == 0.0 )
-        return FALSE;
-
-    det_inv = 1 / (a1*b2 - a2*b1);
-
-    *x_center = (b1*c2 - b2*c1) * det_inv;
-    *y_center = (a2*c1 - a1*c2) * det_inv;
-
-    return TRUE;
-}
-
-/************************************************************************/
-/*                OGROCIStrokeArcToOGRGeometry_Angles()                 */
-/************************************************************************/
-
-static int 
-OGROCIStrokeArcToOGRGeometry_Angles( double dfCenterX, double dfCenterY, 
-                                     double dfRadius, 
-                                     double dfStartAngle, double dfEndAngle,
-                                     double dfMaxAngleStepSizeDegrees,
-                                     OGRLineString *poLine )
-
-{
-    double             dfArcX, dfArcY, dfSlice;
-    int                iPoint, iAppendLocation, nVertexCount;
-    double             dfEps = dfRadius / 100000.0;
-
-    nVertexCount = (int) 
-        ceil(fabs(dfEndAngle - dfStartAngle)/dfMaxAngleStepSizeDegrees) + 1;
-    nVertexCount = MAX(2,nVertexCount);
-    dfSlice = (dfEndAngle-dfStartAngle)/(nVertexCount-1);
-
-    for( iPoint=0; iPoint < nVertexCount; iPoint++ )
-    {
-        double      dfAngle;
-
-        dfAngle = (dfStartAngle + iPoint * dfSlice) * PI / 180.0;
-
-        dfArcX = dfCenterX + cos(dfAngle) * dfRadius;
-        dfArcY = dfCenterY + sin(dfAngle) * dfRadius;
-
-        if( iPoint == 0 )
-        {
-            iAppendLocation = poLine->getNumPoints();
-
-            if( poLine->getNumPoints() > 0 
-                && fabs(poLine->getX(poLine->getNumPoints()-1)-dfArcX) < dfEps
-                && fabs(poLine->getY(poLine->getNumPoints()-1)-dfArcY) < dfEps)
-            {
-                poLine->setNumPoints( 
-                    poLine->getNumPoints() + nVertexCount - 1 );
-            }
-            else
-            {
-                poLine->setNumPoints( 
-                    poLine->getNumPoints() + nVertexCount - 1 );
-                poLine->setPoint( iAppendLocation++, dfArcX, dfArcY );
-            }
-        }
-        else
-            poLine->setPoint( iAppendLocation++, dfArcX, dfArcY );
-    }
-
-    return TRUE;
-}
-
-
-/************************************************************************/
-/*                OGROCIStrokeArcToOGRGeometry_Points()                 */
-/************************************************************************/
-
-int 
-OGROCIStrokeArcToOGRGeometry_Points( double dfStartX, double dfStartY,
-                                     double dfAlongX, double dfAlongY,
-                                     double dfEndX, double dfEndY,
-                                     double dfMaxAngleStepSizeDegrees,
-                                     int bForceWholeCircle,
-                                     OGRLineString *poLine )
-    
-{
-    double      dfStartAngle, dfEndAngle, dfAlongAngle;
-    double      dfCenterX, dfCenterY, dfRadius;
-
-    if( !OGROCIArcCenterFromEdgePoints( dfStartX, dfStartY, 
-                                        dfAlongX, dfAlongY,
-                                        dfEndX, dfEndY, 
-                                        &dfCenterX, &dfCenterY ) )
-        return FALSE;
-
-    if( bForceWholeCircle || (dfStartX == dfEndX && dfStartY == dfEndY) )
-    {
-        dfStartAngle = 0.0;
-        dfEndAngle = 360.0;
-    }
-    else
-    {
-        double  dfDeltaX, dfDeltaY;
-
-        dfDeltaX = dfStartX - dfCenterX;
-        dfDeltaY = dfStartY - dfCenterY;
-        dfStartAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
-
-        dfDeltaX = dfAlongX - dfCenterX;
-        dfDeltaY = dfAlongY - dfCenterY;
-        dfAlongAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
-
-        dfDeltaX = dfEndX - dfCenterX;
-        dfDeltaY = dfEndY - dfCenterY;
-        dfEndAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
-
-        // Try positive (clockwise?) winding.
-        while( dfAlongAngle < dfStartAngle )
-            dfAlongAngle += 360.0;
-
-        while( dfEndAngle < dfAlongAngle )
-            dfEndAngle += 360.0;
-
-        // If that doesn't work out, then go anticlockwise.
-        if( dfEndAngle - dfStartAngle > 360.0 )
-        {
-            while( dfAlongAngle > dfStartAngle )
-                dfAlongAngle -= 360.0;
-            
-            while( dfEndAngle > dfAlongAngle )
-                dfEndAngle -= 360.0;
-        }
-    }
-
-    dfRadius = sqrt( (dfCenterX - dfStartX) * (dfCenterX - dfStartX)
-                     + (dfCenterY - dfStartY) * (dfCenterY - dfStartY) );
-
-    int bResult;
-
-    bResult = 
-        OGROCIStrokeArcToOGRGeometry_Angles( dfCenterX, dfCenterY, 
-                                             dfRadius, 
-                                             dfStartAngle, dfEndAngle,
-                                             dfMaxAngleStepSizeDegrees,
-                                             poLine );
-
-/* -------------------------------------------------------------------- */
-/*      Force the points for arcs, to avoid odd rounding/math           */
-/*      issues.  Perhaps we should do this for the start too, but       */
-/*      this is a bit tricky since it isn't obvious which point is      */
-/*      the start.                                                      */
-/* -------------------------------------------------------------------- */
-    if( bResult && !bForceWholeCircle )
-    {
-        poLine->setPoint( poLine->getNumPoints() - 1, 
-                          dfEndX, dfEndY );
-    }
-
-    return bResult;
-}
-
+/******************************************************************************
+ *
+ * Purpose:  Oracle curve to linestring stroking (approximation).
+ * Author:   Frank Warmerdam, warmerdam at pobox.com
+ *
+ ******************************************************************************
+ * Copyright (c) 2008, Frank Warmerdam
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ ****************************************************************************/
+
+#include <stdarg.h>
+#include "ogr_oci.h"
+#include "cpl_conv.h"
+#include "cpl_string.h"
+
+CPL_CVSID("$Id: ntfstroke.cpp 10645 2007-01-18 02:22:39Z warmerdam $");
+
+#ifndef PI
+#define PI  3.14159265358979323846
+#endif 
+
+/************************************************************************/
+/*                   OGROCIArcCenterFromEdgePoints()                    */
+/*                                                                      */
+/*      Compute the center of an arc/circle from three edge points.     */
+/************************************************************************/
+
+static int 
+OGROCIArcCenterFromEdgePoints( double x_c0, double y_c0,
+                               double x_c1, double y_c1, 
+                               double x_c2, double y_c2, 
+                               double *x_center, double *y_center )
+    
+{
+
+/* -------------------------------------------------------------------- */
+/*      Handle a degenerate case that occurs in OSNI products by        */
+/*      making some assumptions.  If the first and third points are     */
+/*      the same assume they are intended to define a full circle,      */
+/*      and that the second point is on the opposite side of the        */
+/*      circle.                                                         */
+/* -------------------------------------------------------------------- */
+    if( x_c0 == x_c2 && y_c0 == y_c2 )
+    {
+        *x_center = (x_c0 + x_c1) * 0.5;
+        *y_center = (y_c0 + y_c1) * 0.5;
+
+        return TRUE;
+    }
+
+/* -------------------------------------------------------------------- */
+/*      Compute the inverse of the slopes connecting the first and      */
+/*      second points.  Also compute the center point of the two        */
+/*      lines ... the point our crossing line will go through.          */
+/* -------------------------------------------------------------------- */
+    double m1, x1, y1;
+
+    if( (y_c1 - y_c0) != 0.0 )
+        m1 = (x_c0 - x_c1) / (y_c1 - y_c0);
+    else
+        m1 = 1e+10;
+
+    x1 = (x_c0 + x_c1) * 0.5;
+    y1 = (y_c0 + y_c1) * 0.5;
+
+/* -------------------------------------------------------------------- */
+/*      Compute the same for the second point compared to the third     */
+/*      point.                                                          */
+/* -------------------------------------------------------------------- */
+    double m2, x2, y2;
+
+    if( (y_c2 - y_c1) != 0.0 )
+        m2 = (x_c1 - x_c2) / (y_c2 - y_c1);
+    else
+        m2 = 1e+10;
+
+    x2 = (x_c1 + x_c2) * 0.5;
+    y2 = (y_c1 + y_c2) * 0.5;
+
+/* -------------------------------------------------------------------- */
+/*      Turn these into the Ax+By+C = 0 form of the lines.              */
+/* -------------------------------------------------------------------- */
+    double      a1, a2, b1, b2, c1, c2;
+
+    a1 = m1;
+    a2 = m2;
+
+    b1 = -1.0;
+    b2 = -1.0;
+    
+    c1 = (y1 - m1*x1);
+    c2 = (y2 - m2*x2);
+    
+/* -------------------------------------------------------------------- */
+/*      Compute the intersection of the two lines through the center    */
+/*      of the circle, using Kramers rule.                              */
+/* -------------------------------------------------------------------- */
+    double      det_inv;
+
+    if( a1*b2 - a2*b1 == 0.0 )
+        return FALSE;
+
+    det_inv = 1 / (a1*b2 - a2*b1);
+
+    *x_center = (b1*c2 - b2*c1) * det_inv;
+    *y_center = (a2*c1 - a1*c2) * det_inv;
+
+    return TRUE;
+}
+
+/************************************************************************/
+/*                OGROCIStrokeArcToOGRGeometry_Angles()                 */
+/************************************************************************/
+
+static int 
+OGROCIStrokeArcToOGRGeometry_Angles( double dfCenterX, double dfCenterY, 
+                                     double dfRadius, 
+                                     double dfStartAngle, double dfEndAngle,
+                                     double dfMaxAngleStepSizeDegrees,
+                                     OGRLineString *poLine )
+
+{
+    double             dfArcX, dfArcY, dfSlice;
+    int                iPoint, iAppendLocation, nVertexCount;
+    double             dfEps = dfRadius / 100000.0;
+
+    nVertexCount = (int) 
+        ceil(fabs(dfEndAngle - dfStartAngle)/dfMaxAngleStepSizeDegrees) + 1;
+    nVertexCount = MAX(2,nVertexCount);
+    dfSlice = (dfEndAngle-dfStartAngle)/(nVertexCount-1);
+
+    for( iPoint=0; iPoint < nVertexCount; iPoint++ )
+    {
+        double      dfAngle;
+
+        dfAngle = (dfStartAngle + iPoint * dfSlice) * PI / 180.0;
+
+        dfArcX = dfCenterX + cos(dfAngle) * dfRadius;
+        dfArcY = dfCenterY + sin(dfAngle) * dfRadius;
+
+        if( iPoint == 0 )
+        {
+            iAppendLocation = poLine->getNumPoints();
+
+            if( poLine->getNumPoints() > 0 
+                && fabs(poLine->getX(poLine->getNumPoints()-1)-dfArcX) < dfEps
+                && fabs(poLine->getY(poLine->getNumPoints()-1)-dfArcY) < dfEps)
+            {
+                poLine->setNumPoints( 
+                    poLine->getNumPoints() + nVertexCount - 1 );
+            }
+            else
+            {
+                poLine->setNumPoints( 
+                    poLine->getNumPoints() + nVertexCount - 1 );
+                poLine->setPoint( iAppendLocation++, dfArcX, dfArcY );
+            }
+        }
+        else
+            poLine->setPoint( iAppendLocation++, dfArcX, dfArcY );
+    }
+
+    return TRUE;
+}
+
+
+/************************************************************************/
+/*                OGROCIStrokeArcToOGRGeometry_Points()                 */
+/************************************************************************/
+
+int 
+OGROCIStrokeArcToOGRGeometry_Points( double dfStartX, double dfStartY,
+                                     double dfAlongX, double dfAlongY,
+                                     double dfEndX, double dfEndY,
+                                     double dfMaxAngleStepSizeDegrees,
+                                     int bForceWholeCircle,
+                                     OGRLineString *poLine )
+    
+{
+    double      dfStartAngle, dfEndAngle, dfAlongAngle;
+    double      dfCenterX, dfCenterY, dfRadius;
+
+    if( !OGROCIArcCenterFromEdgePoints( dfStartX, dfStartY, 
+                                        dfAlongX, dfAlongY,
+                                        dfEndX, dfEndY, 
+                                        &dfCenterX, &dfCenterY ) )
+        return FALSE;
+
+    if( bForceWholeCircle || (dfStartX == dfEndX && dfStartY == dfEndY) )
+    {
+        dfStartAngle = 0.0;
+        dfEndAngle = 360.0;
+    }
+    else
+    {
+        double  dfDeltaX, dfDeltaY;
+
+        dfDeltaX = dfStartX - dfCenterX;
+        dfDeltaY = dfStartY - dfCenterY;
+        dfStartAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
+
+        dfDeltaX = dfAlongX - dfCenterX;
+        dfDeltaY = dfAlongY - dfCenterY;
+        dfAlongAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
+
+        dfDeltaX = dfEndX - dfCenterX;
+        dfDeltaY = dfEndY - dfCenterY;
+        dfEndAngle = atan2(dfDeltaY,dfDeltaX) * 180.0 / PI;
+
+        // Try positive (clockwise?) winding.
+        while( dfAlongAngle < dfStartAngle )
+            dfAlongAngle += 360.0;
+
+        while( dfEndAngle < dfAlongAngle )
+            dfEndAngle += 360.0;
+
+        // If that doesn't work out, then go anticlockwise.
+        if( dfEndAngle - dfStartAngle > 360.0 )
+        {
+            while( dfAlongAngle > dfStartAngle )
+                dfAlongAngle -= 360.0;
+            
+            while( dfEndAngle > dfAlongAngle )
+                dfEndAngle -= 360.0;
+        }
+    }
+
+    dfRadius = sqrt( (dfCenterX - dfStartX) * (dfCenterX - dfStartX)
+                     + (dfCenterY - dfStartY) * (dfCenterY - dfStartY) );
+
+    int bResult;
+
+    bResult = 
+        OGROCIStrokeArcToOGRGeometry_Angles( dfCenterX, dfCenterY, 
+                                             dfRadius, 
+                                             dfStartAngle, dfEndAngle,
+                                             dfMaxAngleStepSizeDegrees,
+                                             poLine );
+
+/* -------------------------------------------------------------------- */
+/*      Force the points for arcs, to avoid odd rounding/math           */
+/*      issues.  Perhaps we should do this for the start too, but       */
+/*      this is a bit tricky since it isn't obvious which point is      */
+/*      the start.                                                      */
+/* -------------------------------------------------------------------- */
+    if( bResult && !bForceWholeCircle )
+    {
+        poLine->setPoint( poLine->getNumPoints() - 1, 
+                          dfEndX, dfEndY );
+    }
+
+    return bResult;
+}
+
diff --git a/ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp b/ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp
index 9f63d0b..e63f103 100644
--- a/ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp
+++ b/ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrociwritablelayer.cpp 26573 2013-10-30 13:34:41Z rouault $
+ * $Id: ogrociwritablelayer.cpp 27583 2014-08-12 16:06:37Z martinl $
  *
  * Project:  Oracle Spatial Driver
  * Purpose:  Implementation of the OGROCIWritableLayer class.  This provides
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrociwritablelayer.cpp 26573 2013-10-30 13:34:41Z rouault $");
+CPL_CVSID("$Id: ogrociwritablelayer.cpp 27583 2014-08-12 16:06:37Z martinl $");
 
 /************************************************************************/
 /*                        OGROCIWritableLayer()                         */
@@ -247,6 +247,7 @@ OGRErr OGROCIWritableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK
 {
     OGROCISession      *poSession = poDS->GetSession();
     char                szFieldType[256];
+    char                szFieldName[30];     // specify at most 30 characters, see ORA-00972
     OGRFieldDefn        oField( poFieldIn );
 
 /* -------------------------------------------------------------------- */
@@ -287,6 +288,11 @@ OGRErr OGROCIWritableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK
         else
             sprintf( szFieldType, "VARCHAR2(%d)", oField.GetWidth() );
     }
+    else if ( oField.GetType() == OFTDate ||
+              oField.GetType() == OFTDateTime )
+    {
+        sprintf( szFieldType, "DATE" );
+    }
     else if( bApproxOK )
     {
         CPLError( CE_Warning, CPLE_NotSupported,
@@ -315,8 +321,18 @@ OGRErr OGROCIWritableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK
                           + strlen(oField.GetNameRef())
                           + strlen(szFieldType) );
 
+    snprintf( szFieldName, sizeof( szFieldName ), oField.GetNameRef());
+    szFieldName[sizeof( szFieldName )-1] = '\0';
+    if ( strlen(oField.GetNameRef()) > sizeof ( szFieldName ) )
+    {
+        szFieldName[sizeof( szFieldName ) - 1] = '_';
+        CPLError( CE_Warning, CPLE_AppDefined, 
+                  "Column %s is too long (at most 30 characters). Using %s.", 
+                  oField.GetNameRef(), szFieldName );
+        oField.SetName(szFieldName);
+    }
     sprintf( oCommand.GetString(), "ALTER TABLE %s ADD \"%s\" %s", 
-             poFeatureDefn->GetName(), oField.GetNameRef(), szFieldType );
+             poFeatureDefn->GetName(), szFieldName, szFieldType );
     if( oAddField.Execute( oCommand.GetString() ) != CE_None )
         return OGRERR_FAILURE;
 
diff --git a/ogr/ogrsf_frmts/ods/ods_formula_parser.cpp b/ogr/ogrsf_frmts/ods/ods_formula_parser.cpp
index f5d5434..96b96fa 100644
--- a/ogr/ogrsf_frmts/ods/ods_formula_parser.cpp
+++ b/ogr/ogrsf_frmts/ods/ods_formula_parser.cpp
@@ -80,7 +80,7 @@
 #line 1 "ods_formula_parser.y"
 
 /******************************************************************************
- * $Id: ods_formula_parser.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ods_formula_parser.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Component: OGR ODS Formula Engine
  * Purpose: expression and select parser grammar.
@@ -123,7 +123,7 @@
 /* it appears to be a non documented feature of Bison */ 
 #define YYSTYPE_IS_TRIVIAL 1
 
-static void ods_formulaerror( ods_formula_parse_context *context, const char *msg )
+static void ods_formulaerror( CPL_UNUSED ods_formula_parse_context *context, const char *msg )
 {
     CPLError( CE_Failure, CPLE_AppDefined, 
               "Formula Parsing Error: %s", msg );
diff --git a/ogr/ogrsf_frmts/ods/ods_formula_parser.y b/ogr/ogrsf_frmts/ods/ods_formula_parser.y
index 47ad151..1f28c53 100644
--- a/ogr/ogrsf_frmts/ods/ods_formula_parser.y
+++ b/ogr/ogrsf_frmts/ods/ods_formula_parser.y
@@ -1,6 +1,6 @@
 %{
 /******************************************************************************
- * $Id: ods_formula_parser.y 23831 2012-01-30 23:12:23Z rouault $
+ * $Id: ods_formula_parser.y 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Component: OGR ODS Formula Engine
  * Purpose: expression and select parser grammar.
@@ -43,7 +43,7 @@
 /* it appears to be a non documented feature of Bison */ 
 #define YYSTYPE_IS_TRIVIAL 1
 
-static void ods_formulaerror( ods_formula_parse_context *context, const char *msg )
+static void ods_formulaerror( CPL_UNUSED ods_formula_parse_context *context, const char *msg )
 {
     CPLError( CE_Failure, CPLE_AppDefined, 
               "Formula Parsing Error: %s", msg );
diff --git a/ogr/ogrsf_frmts/ods/ogrodsdatasource.cpp b/ogr/ogrsf_frmts/ods/ogrodsdatasource.cpp
index ed3992b..df2312a 100644
--- a/ogr/ogrsf_frmts/ods/ogrodsdatasource.cpp
+++ b/ogr/ogrsf_frmts/ods/ogrodsdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrodsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrodsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  ODS Translator
  * Purpose:  Implements OGRODSDataSource class
@@ -34,7 +34,7 @@
 #include "ods_formula.h"
 #include <set>
 
-CPL_CVSID("$Id: ogrodsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrodsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 
 /************************************************************************/
@@ -273,7 +273,7 @@ int OGRODSDataSource::Open( const char * pszFilename,
 /*                             Create()                                 */
 /************************************************************************/
 
-int OGRODSDataSource::Create( const char * pszFilename, char **papszOptions )
+int OGRODSDataSource::Create( const char * pszFilename, CPL_UNUSED char **papszOptions )
 {
     bUpdated = TRUE;
     bUpdatable = TRUE;
@@ -610,7 +610,7 @@ void OGRODSDataSource::startElementTable(const char *pszName,
 /*                           endElementTable()                          */
 /************************************************************************/
 
-void OGRODSDataSource::endElementTable(const char *pszName)
+void OGRODSDataSource::endElementTable(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -742,7 +742,7 @@ void OGRODSDataSource::startElementRow(const char *pszName,
 /*                            endElementRow()                           */
 /************************************************************************/
 
-void OGRODSDataSource::endElementRow(const char *pszName)
+void OGRODSDataSource::endElementRow(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -930,7 +930,7 @@ void OGRODSDataSource::endElementRow(const char *pszName)
 /************************************************************************/
 
 void OGRODSDataSource::startElementCell(const char *pszName,
-                                        const char **ppszAttr)
+                                        CPL_UNUSED const char **ppszAttr)
 {
     if (osValue.size() == 0 && strcmp(pszName, "text:p") == 0)
     {
@@ -942,7 +942,7 @@ void OGRODSDataSource::startElementCell(const char *pszName,
 /*                            endElementCell()                          */
 /************************************************************************/
 
-void OGRODSDataSource::endElementCell(const char *pszName)
+void OGRODSDataSource::endElementCell(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -1088,7 +1088,7 @@ static void XMLCALL endElementStylesCbk(void *pUserData, const char *pszName)
     ((OGRODSDataSource*)pUserData)->endElementStylesCbk(pszName);
 }
 
-void OGRODSDataSource::endElementStylesCbk(const char *pszName)
+void OGRODSDataSource::endElementStylesCbk(CPL_UNUSED const char *pszName)
 {
     if (bStopParsing) return;
 
@@ -1208,9 +1208,9 @@ void OGRODSDataSource::AnalyseSettings()
 
 OGRLayer *
 OGRODSDataSource::CreateLayer( const char * pszLayerName,
-                                OGRSpatialReference *poSRS,
-                                OGRwkbGeometryType eType,
-                                char ** papszOptions )
+                               CPL_UNUSED OGRSpatialReference *poSRS,
+                               CPL_UNUSED OGRwkbGeometryType eType,
+                               char ** papszOptions )
 
 {
 /* -------------------------------------------------------------------- */
diff --git a/ogr/ogrsf_frmts/openair/ogropenairdatasource.cpp b/ogr/ogrsf_frmts/openair/ogropenairdatasource.cpp
index bdc5a54..24a53d6 100644
--- a/ogr/ogrsf_frmts/openair/ogropenairdatasource.cpp
+++ b/ogr/ogrsf_frmts/openair/ogropenairdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogropenairdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogropenairdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenAir Translator
  * Purpose:  Implements OGROpenAirDataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogropenairdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogropenairdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGROpenAirDataSource()                        */
@@ -64,8 +64,7 @@ OGROpenAirDataSource::~OGROpenAirDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROpenAirDataSource::TestCapability( const char * pszCap )
-
+int OGROpenAirDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/openair/ogropenairdriver.cpp b/ogr/ogrsf_frmts/openair/ogropenairdriver.cpp
index 76a1faf..5c89b59 100644
--- a/ogr/ogrsf_frmts/openair/ogropenairdriver.cpp
+++ b/ogr/ogrsf_frmts/openair/ogropenairdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogropenairdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogropenairdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenAir Translator
  * Purpose:  Implements OGROpenAirDriver.
@@ -30,7 +30,7 @@
 #include "ogr_openair.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogropenairdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogropenairdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGROpenAir();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGROpenAirDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROpenAirDriver::TestCapability( const char * pszCap )
-
+int OGROpenAirDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/openair/ogropenairlabellayer.cpp b/ogr/ogrsf_frmts/openair/ogropenairlabellayer.cpp
index a4f6473..85a84f9 100644
--- a/ogr/ogrsf_frmts/openair/ogropenairlabellayer.cpp
+++ b/ogr/ogrsf_frmts/openair/ogropenairlabellayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogropenairlabellayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogropenairlabellayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenAir Translator
  * Purpose:  Implements OGROpenAirLabelLayer class.
@@ -33,7 +33,7 @@
 #include "ogr_p.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ogropenairlabellayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogropenairlabellayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                      OGROpenAirLabelLayer()                          */
@@ -184,8 +184,7 @@ OGRFeature *OGROpenAirLabelLayer::GetNextRawFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROpenAirLabelLayer::TestCapability( const char * pszCap )
-
+int OGROpenAirLabelLayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/openair/ogropenairlayer.cpp b/ogr/ogrsf_frmts/openair/ogropenairlayer.cpp
index 4668dbd..04cdee5 100644
--- a/ogr/ogrsf_frmts/openair/ogropenairlayer.cpp
+++ b/ogr/ogrsf_frmts/openair/ogropenairlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogropenairlayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogropenairlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenAir Translator
  * Purpose:  Implements OGROpenAirLayer class.
@@ -34,7 +34,7 @@
 #include "ogr_xplane_geo_utils.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ogropenairlayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogropenairlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         OGROpenAirLayer()                            */
@@ -465,8 +465,7 @@ OGRFeature *OGROpenAirLayer::GetNextRawFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROpenAirLayer::TestCapability( const char * pszCap )
-
+int OGROpenAirLayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp
index ae2d74a..2c0fabb 100644
--- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp
+++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: filegdbtable.cpp 27152 2014-04-10 20:47:42Z rouault $
+ * $Id: filegdbtable.cpp 27727 2014-09-23 18:41:36Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements reading of FileGDB tables
@@ -113,6 +113,7 @@ void FileGDBTable::Init()
     bHasReadGDBIndexes = FALSE;
     nOffsetFieldDesc = 0;
     nFieldDescLength = 0;
+    nTablxOffsetSize = 0;
     anFeatureOffsets.resize(0);
     nOffsetHeaderEnd = 0;
 }
@@ -265,8 +266,8 @@ static void ReadVarUInt64NoCheck(GByte*& pabyIter, GUIntBig& nOutVal)
 /*                      IsLikelyFeatureAtOffset()                       */
 /************************************************************************/
 
-int FileGDBTable::IsLikelyFeatureAtOffset(GUInt32 nFileSize,
-                                          GUInt32 nOffset,
+int FileGDBTable::IsLikelyFeatureAtOffset(vsi_l_offset nFileSize,
+                                          vsi_l_offset nOffset,
                                           GUInt32* pnSize,
                                           int* pbDeletedRecord)
 {
@@ -446,11 +447,11 @@ int FileGDBTable::IsLikelyFeatureAtOffset(GUInt32 nFileSize,
 
 int FileGDBTable::GuessFeatureLocations()
 {
-    GUInt32 nFileSize;
+    vsi_l_offset nFileSize;
     VSIFSeekL(fpTable, 0, SEEK_END);
-    nFileSize = (GUInt32) MIN(~((GUInt32)0), VSIFTellL(fpTable));
+    nFileSize = VSIFTellL(fpTable);
 
-    GUInt32 nOffset = 40 + nFieldDescLength;
+    vsi_l_offset nOffset = 40 + nFieldDescLength;
     
     if( nOffsetFieldDesc != 40 )
     {
@@ -529,11 +530,14 @@ int FileGDBTable::ReadTableXHeader()
     else
         returnErrorIf(nTotalRecordCount < 0 );
 
+    nTablxOffsetSize = GetUInt32(abyHeader + 12, 0);
+    returnErrorIf(nTablxOffsetSize < 4 || nTablxOffsetSize > 6);
+
     if( n1024Blocks != 0 )
     {
         GByte abyTrailer[16];
 
-        VSIFSeekL( fpTableX, 5 * 1024 * (vsi_l_offset)n1024Blocks + 16, SEEK_SET );
+        VSIFSeekL( fpTableX, nTablxOffsetSize * 1024 * (vsi_l_offset)n1024Blocks + 16, SEEK_SET );
         returnErrorIf(VSIFReadL( abyTrailer, 16, 1, fpTableX ) != 1 );
 
         GUInt32 nMagic = GetUInt32(abyTrailer, 0);
@@ -546,7 +550,6 @@ int FileGDBTable::ReadTableXHeader()
 
         /* GUInt32 nMagic2 = GetUInt32(abyTrailer + 12, 0); */
 
-        returnErrorIf(nMagic != 0 && nMagic != 32 );
         if( nMagic == 0 )
         {
             returnErrorIf(nBitsForBlockMap != n1024Blocks );
@@ -653,7 +656,7 @@ int FileGDBTable::Open(const char* pszFilename)
 
     nOffsetHeaderEnd = nOffsetFieldDesc + nFieldDescLength;
 
-    returnErrorIf(nFieldDescLength > 1024 * 1024 || nFieldDescLength < 10 );
+    returnErrorIf(nFieldDescLength > 10 * 1024 * 1024 || nFieldDescLength < 10 );
     GByte byTableGeomType = abyHeader[8];
     if( IS_VALID_LAYER_GEOM_TYPE(byTableGeomType) )
         eTableGeomType = (FileGDBTableGeometryType) byTableGeomType;
@@ -667,7 +670,7 @@ int FileGDBTable::Open(const char* pszFilename)
 
     GUInt32 nRemaining = nFieldDescLength - 10;
     nBufferMaxSize = nRemaining;
-    pabyBuffer = (GByte*)VSIMalloc(nBufferMaxSize);
+    pabyBuffer = (GByte*)VSIMalloc(nBufferMaxSize + ZEROES_AFTER_END_OF_BUFFER);
     returnErrorIf(pabyBuffer == NULL );
     returnErrorIf(VSIFReadL(pabyBuffer, nRemaining, 1, fpTable) != 1 );
 
@@ -713,19 +716,23 @@ int FileGDBTable::Open(const char* pszFilename)
         {
             GByte flags = 0;
             int nMaxWidth = 0;
-            GByte defaultValueLength = 0;
+            GUInt32 defaultValueLength = 0;
 
             switch( eType )
             {
                 case FGFT_STRING:
+                {
                     returnErrorIf(nRemaining < 6 );
                     nMaxWidth = GetInt32(pabyIter, 0);
                     returnErrorIf(nMaxWidth < 0);
                     flags = pabyIter[4];
-                    defaultValueLength = pabyIter[5];
-                    pabyIter += 6;
-                    nRemaining -= 6;
+                    pabyIter += 5;
+                    nRemaining -= 5;
+                    GByte* pabyIterBefore = pabyIter;
+                    returnErrorIf(!ReadVarUInt32(pabyIter, pabyIter + nRemaining, defaultValueLength));
+                    nRemaining -= (pabyIter - pabyIterBefore);
                     break;
+                }
 
                 case FGFT_OBJECTID:
                 case FGFT_BINARY:
@@ -990,7 +997,7 @@ static void ReadVarIntAndAddNoCheck(GByte*& pabyIter, GIntBig& nOutVal)
 /*                       GetOffsetInTableForRow()                       */
 /************************************************************************/
 
-GUInt32 FileGDBTable::GetOffsetInTableForRow(int iRow)
+vsi_l_offset FileGDBTable::GetOffsetInTableForRow(int iRow)
 {
     const int errorRetValue = 0;
     returnErrorIf(iRow < 0 || iRow >= nTotalRecordCount );
@@ -1010,22 +1017,29 @@ GUInt32 FileGDBTable::GetOffsetInTableForRow(int iRow)
         for(int i=0;i<iBlock;i++)
             nCountBlocksBefore += TEST_BIT(pabyTablXBlockMap, i) != 0;
         int iCorrectedRow = nCountBlocksBefore * 1024 + (iRow % 1024);
-        VSIFSeekL(fpTableX, 16 + 5 * iCorrectedRow, SEEK_SET);
+        VSIFSeekL(fpTableX, 16 + nTablxOffsetSize * iCorrectedRow, SEEK_SET);
     }
     else
     {
-        VSIFSeekL(fpTableX, 16 + 5 * iRow, SEEK_SET);
+        VSIFSeekL(fpTableX, 16 + nTablxOffsetSize * iRow, SEEK_SET);
     }
 
-    GByte abyBuffer[4];
-    bError = VSIFReadL(abyBuffer, 4, 1, fpTableX) != 1;
+    GByte abyBuffer[6];
+    bError = VSIFReadL(abyBuffer, nTablxOffsetSize, 1, fpTableX) != 1;
     returnErrorIf(bError );
-    GUInt32 nOffset = GetUInt32(abyBuffer, 0);
+    vsi_l_offset nOffset;
+
+    if( nTablxOffsetSize == 4 )
+        nOffset = GetUInt32(abyBuffer, 0);
+    else if( nTablxOffsetSize == 5 )
+        nOffset = GetUInt32(abyBuffer, 0) | (((vsi_l_offset)abyBuffer[4]) << 32);
+    else
+        nOffset = GetUInt32(abyBuffer, 0) | (((vsi_l_offset)abyBuffer[4]) << 32) | (((vsi_l_offset)abyBuffer[5]) << 40);
 
 #ifdef DEBUG_VERBOSE
     if( iRow == 0 && nOffset != 0 &&
         nOffset != nOffsetHeaderEnd && nOffset != nOffsetHeaderEnd + 4 )
-        CPLDebug("OpenFileGDB", "%s: first feature offset = %d. Expected %d",
+        CPLDebug("OpenFileGDB", "%s: first feature offset = " CPL_FRMT_GUIB ". Expected %d",
                  osFilename.c_str(), nOffset, nOffsetHeaderEnd);
 #endif
 
@@ -1043,7 +1057,7 @@ int FileGDBTable::SelectRow(int iRow)
 
     if( nCurRow != iRow )
     {
-        GUInt32 nOffsetTable = GetOffsetInTableForRow(iRow);
+        vsi_l_offset nOffsetTable = GetOffsetInTableForRow(iRow);
         if( nOffsetTable == 0 )
         {
             nCurRow = -1;
@@ -1639,8 +1653,13 @@ int FileGDBTable::GetFeatureExtent(const OGRField* psField,
             nToSkip = 1;
             break;
         }
-
         case SHPT_GENERALPOLYLINE:
+        case SHPT_GENERALPOLYGON:
+        {
+            nToSkip = 1 + ((nGeomType & 0x20000000) ? 1 : 0);
+            break;
+        }
+
         case SHPT_GENERALMULTIPATCH:
         case SHPT_MULTIPATCHM:
         case SHPT_MULTIPATCH:
diff --git a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.h b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.h
index ddaa437..41cc496 100644
--- a/ogr/ogrsf_frmts/openfilegdb/filegdbtable.h
+++ b/ogr/ogrsf_frmts/openfilegdb/filegdbtable.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: filegdbtable.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: filegdbtable.h 27640 2014-09-06 15:32:09Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements reading of FileGDB tables
@@ -223,7 +223,8 @@ class FileGDBTable
         GUInt32                     nOffsetFieldDesc;
         GUInt32                     nFieldDescLength;
 
-        std::vector<GUInt32>        anFeatureOffsets;
+        GUInt32                     nTablxOffsetSize;
+        std::vector<vsi_l_offset>   anFeatureOffsets;
 
         GByte*                      pabyTablXBlockMap;
 
@@ -256,8 +257,8 @@ class FileGDBTable
         GUInt32                     nOffsetHeaderEnd;
 
         int                         ReadTableXHeader();
-        int                         IsLikelyFeatureAtOffset(GUInt32 nFileSize,
-                                                GUInt32 nOffset, GUInt32* pnSize,
+        int                         IsLikelyFeatureAtOffset(vsi_l_offset nFileSize,
+                                                vsi_l_offset nOffset, GUInt32* pnSize,
                                                 int* pbDeletedRecord);
         int                         GuessFeatureLocations();
 
@@ -284,7 +285,7 @@ class FileGDBTable
        int                      GetIndexCount();
        const FileGDBIndex*      GetIndex(int i) const { return apoIndexes[i]; }
 
-       GUInt32                  GetOffsetInTableForRow(int iRow);
+       vsi_l_offset             GetOffsetInTableForRow(int iRow);
 
        /* Next call to SelectRow() or GetFieldValue() invalidates previously returned values */
        int                      SelectRow(int iRow);
diff --git a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer.cpp b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer.cpp
index 63a0160..249e2ec 100644
--- a/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer.cpp
+++ b/ogr/ogrsf_frmts/openfilegdb/ogropenfilegdblayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogropenfilegdblayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogropenfilegdblayer.cpp 27654 2014-09-09 18:28:10Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements Open FileGDB OGR driver.
@@ -204,19 +204,48 @@ int OGROpenFileGDBLayer::BuildGeometryColumnGDBv10()
 
         const char* pszWKT = CPLGetXMLValue( psInfo, "SpatialReference.WKT", NULL );
         int nWKID = atoi(CPLGetXMLValue( psInfo, "SpatialReference.WKID", "0" ));
+        /* The concept of LatestWKID is explained in http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000n1000000 */
+        int nLatestWKID = atoi(CPLGetXMLValue( psInfo, "SpatialReference.LatestWKID", "0" ));
 
         OGROpenFileGDBGeomFieldDefn* poGeomFieldDefn =
             new OGROpenFileGDBGeomFieldDefn(NULL, pszShapeFieldName, m_eGeomType);
 
         OGRSpatialReference* poSRS = NULL;
-        if( nWKID > 0 )
+        if( nWKID > 0 || nLatestWKID > 0 )
         {
+            int bSuccess = FALSE;
             poSRS = new OGRSpatialReference();
-            if( poSRS->importFromEPSG(nWKID) != OGRERR_NONE )
+            CPLPushErrorHandler(CPLQuietErrorHandler);
+            /* Try first with nLatestWKID as there's a higher chance it is a EPSG code and not an ESRI one */
+            if( nLatestWKID > 0 )
+            {
+                if( poSRS->importFromEPSG(nLatestWKID) == OGRERR_NONE )
+                {
+                    bSuccess = TRUE;
+                }
+                else
+                {
+                    CPLDebug("OpenFileGDB", "Cannot import SRID %d", nLatestWKID);
+                }
+            }
+            if( !bSuccess && nWKID > 0 )
+            {
+                if( poSRS->importFromEPSG(nWKID) == OGRERR_NONE )
+                {
+                    bSuccess = TRUE;
+                }
+                else
+                {
+                    CPLDebug("OpenFileGDB", "Cannot import SRID %d", nWKID);
+                }
+            }
+            if( !bSuccess )
             {
                 delete poSRS;
                 poSRS = NULL;
             }
+            CPLPopErrorHandler();
+            CPLErrorReset();
         }
         if( poSRS == NULL && pszWKT != NULL && pszWKT[0] != '{' )
         {
diff --git a/ogr/ogrsf_frmts/osm/gpb.h b/ogr/ogrsf_frmts/osm/gpb.h
index 3f262c9..626b215 100644
--- a/ogr/ogrsf_frmts/osm/gpb.h
+++ b/ogr/ogrsf_frmts/osm/gpb.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gpb.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: gpb.h 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Author:   Even Rouault, <even dot rouault at mines dash paris dot org>
@@ -226,6 +226,7 @@ static void SkipVarInt(GByte** ppabyData)
 /*                         SkipUnknownField()                           */
 /************************************************************************/
 
+/* TODO: Move static function into the cpp file where it is used. */
 #define SKIP_UNKNOWN_FIELD_INLINE(pabyData, pabyDataLimit, verbose) \
         int nWireType = GET_WIRETYPE(nKey); \
         if (verbose) \
diff --git a/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp b/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp
index 0dd6258..1727b2f 100644
--- a/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp
+++ b/ogr/ogrsf_frmts/osm/ogrosmdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrosmdatasource.cpp 27139 2014-04-07 20:39:34Z rouault $
+ * $Id: ogrosmdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGROSMDataSource class.
@@ -121,7 +121,7 @@ size_t GetMaxTotalAllocs();
 static void WriteVarInt64(GUIntBig nSVal, GByte** ppabyData);
 static void WriteVarSInt64(GIntBig nSVal, GByte** ppabyData);
 
-CPL_CVSID("$Id: ogrosmdatasource.cpp 27139 2014-04-07 20:39:34Z rouault $");
+CPL_CVSID("$Id: ogrosmdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 class DSToBeOpened
 {
@@ -861,7 +861,7 @@ void OGROSMDataSource::NotifyNodes(unsigned int nNodes, OSMNode* pasNodes)
 }
 
 static void OGROSMNotifyNodes (unsigned int nNodes, OSMNode* pasNodes,
-                               OSMContext* psOSMContext, void* user_data)
+                               CPL_UNUSED OSMContext* psOSMContext, void* user_data)
 {
     ((OGROSMDataSource*) user_data)->NotifyNodes(nNodes, pasNodes);
 }
@@ -1652,7 +1652,8 @@ void OGROSMDataSource::ProcessWaysBatch()
                         }
                     }
                 }
-                else if( panReqIds[nIdx] != psWayFeaturePairs->panNodeRefs[i] )
+                else if( nIdx >= 0 &&
+                         panReqIds[nIdx] != psWayFeaturePairs->panNodeRefs[i] )
                     nIdx = -1;
 
                 if (nIdx >= 0)
@@ -2069,7 +2070,7 @@ void OGROSMDataSource::NotifyWay (OSMWay* psWay)
     nUnsortedReqIds += (psWay->nRefs - bIsArea);
 }
 
-static void OGROSMNotifyWay (OSMWay* psWay, OSMContext* psOSMContext, void* user_data)
+static void OGROSMNotifyWay (OSMWay* psWay, CPL_UNUSED OSMContext* psOSMContext, void* user_data)
 {
     ((OGROSMDataSource*) user_data)->NotifyWay(psWay);
 }
@@ -2518,7 +2519,7 @@ void OGROSMDataSource::NotifyRelation (OSMRelation* psRelation)
 }
 
 static void OGROSMNotifyRelation (OSMRelation* psRelation,
-                                  OSMContext* psOSMContext, void* user_data)
+                                  CPL_UNUSED OSMContext* psOSMContext, void* user_data)
 {
     ((OGROSMDataSource*) user_data)->NotifyRelation(psRelation);
 }
@@ -2638,7 +2639,7 @@ void OGROSMDataSource::NotifyBounds (double dfXMin, double dfYMin,
 
 static void OGROSMNotifyBounds( double dfXMin, double dfYMin,
                                 double dfXMax, double dfYMax,
-                                OSMContext* psCtxt, void* user_data )
+                                CPL_UNUSED OSMContext* psCtxt, void* user_data )
 {
     ((OGROSMDataSource*) user_data)->NotifyBounds(dfXMin, dfYMin,
                                                   dfXMax, dfYMax);
@@ -3785,8 +3786,7 @@ int OGROSMDataSource::TransferToDiskIfNecesserary()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROSMDataSource::TestCapability( const char * pszCap )
-
+int OGROSMDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/osm/ogrosmdriver.cpp b/ogr/ogrsf_frmts/osm/ogrosmdriver.cpp
index a433855..6f322ad 100644
--- a/ogr/ogrsf_frmts/osm/ogrosmdriver.cpp
+++ b/ogr/ogrsf_frmts/osm/ogrosmdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrosmdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrosmdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGROSMDriver class.
@@ -34,7 +34,7 @@
 
 extern "C" void CPL_DLL RegisterOGROSM();
 
-CPL_CVSID("$Id: ogrosmdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrosmdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         ~OGROSMDriver()                           */
@@ -81,9 +81,8 @@ OGRDataSource *OGROSMDriver::Open( const char * pszFilename,
 /*                          CreateDataSource()                          */
 /************************************************************************/
 
-OGRDataSource *OGROSMDriver::CreateDataSource( const char * pszName,
-                                               char **papszOptions )
-
+OGRDataSource *OGROSMDriver::CreateDataSource( CPL_UNUSED const char * pszName,
+                                               CPL_UNUSED char **papszOptions )
 {
     return NULL;
 }
@@ -92,8 +91,7 @@ OGRDataSource *OGROSMDriver::CreateDataSource( const char * pszName,
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGROSMDriver::TestCapability( const char * pszCap )
-
+int OGROSMDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/osm/ogrosmlayer.cpp b/ogr/ogrsf_frmts/osm/ogrosmlayer.cpp
index d355a02..a32c3a6 100644
--- a/ogr/ogrsf_frmts/osm/ogrosmlayer.cpp
+++ b/ogr/ogrsf_frmts/osm/ogrosmlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrosmlayer.cpp 27138 2014-04-07 20:32:14Z rouault $
+ * $Id: ogrosmlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGROSMLayer class
@@ -33,7 +33,7 @@
 #include "cpl_time.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrosmlayer.cpp 27138 2014-04-07 20:32:14Z rouault $");
+CPL_CVSID("$Id: ogrosmlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define SWITCH_THRESHOLD   10000
 #define MAX_THRESHOLD      100000
@@ -400,7 +400,7 @@ int  OGROSMLayer::AddFeature(OGRFeature* poFeature,
 /*                             GetExtent()                              */
 /************************************************************************/
 
-OGRErr OGROSMLayer::GetExtent( OGREnvelope *psExtent, int bForce )
+OGRErr OGROSMLayer::GetExtent( OGREnvelope *psExtent, CPL_UNUSED int bForce )
 {
     if (poDS->GetExtent(psExtent) == OGRERR_NONE)
         return OGRERR_NONE;
diff --git a/ogr/ogrsf_frmts/osm/osm_parser.cpp b/ogr/ogrsf_frmts/osm/osm_parser.cpp
index a375119..e537daa 100644
--- a/ogr/ogrsf_frmts/osm/osm_parser.cpp
+++ b/ogr/ogrsf_frmts/osm/osm_parser.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: osm_parser.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: osm_parser.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Author:   Even Rouault, <even dot rouault at mines dash paris dot org>
@@ -45,7 +45,7 @@
 
 #define XML_BUFSIZE 64*1024
 
-CPL_CVSID("$Id: osm_parser.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: osm_parser.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            INIT_INFO()                               */
@@ -1587,8 +1587,8 @@ end_error:
 /*                        EmptyNotifyNodesFunc()                        */
 /************************************************************************/
 
-static void EmptyNotifyNodesFunc(unsigned int nNodes, OSMNode* pasNodes,
-                                 OSMContext* psCtxt, void* user_data)
+static void EmptyNotifyNodesFunc(CPL_UNUSED unsigned int nNodes, CPL_UNUSED OSMNode* pasNodes,
+                                 CPL_UNUSED OSMContext* psCtxt, CPL_UNUSED void* user_data)
 {
 }
 
@@ -1597,8 +1597,8 @@ static void EmptyNotifyNodesFunc(unsigned int nNodes, OSMNode* pasNodes,
 /*                         EmptyNotifyWayFunc()                         */
 /************************************************************************/
 
-static void EmptyNotifyWayFunc(OSMWay* psWay,
-                               OSMContext* psCtxt, void* user_data)
+static void EmptyNotifyWayFunc(CPL_UNUSED OSMWay* psWay,
+                               CPL_UNUSED OSMContext* psCtxt, CPL_UNUSED void* user_data)
 {
 }
 
@@ -1606,8 +1606,8 @@ static void EmptyNotifyWayFunc(OSMWay* psWay,
 /*                       EmptyNotifyRelationFunc()                      */
 /************************************************************************/
 
-static void EmptyNotifyRelationFunc(OSMRelation* psRelation,
-                                    OSMContext* psCtxt, void* user_data)
+static void EmptyNotifyRelationFunc(CPL_UNUSED OSMRelation* psRelation,
+                                    CPL_UNUSED OSMContext* psCtxt, CPL_UNUSED void* user_data)
 {
 }
 
@@ -1615,9 +1615,9 @@ static void EmptyNotifyRelationFunc(OSMRelation* psRelation,
 /*                         EmptyNotifyBoundsFunc()                      */
 /************************************************************************/
 
-static void EmptyNotifyBoundsFunc( double dfXMin, double dfYMin,
-                                   double dfXMax, double dfYMax,
-                                   OSMContext* psCtxt, void* user_data )
+static void EmptyNotifyBoundsFunc( CPL_UNUSED double dfXMin, CPL_UNUSED double dfYMin,
+                                   CPL_UNUSED double dfXMax, CPL_UNUSED double dfYMax,
+                                   CPL_UNUSED OSMContext* psCtxt, CPL_UNUSED void* user_data )
 {
 }
 
@@ -2063,7 +2063,9 @@ static void XMLCALL OSM_XML_endElementCbk(void *pUserData, const char *pszName)
 /*                           dataHandlerCbk()                           */
 /************************************************************************/
 
-static void XMLCALL OSM_XML_dataHandlerCbk(void *pUserData, const char *data, int nLen)
+static void XMLCALL OSM_XML_dataHandlerCbk(void *pUserData,
+                                           CPL_UNUSED const char *data,
+                                           CPL_UNUSED int nLen)
 {
     OSMContext* psCtxt = (OSMContext*) pUserData;
 
diff --git a/ogr/ogrsf_frmts/pcidsk/ogrpcidskdatasource.cpp b/ogr/ogrsf_frmts/pcidsk/ogrpcidskdatasource.cpp
index 7e61496..3f409a8 100644
--- a/ogr/ogrsf_frmts/pcidsk/ogrpcidskdatasource.cpp
+++ b/ogr/ogrsf_frmts/pcidsk/ogrpcidskdatasource.cpp
@@ -163,8 +163,7 @@ OGRLayer *
 OGRPCIDSKDataSource::CreateLayer( const char * pszLayerName,
                                   OGRSpatialReference *poSRS,
                                   OGRwkbGeometryType eType,
-                                  char ** papszOptions )
-    
+                                  CPL_UNUSED char ** papszOptions )
 {
 /* -------------------------------------------------------------------- */
 /*      Verify we are in update mode.                                   */
diff --git a/ogr/ogrsf_frmts/pcidsk/ogrpcidskdriver.cpp b/ogr/ogrsf_frmts/pcidsk/ogrpcidskdriver.cpp
index 50c9457..5f1c4fc 100644
--- a/ogr/ogrsf_frmts/pcidsk/ogrpcidskdriver.cpp
+++ b/ogr/ogrsf_frmts/pcidsk/ogrpcidskdriver.cpp
@@ -76,8 +76,7 @@ OGRDataSource *OGRPCIDSKDriver::Open( const char * pszFilename, int bUpdate )
 /************************************************************************/
 
 OGRDataSource *OGRPCIDSKDriver::CreateDataSource( const char * pszName,
-                                                  char **papszOptions )
-
+                                                  CPL_UNUSED char **papszOptions )
 {
 /* -------------------------------------------------------------------- */
 /*      Try creation.                                                   */
diff --git a/ogr/ogrsf_frmts/pdf/ogrpdfdatasource.cpp b/ogr/ogrsf_frmts/pdf/ogrpdfdatasource.cpp
index 01f0ed0..79c0349 100644
--- a/ogr/ogrsf_frmts/pdf/ogrpdfdatasource.cpp
+++ b/ogr/ogrsf_frmts/pdf/ogrpdfdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpdfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrpdfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PDF Translator
  * Purpose:  Implements OGRPDFDataSource class
@@ -39,7 +39,7 @@
 #define SQUARE(x) ((x)*(x))
 #define EPSILON 1e-5
 
-CPL_CVSID("$Id: ogrpdfdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrpdfdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRPDFLayer()                             */
@@ -1950,9 +1950,9 @@ int OGRPDFDataSource::Create( const char * pszName, char **papszOptions )
 
 OGRLayer *
 OGRPDFDataSource::CreateLayer( const char * pszLayerName,
-                                OGRSpatialReference *poSRS,
-                                OGRwkbGeometryType eType,
-                                char ** papszOptions )
+                               OGRSpatialReference *poSRS,
+                               OGRwkbGeometryType eType,
+                               CPL_UNUSED char ** papszOptions )
 
 {
 /* -------------------------------------------------------------------- */
diff --git a/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp b/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp
index cf08596..29e84eb 100644
--- a/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp
+++ b/ogr/ogrsf_frmts/pds/ogrpdsdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpdsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrpdsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PDS Translator
  * Purpose:  Implements OGRPDSDataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrpdsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrpdsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRPDSDataSource()                         */
@@ -64,8 +64,7 @@ OGRPDSDataSource::~OGRPDSDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRPDSDataSource::TestCapability( const char * pszCap )
-
+int OGRPDSDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/pds/ogrpdsdriver.cpp b/ogr/ogrsf_frmts/pds/ogrpdsdriver.cpp
index 1e09a54..751f2e5 100644
--- a/ogr/ogrsf_frmts/pds/ogrpdsdriver.cpp
+++ b/ogr/ogrsf_frmts/pds/ogrpdsdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpdsdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrpdsdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  PDS Translator
  * Purpose:  Implements OGRPDSDriver.
@@ -30,7 +30,7 @@
 #include "ogr_pds.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrpdsdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrpdsdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRPDS();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGRPDSDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRPDSDriver::TestCapability( const char * pszCap )
-
+int OGRPDSDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/pg/ogrpgtablelayer.cpp b/ogr/ogrsf_frmts/pg/ogrpgtablelayer.cpp
index 907bbb0..54ff9aa 100644
--- a/ogr/ogrsf_frmts/pg/ogrpgtablelayer.cpp
+++ b/ogr/ogrsf_frmts/pg/ogrpgtablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpgtablelayer.cpp 27106 2014-03-28 11:59:57Z rouault $
+ * $Id: ogrpgtablelayer.cpp 27697 2014-09-19 18:21:02Z rouault $
 
  *
  * Project:  OpenGIS Simple Features Reference Implementation
@@ -37,7 +37,7 @@
 
 #define PQexec this_is_an_error
 
-CPL_CVSID("$Id: ogrpgtablelayer.cpp 27106 2014-03-28 11:59:57Z rouault $");
+CPL_CVSID("$Id: ogrpgtablelayer.cpp 27697 2014-09-19 18:21:02Z rouault $");
 
 
 #define USE_COPY_UNSET  -10
@@ -1590,7 +1590,7 @@ static CPLString OGRPGEscapeStringList(PGconn *hPGConn,
         osStr += "ARRAY[";
     else
         osStr += "{";
-    while(*papszItems)
+    while(papszItems && *papszItems)
     {
         if (!bFirstItem)
         {
@@ -1625,7 +1625,11 @@ static CPLString OGRPGEscapeStringList(PGconn *hPGConn,
         papszItems++;
     }
     if (bForInsertOrUpdate)
+    {
         osStr += "]";
+        if( papszItems == NULL )
+            osStr += "::varchar[]";
+    }
     else
         osStr += "}";
     return osStr;
diff --git a/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp b/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp
index bbd6bdd..46b2ddd 100644
--- a/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp
+++ b/ogr/ogrsf_frmts/pgdump/ogrpgdumpdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpgdumpdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrpgdumpdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRPGDumpDriver class.
@@ -30,7 +30,7 @@
 #include "ogr_pgdump.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrpgdumpdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrpgdumpdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                         ~OGRPGDumpDriver()                           */
@@ -55,8 +55,8 @@ const char *OGRPGDumpDriver::GetName()
 /*                                Open()                                */
 /************************************************************************/
 
-OGRDataSource *OGRPGDumpDriver::Open( const char * pszFilename,
-                                     int bUpdate )
+OGRDataSource *OGRPGDumpDriver::Open( CPL_UNUSED const char * pszFilename,
+                                      CPL_UNUSED int bUpdate )
 
 {
     return NULL;
diff --git a/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp b/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp
index 9cbefbd..178ab74 100644
--- a/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp
+++ b/ogr/ogrsf_frmts/pgdump/ogrpgdumplayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrpgdumplayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrpgdumplayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRPGDumpLayer class
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrpgdumplayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrpgdumplayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define USE_COPY_UNSET -1
 
@@ -738,7 +738,7 @@ static CPLString OGRPGDumpEscapeStringList(
         osStr += "ARRAY[";
     else
         osStr += "{";
-    while(*papszItems)
+    while(papszItems && *papszItems)
     {
         if (!bFirstItem)
         {
@@ -773,7 +773,11 @@ static CPLString OGRPGDumpEscapeStringList(
         papszItems++;
     }
     if (bForInsertOrUpdate)
+    {
         osStr += "]";
+        if( papszItems == NULL )
+            osStr += "::varchar[]";
+    }
     else
         osStr += "}";
     return osStr;
@@ -1088,7 +1092,7 @@ OGRErr OGRPGDumpLayer::CreateField( OGRFieldDefn *poFieldIn,
 /************************************************************************/
 
 OGRErr OGRPGDumpLayer::CreateGeomField( OGRGeomFieldDefn *poGeomFieldIn,
-                                        int bApproxOK )
+                                        CPL_UNUSED int bApproxOK )
 {
     OGRwkbGeometryType eType = poGeomFieldIn->GetType();
     if( eType == wkbNone )
diff --git a/ogr/ogrsf_frmts/rec/ogrreclayer.cpp b/ogr/ogrsf_frmts/rec/ogrreclayer.cpp
index d5ceafc..ba885e3 100644
--- a/ogr/ogrsf_frmts/rec/ogrreclayer.cpp
+++ b/ogr/ogrsf_frmts/rec/ogrreclayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrreclayer.cpp 25185 2012-10-27 19:40:46Z rouault $
+ * $Id: ogrreclayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  EPIInfo .REC Reader
  * Purpose:  Implements OGRRECLayer class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrreclayer.cpp 25185 2012-10-27 19:40:46Z rouault $");
+CPL_CVSID("$Id: ogrreclayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRRECLayer()                             */
@@ -301,8 +301,7 @@ OGRFeature *OGRRECLayer::GetNextFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRRECLayer::TestCapability( const char * pszCap )
-
+int OGRRECLayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/s57/ogrs57datasource.cpp b/ogr/ogrsf_frmts/s57/ogrs57datasource.cpp
index eeb08f5..0018002 100644
--- a/ogr/ogrsf_frmts/s57/ogrs57datasource.cpp
+++ b/ogr/ogrsf_frmts/s57/ogrs57datasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrs57datasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrs57datasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  S-57 Translator
  * Purpose:  Implements OGRS57DataSource class
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrs57datasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrs57datasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRS57DataSource()                          */
@@ -477,8 +477,7 @@ OGRErr OGRS57DataSource::GetDSExtent( OGREnvelope *psExtent, int bForce )
 /*      Create a new S57 file, and represent it as a datasource.        */
 /************************************************************************/
 
-int OGRS57DataSource::Create( const char *pszFilename, char **papszOptions )
-
+int OGRS57DataSource::Create( const char *pszFilename, CPL_UNUSED char **papszOptions )
 {
 /* -------------------------------------------------------------------- */
 /*      Instantiate the class registrar if possible.                    */
diff --git a/ogr/ogrsf_frmts/s57/s57featuredefns.cpp b/ogr/ogrsf_frmts/s57/s57featuredefns.cpp
index 42d0cf9..ea3ea75 100644
--- a/ogr/ogrsf_frmts/s57/s57featuredefns.cpp
+++ b/ogr/ogrsf_frmts/s57/s57featuredefns.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: s57featuredefns.cpp 26333 2013-08-15 21:40:50Z rouault $
+ * $Id: s57featuredefns.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  S-57 Translator
  * Purpose:  Implements methods to create OGRFeatureDefns for various
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: s57featuredefns.cpp 26333 2013-08-15 21:40:50Z rouault $");
+CPL_CVSID("$Id: s57featuredefns.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 
 /************************************************************************/
@@ -220,8 +220,7 @@ OGRFeatureDefn *S57GenerateGeomFeatureDefn( OGRwkbGeometryType eGType,
 /************************************************************************/
 
 OGRFeatureDefn *
-S57GenerateVectorPrimitiveFeatureDefn( int nRCNM, int nOptionFlags )
-
+S57GenerateVectorPrimitiveFeatureDefn( int nRCNM, CPL_UNUSED int nOptionFlags )
 {
     OGRFeatureDefn      *poFDefn = NULL;
  
diff --git a/ogr/ogrsf_frmts/sdts/ogrsdtslayer.cpp b/ogr/ogrsf_frmts/sdts/ogrsdtslayer.cpp
index 4d05e7a..b358aa3 100644
--- a/ogr/ogrsf_frmts/sdts/ogrsdtslayer.cpp
+++ b/ogr/ogrsf_frmts/sdts/ogrsdtslayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsdtslayer.cpp 26466 2013-09-14 09:07:46Z rouault $
+ * $Id: ogrsdtslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SDTSReader
  * Purpose:  Implements OGRSDTSLayer class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrsdtslayer.cpp 26466 2013-09-14 09:07:46Z rouault $");
+CPL_CVSID("$Id: ogrsdtslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRSDTSLayer()                            */
@@ -219,9 +219,8 @@ void OGRSDTSLayer::ResetReading()
 /************************************************************************/
 
 static void
-AssignAttrRecordToFeature( OGRFeature * poFeature, SDTSTransfer * poTransfer, 
+AssignAttrRecordToFeature( OGRFeature * poFeature, CPL_UNUSED SDTSTransfer * poTransfer,
                            DDFField * poSR )
-
 {
 /* -------------------------------------------------------------------- */
 /*      Process each subfield in the record.                            */
diff --git a/ogr/ogrsf_frmts/segukooa/ogrsegukooadatasource.cpp b/ogr/ogrsf_frmts/segukooa/ogrsegukooadatasource.cpp
index fd470f8..e134d89 100644
--- a/ogr/ogrsf_frmts/segukooa/ogrsegukooadatasource.cpp
+++ b/ogr/ogrsf_frmts/segukooa/ogrsegukooadatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsegukooadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsegukooadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SEG-P1 / UKOOA P1-90 Translator
  * Purpose:  Implements OGRSEGUKOOADataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrsegukooadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsegukooadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRSEGUKOOADataSource()                       */
@@ -64,8 +64,7 @@ OGRSEGUKOOADataSource::~OGRSEGUKOOADataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSEGUKOOADataSource::TestCapability( const char * pszCap )
-
+int OGRSEGUKOOADataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/segukooa/ogrsegukooadriver.cpp b/ogr/ogrsf_frmts/segukooa/ogrsegukooadriver.cpp
index 6059419..61f790f 100644
--- a/ogr/ogrsf_frmts/segukooa/ogrsegukooadriver.cpp
+++ b/ogr/ogrsf_frmts/segukooa/ogrsegukooadriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsegukooadriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsegukooadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SEG-P1 / UKOOA P1-90 Translator
  * Purpose:  Implements OGRSEGUKOOADriver.
@@ -30,7 +30,7 @@
 #include "ogr_segukooa.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsegukooadriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsegukooadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRSEGUKOOA();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGRSEGUKOOADriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSEGUKOOADriver::TestCapability( const char * pszCap )
-
+int OGRSEGUKOOADriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/segy/ogrsegydatasource.cpp b/ogr/ogrsf_frmts/segy/ogrsegydatasource.cpp
index 65c5cac..d3bc539 100644
--- a/ogr/ogrsf_frmts/segy/ogrsegydatasource.cpp
+++ b/ogr/ogrsf_frmts/segy/ogrsegydatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsegydatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsegydatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SEG-Y Translator
  * Purpose:  Implements OGRSEGYDataSource class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrsegydatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsegydatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRSEGYDataSource()                       */
@@ -64,8 +64,7 @@ OGRSEGYDataSource::~OGRSEGYDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSEGYDataSource::TestCapability( const char * pszCap )
-
+int OGRSEGYDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/segy/ogrsegydriver.cpp b/ogr/ogrsf_frmts/segy/ogrsegydriver.cpp
index 8e58be4..197d219 100644
--- a/ogr/ogrsf_frmts/segy/ogrsegydriver.cpp
+++ b/ogr/ogrsf_frmts/segy/ogrsegydriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsegydriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsegydriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SEG-Y Translator
  * Purpose:  Implements OGRSEGYDriver class.
@@ -30,7 +30,7 @@
 #include "ogr_segy.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsegydriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsegydriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           ~OGRSEGYDriver()                           */
@@ -73,8 +73,7 @@ OGRDataSource *OGRSEGYDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSEGYDriver::TestCapability( const char * pszCap )
-
+int OGRSEGYDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/shape/dbfopen.c b/ogr/ogrsf_frmts/shape/dbfopen.c
index 5ceda6d..c38debf 100644
--- a/ogr/ogrsf_frmts/shape/dbfopen.c
+++ b/ogr/ogrsf_frmts/shape/dbfopen.c
@@ -1324,43 +1324,24 @@ static int DBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField,
       case 'D':
       case 'N':
       case 'F':
-	if( psDBF->panFieldDecimals[iField] == 0 )
-	{
-            int		nWidth = psDBF->panFieldSize[iField];
-
-            if( (int) sizeof(szSField)-2 < nWidth )
-                nWidth = sizeof(szSField)-2;
-
-	    sprintf( szFormat, "%%%dd", nWidth );
-	    sprintf(szSField, szFormat, (int) *((double *) pValue) );
-	    if( (int)strlen(szSField) > psDBF->panFieldSize[iField] )
-            {
-	        szSField[psDBF->panFieldSize[iField]] = '\0';
-                nRetResult = FALSE;
-            }
-
-	    strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]),
-		    szSField, strlen(szSField) );
-	}
-	else
-	{
-            int		nWidth = psDBF->panFieldSize[iField];
+      {
+        int		nWidth = psDBF->panFieldSize[iField];
 
-            if( (int) sizeof(szSField)-2 < nWidth )
-                nWidth = sizeof(szSField)-2;
+        if( (int) sizeof(szSField)-2 < nWidth )
+            nWidth = sizeof(szSField)-2;
 
-	    sprintf( szFormat, "%%%d.%df", 
-                     nWidth, psDBF->panFieldDecimals[iField] );
-	    sprintf(szSField, szFormat, *((double *) pValue) );
-	    if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
-            {
-	        szSField[psDBF->panFieldSize[iField]] = '\0';
-                nRetResult = FALSE;
-            }
-	    strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]),
-		    szSField, strlen(szSField) );
-	}
-	break;
+        sprintf( szFormat, "%%%d.%df", 
+                    nWidth, psDBF->panFieldDecimals[iField] );
+        sprintf(szSField, szFormat, *((double *) pValue) );
+        if( (int) strlen(szSField) > psDBF->panFieldSize[iField] )
+        {
+            szSField[psDBF->panFieldSize[iField]] = '\0';
+            nRetResult = FALSE;
+        }
+        strncpy((char *) (pabyRec+psDBF->panFieldOffset[iField]),
+            szSField, strlen(szSField) );
+        break;
+      }
 
       case 'L':
         if (psDBF->panFieldSize[iField] >= 1  && 
diff --git a/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp b/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp
index b2cdeea..45f029b 100644
--- a/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp
+++ b/ogr/ogrsf_frmts/shape/ogrshapedriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrshapedriver.cpp 25881 2013-04-08 20:34:55Z rouault $
+ * $Id: ogrshapedriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRShapeDriver class.
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrshapedriver.cpp 25881 2013-04-08 20:34:55Z rouault $");
+CPL_CVSID("$Id: ogrshapedriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          ~OGRShapeDriver()                           */
@@ -78,8 +78,7 @@ OGRDataSource *OGRShapeDriver::Open( const char * pszFilename,
 /************************************************************************/
 
 OGRDataSource *OGRShapeDriver::CreateDataSource( const char * pszName,
-                                                 char **papszOptions )
-
+                                                 CPL_UNUSED char **papszOptions )
 {
     VSIStatBuf  stat;
     int         bSingleNewFile = FALSE;
diff --git a/ogr/ogrsf_frmts/shape/shape2ogr.cpp b/ogr/ogrsf_frmts/shape/shape2ogr.cpp
index fb58ea9..7a7b481 100644
--- a/ogr/ogrsf_frmts/shape/shape2ogr.cpp
+++ b/ogr/ogrsf_frmts/shape/shape2ogr.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: shape2ogr.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: shape2ogr.cpp 27604 2014-08-23 10:01:50Z rouault $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements translation of Shapefile shapes into OGR
@@ -32,7 +32,7 @@
 #include "ogrshape.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: shape2ogr.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: shape2ogr.cpp 27604 2014-08-23 10:01:50Z rouault $");
 
 /************************************************************************/
 /*                        RingStartEnd                                  */
@@ -1319,14 +1319,38 @@ OGRErr SHPWriteOGRFeature( SHPHandle hSHP, DBFHandle hDBF,
               }
 
               DBFWriteAttributeDirectly( hDBF, poFeature->GetFID(), iField, 
-                                                szValue );
-            break;
+                                         szValue );
+
+              break;
           }
 
           case OFTReal:
-            DBFWriteDoubleAttribute( hDBF, poFeature->GetFID(), iField, 
-                                     poFeature->GetFieldAsDouble(iField) );
+          {
+            double dfVal = poFeature->GetFieldAsDouble(iField);
+            /* IEEE754 doubles can store exact values of all integers below 2^53 */
+            if( poFieldDefn->GetPrecision() == 0 && fabs(dfVal) > ((GIntBig)1 << 53) )
+            {
+                static int nCounter = 0;
+                if( nCounter <= 10 )
+                {
+                    CPLError(CE_Warning, CPLE_AppDefined,
+                             "Value %.18g of field %s with 0 decimal of feature %ld is bigger than 2^53. Precision loss likely occured or going to happen.%s",
+                             dfVal, poFieldDefn->GetNameRef(), poFeature->GetFID(),
+                             (nCounter == 10) ? " This warning will not be emitted anymore." : "");
+                    nCounter ++;
+                }
+            }
+            int ret = DBFWriteDoubleAttribute( hDBF, poFeature->GetFID(), iField, 
+                                               dfVal );
+            if( !ret )
+            {
+                CPLError(CE_Warning, CPLE_AppDefined,
+                         "Value %.18g of field %s of feature %ld not successfully written. "
+                         "Possibly due to too larger number with respect to field width",
+                         dfVal, poFieldDefn->GetNameRef(), poFeature->GetFID());
+            }
             break;
+          }
 
           case OFTDate:
           {
diff --git a/ogr/ogrsf_frmts/shape/shpopen.c b/ogr/ogrsf_frmts/shape/shpopen.c
index ec1b0dd..d9fe682 100644
--- a/ogr/ogrsf_frmts/shape/shpopen.c
+++ b/ogr/ogrsf_frmts/shape/shpopen.c
@@ -1829,7 +1829,8 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
         if( bBigEndian ) SwapWord( 4, &nPoints );
         if( bBigEndian ) SwapWord( 4, &nParts );
 
-        if (nPoints < 0 || nParts < 0 ||
+        /* nPoints and nParts are unsigned */
+        if (/* nPoints < 0 || nParts < 0 || */
             nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000)
         {
             snprintf(szErrorMsg, sizeof(szErrorMsg),
@@ -1896,14 +1897,14 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             return NULL;
         }
 
-        for( i = 0; i < nParts; i++ )
+        for( i = 0; (int32)i < nParts; i++ )
             psShape->panPartType[i] = SHPP_RING;
 
 /* -------------------------------------------------------------------- */
 /*      Copy out the part array from the record.                        */
 /* -------------------------------------------------------------------- */
         memcpy( psShape->panPartStart, psSHP->pabyRec + 44 + 8, 4 * nParts );
-        for( i = 0; i < nParts; i++ )
+        for( i = 0; (int32)i < nParts; i++ )
         {
             if( bBigEndian ) SwapWord( 4, psShape->panPartStart+i );
 
@@ -1938,7 +1939,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
         if( psShape->nSHPType == SHPT_MULTIPATCH )
         {
             memcpy( psShape->panPartType, psSHP->pabyRec + nOffset, 4*nParts );
-            for( i = 0; i < nParts; i++ )
+            for( i = 0; (int32)i < nParts; i++ )
             {
                 if( bBigEndian ) SwapWord( 4, psShape->panPartType+i );
             }
@@ -1949,7 +1950,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
 /* -------------------------------------------------------------------- */
 /*      Copy out the vertices from the record.                          */
 /* -------------------------------------------------------------------- */
-        for( i = 0; i < nPoints; i++ )
+        for( i = 0; (int32)i < nPoints; i++ )
         {
             memcpy(psShape->padfX + i,
                    psSHP->pabyRec + nOffset + i * 16,
@@ -1978,7 +1979,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
             if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
             
-            for( i = 0; i < nPoints; i++ )
+            for( i = 0; (int32)i < nPoints; i++ )
             {
                 memcpy( psShape->padfZ + i,
                         psSHP->pabyRec + nOffset + 16 + i*8, 8 );
@@ -1998,7 +1999,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
 /*      big enough, but really it will only occur for the Z shapes      */
 /*      (options), and the M shapes.                                    */
 /* -------------------------------------------------------------------- */
-        if( nEntitySize >= nOffset + 16 + 8*nPoints )
+        if( nEntitySize >= (int)(nOffset + 16 + 8*nPoints) )
         {
             memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
             memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
@@ -2006,7 +2007,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
             if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
             
-            for( i = 0; i < nPoints; i++ )
+            for( i = 0; (int32)i < nPoints; i++ )
             {
                 memcpy( psShape->padfM + i,
                         psSHP->pabyRec + nOffset + 16 + i*8, 8 );
@@ -2045,7 +2046,8 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
 
         if( bBigEndian ) SwapWord( 4, &nPoints );
 
-        if (nPoints < 0 || nPoints > 50 * 1000 * 1000)
+        /* nPoints is unsigned */
+        if (/* nPoints < 0 || */ nPoints > 50 * 1000 * 1000)
         {
             snprintf(szErrorMsg, sizeof(szErrorMsg),
                      "Corrupted .shp file : shape %d : nPoints = %d",
@@ -2097,7 +2099,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             return NULL;
         }
 
-        for( i = 0; i < nPoints; i++ )
+        for( i = 0; (int32)i < nPoints; i++ )
         {
             memcpy(psShape->padfX+i, psSHP->pabyRec + 48 + 16 * i, 8 );
             memcpy(psShape->padfY+i, psSHP->pabyRec + 48 + 16 * i + 8, 8 );
@@ -2132,7 +2134,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
             if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
             
-            for( i = 0; i < nPoints; i++ )
+            for( i = 0; (int32)i < nPoints; i++ )
             {
                 memcpy( psShape->padfZ + i,
                         psSHP->pabyRec + nOffset + 16 + i*8, 8 );
@@ -2150,7 +2152,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
 /*      big enough, but really it will only occur for the Z shapes      */
 /*      (options), and the M shapes.                                    */
 /* -------------------------------------------------------------------- */
-        if( nEntitySize >= nOffset + 16 + 8*nPoints )
+        if( nEntitySize >= (int)(nOffset + 16 + 8*nPoints) )
         {
             memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
             memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
@@ -2158,7 +2160,7 @@ SHPReadObject( SHPHandle psSHP, int hEntity )
             if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
             if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
             
-            for( i = 0; i < nPoints; i++ )
+            for( i = 0; (int32)i < nPoints; i++ )
             {
                 memcpy( psShape->padfM + i,
                         psSHP->pabyRec + nOffset + 16 + i*8, 8 );
@@ -2385,8 +2387,7 @@ SHPDestroyObject( SHPObject * psShape )
 /************************************************************************/
 
 int SHPAPI_CALL
-SHPRewindObject( SHPHandle hSHP, SHPObject * psObject )
-
+SHPRewindObject( CPL_UNUSED SHPHandle hSHP, SHPObject * psObject )
 {
     int  iOpRing, bAltered = 0;
 
diff --git a/ogr/ogrsf_frmts/shape/shptree.c b/ogr/ogrsf_frmts/shape/shptree.c
index a6d4300..aade7ef 100644
--- a/ogr/ogrsf_frmts/shape/shptree.c
+++ b/ogr/ogrsf_frmts/shape/shptree.c
@@ -911,13 +911,13 @@ SHPSearchDiskTreeNode( SHPTreeDiskHandle hDiskTree, double *padfBoundsMin, doubl
 /* -------------------------------------------------------------------- */
     if(numshapes > 0) 
     {
-        if( *pnResultCount + numshapes > *pnBufferMax )
+        if( (int)(*pnResultCount + numshapes) > *pnBufferMax )
         {
             int* pNewBuffer;
 
             *pnBufferMax = (*pnResultCount + numshapes + 100) * 5 / 4;
 
-            if( *pnBufferMax > INT_MAX / sizeof(int) )
+            if( (unsigned int)*pnBufferMax > INT_MAX / sizeof(int) )
                 *pnBufferMax = *pnResultCount + numshapes;
 
             pNewBuffer = (int *)
diff --git a/ogr/ogrsf_frmts/sqlite/ogr_sqlite.h b/ogr/ogrsf_frmts/sqlite/ogr_sqlite.h
index 83391be..36e9966 100644
--- a/ogr/ogrsf_frmts/sqlite/ogr_sqlite.h
+++ b/ogr/ogrsf_frmts/sqlite/ogr_sqlite.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogr_sqlite.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogr_sqlite.h 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Private definitions for OGR/SQLite driver.
@@ -281,8 +281,8 @@ class OGRSQLiteLayer : public OGRLayer
 
     virtual int          HasSpatialIndex() { return bHasSpatialIndex; }
 
-    virtual CPLString     GetSpatialWhere(int iGeomCol,
-                                          OGRGeometry* poFilterGeom) { return ""; }
+    virtual CPLString     GetSpatialWhere(CPL_UNUSED int iGeomCol,
+                                          CPL_UNUSED OGRGeometry* poFilterGeom) { return ""; }
 
     static OGRErr       ImportSpatiaLiteGeometry( const GByte *, int,
                                                   OGRGeometry ** );
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqliteexecutesql.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqliteexecutesql.cpp
index 8a2c12a..7333a45 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqliteexecutesql.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqliteexecutesql.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqliteexecutesql.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqliteexecutesql.cpp 27730 2014-09-24 00:59:45Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Run SQL requests with SQLite SQL engine
@@ -467,6 +467,7 @@ static void OGR2SQLITEGetPotentialLayerNames(const char *pszSQLCommand,
 /*               OGR2SQLITE_IgnoreAllFieldsExceptGeometry()             */
 /************************************************************************/
 
+#if defined(HAVE_SPATIALITE)
 static
 void OGR2SQLITE_IgnoreAllFieldsExceptGeometry(OGRLayer* poLayer)
 {
@@ -481,6 +482,7 @@ void OGR2SQLITE_IgnoreAllFieldsExceptGeometry(OGRLayer* poLayer)
     poLayer->SetIgnoredFields((const char**)papszIgnored);
     CSLDestroy(papszIgnored);
 }
+#endif  // HAVE_SPATIALITE
 
 
 /************************************************************************/
@@ -494,7 +496,13 @@ int OGR2SQLITEDealWithSpatialColumn(OGRLayer* poLayer,
                                     OGRSQLiteDataSource* poSQLiteDS,
                                     sqlite3* hDB,
                                     int bSpatialiteDB,
+#ifndef HAVE_SPATIALITE
+CPL_UNUSED
+#endif
                                     const std::set<LayerDesc>& oSetLayers,
+#ifndef HAVE_SPATIALITE
+CPL_UNUSED
+#endif
                                     const std::set<CPLString>& oSetSpatialIndex
                                    )
 {
@@ -528,7 +536,9 @@ int OGR2SQLITEDealWithSpatialColumn(OGRLayer* poLayer,
         nSRSId = poSQLiteDS->FetchSRSId(poSRS);
 
     CPLString osSQL;
+#ifdef HAVE_SPATIALITE
     int bCreateSpatialIndex = FALSE;
+#endif
     if( !bSpatialiteDB )
     {
         osSQL.Printf("INSERT INTO geometry_columns (f_table_name, "
@@ -709,7 +719,7 @@ int OGR2SQLITEDealWithSpatialColumn(OGRLayer* poLayer,
 OGRLayer * OGRSQLiteExecuteSQL( OGRDataSource* poDS,
                                 const char *pszStatement,
                                 OGRGeometry *poSpatialFilter,
-                                const char *pszDialect )
+                                CPL_UNUSED const char *pszDialect )
 {
     char* pszTmpDBName = (char*) CPLMalloc(256);
     sprintf(pszTmpDBName, "/vsimem/ogr2sqlite/temp_%p.db", pszTmpDBName);
@@ -1052,7 +1062,7 @@ std::set<LayerDesc> OGRSQLiteGetReferencedLayers(const char* pszStatement)
 OGRLayer * OGRSQLiteExecuteSQL( OGRDataSource* poDS,
                                 const char *pszStatement,
                                 OGRGeometry *poSpatialFilter,
-                                const char *pszDialect )
+                                CPL_UNUSED const char *pszDialect )
 {
     CPLError(CE_Failure, CPLE_NotSupported,
                 "The SQLite version is to old to support the SQLite SQL dialect");
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitelayer.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitelayer.cpp
index a5b5bcb..33b494a 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqlitelayer.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqlitelayer.cpp 27102 2014-03-28 09:03:37Z rouault $
+ * $Id: ogrsqlitelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRSQLiteLayer class, code shared between 
@@ -42,7 +42,7 @@
 #include "ogr_sqlite.h"
 #include <cassert>
 
-CPL_CVSID("$Id: ogrsqlitelayer.cpp 27102 2014-03-28 09:03:37Z rouault $");
+CPL_CVSID("$Id: ogrsqlitelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRSQLiteLayer()                           */
@@ -129,7 +129,7 @@ void OGRSQLiteLayer::Finalize()
 
 static
 int OGRIsBinaryGeomCol( sqlite3_stmt *hStmt, int iCol,
-                        OGRFieldDefn& oField,
+                        CPL_UNUSED OGRFieldDefn& oField,
                         OGRSQLiteGeomFormat& eGeomFormat )
 {
     OGRGeometry* poGeometry = NULL;
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqliteregexp.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqliteregexp.cpp
index efa78d3..dc36c22 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqliteregexp.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqliteregexp.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqliteregexp.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqliteregexp.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  SQLite REGEXP function
@@ -167,7 +167,11 @@ void OGRSQLiteREGEXPFunction(sqlite3_context *ctx, int argc, sqlite3_value **arg
 /************************************************************************/
 
 static
-void* OGRSQLiteRegisterRegExpFunction(sqlite3* hDB)
+void* OGRSQLiteRegisterRegExpFunction(
+#ifndef HAVE_PCRE
+CPL_UNUSED
+#endif
+                                      sqlite3* hDB)
 {
 #ifdef HAVE_PCRE
 
@@ -201,7 +205,11 @@ void* OGRSQLiteRegisterRegExpFunction(sqlite3* hDB)
 /************************************************************************/
 
 static
-void OGRSQLiteFreeRegExpCache(void* hRegExpCache)
+void OGRSQLiteFreeRegExpCache(
+#ifndef HAVE_PCRE
+CPL_UNUSED
+#endif
+                              void* hRegExpCache)
 {
 #ifdef HAVE_PCRE
     if( hRegExpCache == NULL )
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitesqlfunctions.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitesqlfunctions.cpp
index a34b5a0..2884bba 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqlitesqlfunctions.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitesqlfunctions.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqlitesqlfunctions.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqlitesqlfunctions.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Extension SQL functions
@@ -69,7 +69,7 @@ class OGRSQLiteExtensionData
 /*                     OGRSQLiteExtensionData()                         */
 /************************************************************************/
 
-OGRSQLiteExtensionData::OGRSQLiteExtensionData(sqlite3* hDB) :
+OGRSQLiteExtensionData::OGRSQLiteExtensionData(CPL_UNUSED sqlite3* hDB) :
         hRegExpCache(NULL), hGeocodingSession(NULL)
 {
 #ifdef DEBUG
@@ -438,8 +438,8 @@ static double OGR2SQLITE_GetValAsDouble(sqlite3_value* val, int* pbGotVal)
 /*                      OGR2SQLITE_GetGeom()                            */
 /************************************************************************/
 
-static OGRGeometry* OGR2SQLITE_GetGeom(sqlite3_context* pContext,
-                                       int argc, sqlite3_value** argv,
+static OGRGeometry* OGR2SQLITE_GetGeom(CPL_UNUSED sqlite3_context* pContext,
+                                       CPL_UNUSED int argc, sqlite3_value** argv,
                                        int* pnSRSId)
 {
     if( sqlite3_value_type (argv[0]) != SQLITE_BLOB )
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitetablelayer.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitetablelayer.cpp
index 5bb4f66..161056e 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqlitetablelayer.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitetablelayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqlitetablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqlitetablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRSQLiteTableLayer class, access to an existing table.
@@ -37,7 +37,7 @@
 
 #define UNSUPPORTED_OP_READ_ONLY "%s : unsupported operation on a read-only datasource."
 
-CPL_CVSID("$Id: ogrsqlitetablelayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsqlitetablelayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRSQLiteTableLayer()                         */
@@ -912,8 +912,7 @@ CPLString OGRSQLiteTableLayer::FieldDefnToSQliteFieldDefn( OGRFieldDefn* poField
 /************************************************************************/
 
 OGRErr OGRSQLiteTableLayer::CreateField( OGRFieldDefn *poFieldIn, 
-                                         int bApproxOK )
-
+                                         CPL_UNUSED int bApproxOK )
 {
     OGRFieldDefn        oField( poFieldIn );
 
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitevfs.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitevfs.cpp
index 6a8cabb..56a3941 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqlitevfs.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitevfs.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqlitevfs.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqlitevfs.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements SQLite VFS
@@ -30,7 +30,7 @@
 #include "cpl_atomic_ops.h"
 #include "ogr_sqlite.h"
 
-CPL_CVSID("$Id: ogrsqlitevfs.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsqlitevfs.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 //#define DEBUG_IO 1
 
@@ -109,7 +109,15 @@ static int OGRSQLiteIOTruncate(sqlite3_file* pFile, sqlite3_int64 size)
     return (nRet == 0) ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
 }
 
-static int OGRSQLiteIOSync(sqlite3_file* pFile, int flags)
+static int OGRSQLiteIOSync(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                           sqlite3_file* pFile,
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                           int flags)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -131,7 +139,15 @@ static int OGRSQLiteIOFileSize(sqlite3_file* pFile, sqlite3_int64 *pSize)
     return SQLITE_OK;
 }
 
-static int OGRSQLiteIOLock(sqlite3_file* pFile, int flags)
+static int OGRSQLiteIOLock(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                           sqlite3_file* pFile,
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                           int flags)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -140,7 +156,7 @@ static int OGRSQLiteIOLock(sqlite3_file* pFile, int flags)
     return SQLITE_OK;
 }
 
-static int OGRSQLiteIOUnlock(sqlite3_file* pFile, int flags)
+static int OGRSQLiteIOUnlock(CPL_UNUSED sqlite3_file* pFile, CPL_UNUSED int flags)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -149,7 +165,15 @@ static int OGRSQLiteIOUnlock(sqlite3_file* pFile, int flags)
     return SQLITE_OK;
 }
 
-static int OGRSQLiteIOCheckReservedLock(sqlite3_file* pFile, int *pResOut)
+static int OGRSQLiteIOCheckReservedLock(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                        sqlite3_file* pFile,
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                        int *pResOut)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -159,7 +183,19 @@ static int OGRSQLiteIOCheckReservedLock(sqlite3_file* pFile, int *pResOut)
     return SQLITE_OK;
 }
 
-static int OGRSQLiteIOFileControl(sqlite3_file* pFile, int op, void *pArg)
+static int OGRSQLiteIOFileControl(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                  sqlite3_file* pFile,
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                  int op,
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                  void *pArg)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -168,7 +204,11 @@ static int OGRSQLiteIOFileControl(sqlite3_file* pFile, int op, void *pArg)
     return SQLITE_NOTFOUND;
 }
 
-static int OGRSQLiteIOSectorSize(sqlite3_file* pFile)
+static int OGRSQLiteIOSectorSize(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                 sqlite3_file* pFile)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -177,7 +217,11 @@ static int OGRSQLiteIOSectorSize(sqlite3_file* pFile)
     return 0;
 }
 
-static int OGRSQLiteIODeviceCharacteristics(sqlite3_file* pFile)
+static int OGRSQLiteIODeviceCharacteristics(
+#ifndef DEBUG_IO
+CPL_UNUSED 
+#endif
+                                            sqlite3_file* pFile)
 {
 #ifdef DEBUG_IO
     OGRSQLiteFileStruct* pMyFile = (OGRSQLiteFileStruct*) pFile;
@@ -201,6 +245,15 @@ static const sqlite3_io_methods OGRSQLiteIOMethods =
     OGRSQLiteIOFileControl,
     OGRSQLiteIOSectorSize,
     OGRSQLiteIODeviceCharacteristics
+#if 0
+    // TODO: These are in sqlite3.
+    0, // xShmMap
+    0, // xShmLock
+    0, // xShmBarrier
+    0, // xShmUnmap
+    0, // xFetch
+    0 // xUnfetch
+#endif
 };
 
 static int OGRSQLiteVFSOpen(sqlite3_vfs* pVFS,
@@ -257,7 +310,9 @@ static int OGRSQLiteVFSOpen(sqlite3_vfs* pVFS,
     return SQLITE_OK;
 }
 
-static int OGRSQLiteVFSDelete(sqlite3_vfs* pVFS, const char *zName, int syncDir)
+static int OGRSQLiteVFSDelete(CPL_UNUSED sqlite3_vfs* pVFS,
+                              const char *zName,
+                              CPL_UNUSED int syncDir)
 {
 #ifdef DEBUG_IO
     CPLDebug("SQLITE", "OGRSQLiteVFSDelete(%s)", zName);
@@ -266,7 +321,7 @@ static int OGRSQLiteVFSDelete(sqlite3_vfs* pVFS, const char *zName, int syncDir)
     return SQLITE_OK;
 }
 
-static int OGRSQLiteVFSAccess (sqlite3_vfs* pVFS, const char *zName, int flags, int *pResOut)
+static int OGRSQLiteVFSAccess (CPL_UNUSED sqlite3_vfs* pVFS, const char *zName, int flags, int *pResOut)
 {
 #ifdef DEBUG_IO
     CPLDebug("SQLITE", "OGRSQLiteVFSAccess(%s, %d)", zName, flags);
diff --git a/ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp b/ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp
index dda8866..9abda33 100644
--- a/ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp
+++ b/ogr/ogrsf_frmts/sqlite/ogrsqlitevirtualogr.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsqlitevirtualogr.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsqlitevirtualogr.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  SQLite Virtual Table module using OGR layers
@@ -879,7 +879,7 @@ int OGR2SQLITE_Close(sqlite3_vtab_cursor* pCursor)
 
 static
 int OGR2SQLITE_Filter(sqlite3_vtab_cursor* pCursor,
-                      int idxNum, const char *idxStr,
+                      CPL_UNUSED int idxNum, const char *idxStr,
                       int argc, sqlite3_value **argv)
 {
     OGR2SQLITE_vtab_cursor* pMyCursor = (OGR2SQLITE_vtab_cursor*) pCursor;
@@ -1330,7 +1330,7 @@ int OGR2SQLITE_Rowid(sqlite3_vtab_cursor* pCursor, sqlite3_int64 *pRowid)
 /************************************************************************/
 
 static
-int OGR2SQLITE_Rename(sqlite3_vtab *pVtab, const char *zNew)
+int OGR2SQLITE_Rename(CPL_UNUSED sqlite3_vtab *pVtab, CPL_UNUSED const char *zNew)
 {
     //CPLDebug("OGR2SQLITE", "Rename");
     return SQLITE_ERROR;
diff --git a/ogr/ogrsf_frmts/sua/ogrsuadatasource.cpp b/ogr/ogrsf_frmts/sua/ogrsuadatasource.cpp
index b84ec42..71d3406 100644
--- a/ogr/ogrsf_frmts/sua/ogrsuadatasource.cpp
+++ b/ogr/ogrsf_frmts/sua/ogrsuadatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsuadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsuadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SUA Translator
  * Purpose:  Implements OGRSUADataSource class
@@ -31,7 +31,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrsuadatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsuadatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRSUADataSource()                          */
@@ -64,8 +64,7 @@ OGRSUADataSource::~OGRSUADataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSUADataSource::TestCapability( const char * pszCap )
-
+int OGRSUADataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/sua/ogrsuadriver.cpp b/ogr/ogrsf_frmts/sua/ogrsuadriver.cpp
index 67e9346..50160f0 100644
--- a/ogr/ogrsf_frmts/sua/ogrsuadriver.cpp
+++ b/ogr/ogrsf_frmts/sua/ogrsuadriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsuadriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsuadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SUA Translator
  * Purpose:  Implements OGRSUADriver.
@@ -30,7 +30,7 @@
 #include "ogr_sua.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsuadriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsuadriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRSUA();
 
@@ -75,8 +75,7 @@ OGRDataSource *OGRSUADriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSUADriver::TestCapability( const char * pszCap )
-
+int OGRSUADriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/sua/ogrsualayer.cpp b/ogr/ogrsf_frmts/sua/ogrsualayer.cpp
index d0d6812..1966d53 100644
--- a/ogr/ogrsf_frmts/sua/ogrsualayer.cpp
+++ b/ogr/ogrsf_frmts/sua/ogrsualayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsualayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsualayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SUA Translator
  * Purpose:  Implements OGRSUALayer class.
@@ -34,7 +34,7 @@
 #include "ogr_xplane_geo_utils.h"
 #include "ogr_srs_api.h"
 
-CPL_CVSID("$Id: ogrsualayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsualayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRSUALayer()                             */
@@ -361,8 +361,7 @@ OGRFeature *OGRSUALayer::GetNextRawFeature()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSUALayer::TestCapability( const char * pszCap )
-
+int OGRSUALayer::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp b/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp
index 7ba6b0c..47665c3 100644
--- a/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp
+++ b/ogr/ogrsf_frmts/svg/ogrsvgdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsvgdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsvgdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SVG Translator
  * Purpose:  Implements OGRSVGDataSource class
@@ -30,7 +30,7 @@
 #include "ogr_svg.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsvgdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsvgdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRSVGDataSource()                          */
@@ -110,7 +110,7 @@ void OGRSVGDataSource::startElementValidateCbk(const char *pszName,
 /*                      dataHandlerValidateCbk()                        */
 /************************************************************************/
 
-void OGRSVGDataSource::dataHandlerValidateCbk(const char *data, int nLen)
+void OGRSVGDataSource::dataHandlerValidateCbk(CPL_UNUSED const char *data, CPL_UNUSED int nLen)
 {
     nDataHandlerCounter ++;
     if (nDataHandlerCounter >= BUFSIZ)
@@ -272,7 +272,7 @@ int OGRSVGDataSource::Open( const char * pszFilename, int bUpdateIn)
 /*                            TestCapability()                          */
 /************************************************************************/
 
-int OGRSVGDataSource::TestCapability( const char *pszCap )
+int OGRSVGDataSource::TestCapability( CPL_UNUSED const char *pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/svg/ogrsvgdriver.cpp b/ogr/ogrsf_frmts/svg/ogrsvgdriver.cpp
index 864379b..2591fee 100644
--- a/ogr/ogrsf_frmts/svg/ogrsvgdriver.cpp
+++ b/ogr/ogrsf_frmts/svg/ogrsvgdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsvgdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsvgdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SVG Translator
  * Purpose:  Implements OGRSVGDriver.
@@ -30,7 +30,7 @@
 #include "ogr_svg.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsvgdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsvgdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 CPL_C_START
 void RegisterOGRSVG();
@@ -84,7 +84,7 @@ OGRDataSource *OGRSVGDriver::Open( const char * pszFilename, int bUpdate )
 /*                            TestCapability()                          */
 /************************************************************************/
 
-int OGRSVGDriver::TestCapability( const char *pszCap )
+int OGRSVGDriver::TestCapability( CPL_UNUSED const char *pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/svg/ogrsvglayer.cpp b/ogr/ogrsf_frmts/svg/ogrsvglayer.cpp
index e6c9a91..2ad5283 100644
--- a/ogr/ogrsf_frmts/svg/ogrsvglayer.cpp
+++ b/ogr/ogrsf_frmts/svg/ogrsvglayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrsvglayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrsvglayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  SVG Translator
  * Purpose:  Implements OGRSVGLayer class.
@@ -30,7 +30,7 @@
 #include "ogr_svg.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrsvglayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrsvglayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRSVGLayer()                             */
@@ -428,7 +428,7 @@ void OGRSVGLayer::startElementCbk(const char *pszName, const char **ppszAttr)
 /*                           endElementCbk()                            */
 /************************************************************************/
 
-void OGRSVGLayer::endElementCbk(const char *pszName)
+void OGRSVGLayer::endElementCbk(CPL_UNUSED const char *pszName)
 {
     if (bStopParsing) return;
 
@@ -758,7 +758,7 @@ void OGRSVGLayer::startElementLoadSchemaCbk(const char *pszName,
 /*                   endElementLoadSchemaCbk()                           */
 /************************************************************************/
 
-void OGRSVGLayer::endElementLoadSchemaCbk(const char *pszName)
+void OGRSVGLayer::endElementLoadSchemaCbk(CPL_UNUSED const char *pszName)
 {
     if (bStopParsing) return;
 
@@ -777,7 +777,7 @@ void OGRSVGLayer::endElementLoadSchemaCbk(const char *pszName)
 /*                   dataHandlerLoadSchemaCbk()                         */
 /************************************************************************/
 
-void OGRSVGLayer::dataHandlerLoadSchemaCbk(const char *data, int nLen)
+void OGRSVGLayer::dataHandlerLoadSchemaCbk(CPL_UNUSED const char *data, CPL_UNUSED int nLen)
 {
     if (bStopParsing) return;
 
diff --git a/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp b/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp
index b1d587b..de56747 100644
--- a/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp
+++ b/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp
@@ -134,8 +134,7 @@ void  OGRSXFDataSource::CloseFile()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRSXFDataSource::TestCapability( const char * pszCap )
-
+int OGRSXFDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
@@ -594,7 +593,7 @@ OGRErr OGRSXFDataSource::ReadSXFMapDescription(VSILFILE* fpSXF, SXFPassport& pas
     long iEllips = anData[0];
     long iVCS = anData[1];
     long iProjSys = anData[2];
-    long iDatum = anData[3];
+    /* long iDatum = anData[3]; Unused. */
     double dfProjScale = 1;
 
     double adfPrjParams[8] = { 0 };
@@ -893,7 +892,7 @@ void OGRSXFDataSource::FillLayers()
         {
             delete pOGRSXFLayer;
             nDeletedLayerIndex = i;
-            while (nDeletedLayerIndex < nLayers - 1)
+            while (nDeletedLayerIndex < (int)(nLayers - 1))
             {
                 papoLayers[nDeletedLayerIndex] = papoLayers[nDeletedLayerIndex + 1];
                 nDeletedLayerIndex++;
@@ -1210,7 +1209,7 @@ void OGRSXFDataSource::CreateLayers(VSILFILE* fpRSC)
     vsi_l_offset nOffset = stRSCFileHeader.Layers.nOffset;
     _layer LAYER;
 
-    for (i = 0; i < stRSCFileHeader.Layers.nRecordCount; ++i)
+    for (i = 0; (GUInt32)i < stRSCFileHeader.Layers.nRecordCount; ++i)
     {
         VSIFReadL(&LAYER, nLayerStructSize, 1, fpRSC);
 
diff --git a/ogr/ogrsf_frmts/sxf/ogrsxflayer.cpp b/ogr/ogrsf_frmts/sxf/ogrsxflayer.cpp
index a733fd3..3562156 100644
--- a/ogr/ogrsf_frmts/sxf/ogrsxflayer.cpp
+++ b/ogr/ogrsf_frmts/sxf/ogrsxflayer.cpp
@@ -134,7 +134,7 @@ int OGRSXFLayer::AddRecord(long nFID, unsigned nClassCode, vsi_l_offset nOffset,
         {
             size_t offset = 0;
 
-            while (offset < nSemanticsSize)
+            while (offset < (size_t)nSemanticsSize)
             {
                 SXFRecordAttributeInfo stAttrInfo;
                 bool bAddField = false;
@@ -276,7 +276,7 @@ int OGRSXFLayer::AddRecord(long nFID, unsigned nClassCode, vsi_l_offset nOffset,
 
 OGRErr OGRSXFLayer::SetNextByIndex(long nIndex)
 {
-    if (nIndex < 0 || nIndex > mnRecordDesc.size())
+  if (nIndex < 0 || (size_t)nIndex > mnRecordDesc.size())
         return OGRERR_FAILURE;
 
     oNextIt = mnRecordDesc.begin();
@@ -1139,7 +1139,7 @@ OGRFeature *OGRSXFLayer::TranslateLine(const SXFRecordDescription& certifInfo,
                   "SXF. 3D metrics do not support." );
 	}
 
-    for(int count=0 ; count <  certifInfo.nPointCount ; count++)
+    for(int count=0 ; (GUInt32)count <  certifInfo.nPointCount ; count++)
     {
         const char * psCoords = psRecordBuf + nOffset ;
         GUInt32 nDelta = TranslateXYH( certifInfo, psCoords, nBufLen - nOffset, &dfX, &dfY );
@@ -1230,7 +1230,7 @@ OGRFeature *OGRSXFLayer::TranslateVetorAngle(const SXFRecordDescription& certifI
             "SXF. 3D metrics do not support.");
     }
 
-    for (int count = 0; count < certifInfo.nPointCount; count++)
+    for (int count = 0; (GUInt32)count < certifInfo.nPointCount; count++)
     {
         const char * psCoords = psRecordBuf + nOffset;
         GUInt32 nDelta = TranslateXYH(certifInfo, psCoords, nBufLen - nOffset, &dfX, &dfY);
@@ -1289,7 +1289,7 @@ OGRFeature *OGRSXFLayer::TranslatePolygon(const SXFRecordDescription& certifInfo
 					"SXF. 3D metrics do not support." );
 	}
 
-    for(int count=0 ; count <  certifInfo.nPointCount ; count++)
+    for(int count=0 ; (GUInt32)count <  certifInfo.nPointCount ; count++)
     {
         const char * psBuf = psRecordBuf + nOffset ;
 
@@ -1378,7 +1378,7 @@ OGRFeature *OGRSXFLayer::TranslateText(const SXFRecordDescription& certifInfo,
 					"SXF. 3D metrics do not support." );
 	}
 
-    for(int count=0 ; count <  certifInfo.nPointCount ; count++)
+    for(int count=0 ; (GUInt32)count <  certifInfo.nPointCount ; count++)
     {
         const char * psBuf = psRecordBuf + nOffset;
         GUInt32 nDelta = TranslateXYH( certifInfo, psBuf, nBufLen - nOffset, &dfX, &dfY );
diff --git a/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp b/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp
index 98bc4fd..6a22a33 100644
--- a/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp
+++ b/ogr/ogrsf_frmts/tiger/ogrtigerdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrtigerdatasource.cpp 24433 2012-05-17 16:21:43Z rouault $
+ * $Id: ogrtigerdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements OGRTigerDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_string.h"
 #include <ctype.h>
 
-CPL_CVSID("$Id: ogrtigerdatasource.cpp 24433 2012-05-17 16:21:43Z rouault $");
+CPL_CVSID("$Id: ogrtigerdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        TigerClassifyVersion()                        */
@@ -318,6 +318,11 @@ int OGRTigerDataSource::Open( const char * pszFilename, int bTestOpen,
     if( VSI_ISREG(stat.st_mode) )
     {
         char       szModule[128];
+        
+        if( strlen(CPLGetFilename(pszFilename)) == 0 )
+        {
+            return FALSE;
+        }
 
         pszPath = CPLStrdup( CPLGetPath(pszFilename) );
 
@@ -815,8 +820,8 @@ int OGRTigerDataSource::Create( const char *pszNameIn, char **papszOptions )
 
 OGRLayer *OGRTigerDataSource::CreateLayer( const char *pszLayerName, 
                                            OGRSpatialReference *poSpatRef, 
-                                           OGRwkbGeometryType eGType, 
-                                           char **papszOptions )
+                                           CPL_UNUSED OGRwkbGeometryType eGType, 
+                                           CPL_UNUSED char **papszOptions )
 
 {
     OGRTigerLayer       *poLayer = NULL;
diff --git a/ogr/ogrsf_frmts/tiger/ogrtigerlayer.cpp b/ogr/ogrsf_frmts/tiger/ogrtigerlayer.cpp
index 95670bd..78b7ac4 100644
--- a/ogr/ogrsf_frmts/tiger/ogrtigerlayer.cpp
+++ b/ogr/ogrsf_frmts/tiger/ogrtigerlayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrtigerlayer.cpp 26466 2013-09-14 09:07:46Z rouault $
+ * $Id: ogrtigerlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements OGRTigerLayer class.
@@ -29,7 +29,7 @@
 
 #include "ogr_tiger.h"
 
-CPL_CVSID("$Id: ogrtigerlayer.cpp 26466 2013-09-14 09:07:46Z rouault $");
+CPL_CVSID("$Id: ogrtigerlayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           OGRTigerLayer()                            */
@@ -245,11 +245,9 @@ OGRFeatureDefn *OGRTigerLayer::GetLayerDefn()
 /*                            CreateField()                             */
 /************************************************************************/
 
-OGRErr OGRTigerLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRTigerLayer::CreateField( CPL_UNUSED OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     /* notdef/TODO: I should add some checking here eventually. */
-
     return OGRERR_NONE;
 }
 
diff --git a/ogr/ogrsf_frmts/tiger/tigeraltname.cpp b/ogr/ogrsf_frmts/tiger/tigeraltname.cpp
index 20dc291..8d1b340 100644
--- a/ogr/ogrsf_frmts/tiger/tigeraltname.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigeraltname.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigeraltname.cpp 23871 2012-02-02 03:24:07Z warmerdam $
+ * $Id: tigeraltname.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerAltName, providing access to RT4 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigeraltname.cpp 23871 2012-02-02 03:24:07Z warmerdam $");
+CPL_CVSID("$Id: tigeraltname.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "4"
 
@@ -58,8 +58,7 @@ static const TigerRecordInfo rt4_info =
 /************************************************************************/
 
 TigerAltName::TigerAltName( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) : TigerFileBase(&rt4_info, FILE_CODE)
-
+                            CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rt4_info, FILE_CODE)
 {
     OGRFieldDefn        oField("",OFTInteger);
 
diff --git a/ogr/ogrsf_frmts/tiger/tigerarealandmarks.cpp b/ogr/ogrsf_frmts/tiger/tigerarealandmarks.cpp
index 9b9fce5..be84dc1 100644
--- a/ogr/ogrsf_frmts/tiger/tigerarealandmarks.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerarealandmarks.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerarealandmarks.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerarealandmarks.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerAreaLandmarks, providing access to .RT8 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerarealandmarks.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerarealandmarks.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "8"
 
@@ -57,8 +57,7 @@ static const TigerRecordInfo rt8_info =
 /************************************************************************/
 
 TigerAreaLandmarks::TigerAreaLandmarks( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule ) : TigerFileBase(&rt8_info, FILE_CODE)
-
+                                        CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rt8_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "AreaLandmarks" );
diff --git a/ogr/ogrsf_frmts/tiger/tigercompletechain.cpp b/ogr/ogrsf_frmts/tiger/tigercompletechain.cpp
index 4bc0d8c..65f719f 100644
--- a/ogr/ogrsf_frmts/tiger/tigercompletechain.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigercompletechain.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigercompletechain.cpp 23871 2012-02-02 03:24:07Z warmerdam $
+ * $Id: tigercompletechain.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerCompleteChain, providing access to RT1 and
@@ -31,7 +31,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigercompletechain.cpp 23871 2012-02-02 03:24:07Z warmerdam $");
+CPL_CVSID("$Id: tigercompletechain.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static const TigerFieldInfo rt1_2002_fields[] = {
   // fieldname    fmt  type OFTType      beg  end  len  bDefine bSet bWrite
@@ -215,8 +215,7 @@ static const TigerRecordInfo rt3_info =
 /************************************************************************/
 
 TigerCompleteChain::TigerCompleteChain( OGRTigerDataSource * poDSIn,
-                                        const char * pszPrototypeModule )
-
+                                        CPL_UNUSED const char * pszPrototypeModule )
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "CompleteChain" );
@@ -483,8 +482,7 @@ OGRFeature *TigerCompleteChain::GetFeature( int nRecordId )
 /************************************************************************/
 
 int TigerCompleteChain::AddShapePoints( int nTLID, int nRecordId,
-                                        OGRLineString * poLine, int nSeqNum ) 
-
+                                        OGRLineString * poLine, CPL_UNUSED int nSeqNum )
 {
     int         nShapeRecId;
 
diff --git a/ogr/ogrsf_frmts/tiger/tigerentitynames.cpp b/ogr/ogrsf_frmts/tiger/tigerentitynames.cpp
index b2bfbca..92da158 100644
--- a/ogr/ogrsf_frmts/tiger/tigerentitynames.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerentitynames.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerentitynames.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: tigerentitynames.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerEntityNames, providing access to .RTC files.
@@ -31,7 +31,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerentitynames.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: tigerentitynames.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "C"
 
@@ -120,8 +120,7 @@ static const TigerRecordInfo rtC_info =
 /************************************************************************/
 
 TigerEntityNames::TigerEntityNames( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
-
+                                    CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "EntityNames" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerfeatureids.cpp b/ogr/ogrsf_frmts/tiger/tigerfeatureids.cpp
index faa8be6..f21a41a 100644
--- a/ogr/ogrsf_frmts/tiger/tigerfeatureids.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerfeatureids.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerfeatureids.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerfeatureids.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerFeatureIds, providing access to .RT5 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerfeatureids.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerfeatureids.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "5"
 
@@ -76,8 +76,7 @@ static const TigerRecordInfo rt5_info =
 /************************************************************************/
 
 TigerFeatureIds::TigerFeatureIds( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
-
+                                  CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
 {
   poDS = poDSIn;
   poFeatureDefn = new OGRFeatureDefn( "FeatureIds" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerfilebase.cpp b/ogr/ogrsf_frmts/tiger/tigerfilebase.cpp
index 1593d8a..0be5361 100644
--- a/ogr/ogrsf_frmts/tiger/tigerfilebase.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerfilebase.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerfilebase.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: tigerfilebase.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerBaseFile class, providing common services to all
@@ -34,7 +34,7 @@
 #include "cpl_error.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: tigerfilebase.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: tigerfilebase.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                           TigerFileBase()                            */
@@ -394,9 +394,8 @@ int TigerFileBase::WriteRecord( char *pachRecord, int nRecLen,
 /*      Setup our access to be to the module indicated in the feature.  */
 /************************************************************************/
 
-int TigerFileBase::SetWriteModule( const char *pszExtension, int nRecLen,
+int TigerFileBase::SetWriteModule( const char *pszExtension, CPL_UNUSED int nRecLen,
                                    OGRFeature *poFeature )
-
 {
 /* -------------------------------------------------------------------- */
 /*      Work out what module we should be writing to.                   */
diff --git a/ogr/ogrsf_frmts/tiger/tigeridhistory.cpp b/ogr/ogrsf_frmts/tiger/tigeridhistory.cpp
index b8f94ac..78b9132 100644
--- a/ogr/ogrsf_frmts/tiger/tigeridhistory.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigeridhistory.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigeridhistory.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigeridhistory.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerIDHistory, providing access to .RTH files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigeridhistory.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigeridhistory.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "H"
 
@@ -60,8 +60,7 @@ static const TigerRecordInfo rtH_info =
 /************************************************************************/
 
 TigerIDHistory::TigerIDHistory( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) : TigerFileBase(&rtH_info, FILE_CODE)
-
+                                CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rtH_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "IDHistory" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerkeyfeatures.cpp b/ogr/ogrsf_frmts/tiger/tigerkeyfeatures.cpp
index 88c1062..20474e9 100644
--- a/ogr/ogrsf_frmts/tiger/tigerkeyfeatures.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerkeyfeatures.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerkeyfeatures.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerkeyfeatures.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerKeyFeatures, providing access to .RT9 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerkeyfeatures.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerkeyfeatures.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "9"
 
@@ -63,8 +63,7 @@ static const TigerRecordInfo rt9_info =
 /************************************************************************/
 
 TigerKeyFeatures::TigerKeyFeatures( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule ) : TigerFileBase(&rt9_info, FILE_CODE)
-
+                                    CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rt9_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "KeyFeatures" );
@@ -76,5 +75,4 @@ TigerKeyFeatures::TigerKeyFeatures( OGRTigerDataSource * poDSIn,
     /* -------------------------------------------------------------------- */
 
     AddFieldDefns( psRTInfo, poFeatureDefn );
-
 }
diff --git a/ogr/ogrsf_frmts/tiger/tigerlandmarks.cpp b/ogr/ogrsf_frmts/tiger/tigerlandmarks.cpp
index 900d7f6..13327ca 100644
--- a/ogr/ogrsf_frmts/tiger/tigerlandmarks.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerlandmarks.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerlandmarks.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerlandmarks.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerLandmarks, providing access to .RT7 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerlandmarks.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerlandmarks.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "7"
 
@@ -76,7 +76,7 @@ static const TigerRecordInfo rt7_info =
 /************************************************************************/
 
 TigerLandmarks::TigerLandmarks( OGRTigerDataSource * poDSIn,
-                                const char * pszPrototypeModule )
+                                CPL_UNUSED const char * pszPrototypeModule )
   : TigerPoint(FALSE, NULL, FILE_CODE)
 {
     poDS = poDSIn;
diff --git a/ogr/ogrsf_frmts/tiger/tigeroverunder.cpp b/ogr/ogrsf_frmts/tiger/tigeroverunder.cpp
index fc5fff4..c65b8a0 100644
--- a/ogr/ogrsf_frmts/tiger/tigeroverunder.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigeroverunder.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigeroverunder.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigeroverunder.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerOverUnder, providing access to .RTU files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigeroverunder.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigeroverunder.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE       "U"
 
@@ -60,7 +60,8 @@ static const TigerRecordInfo rtU_info =
 /************************************************************************/
 
 TigerOverUnder::TigerOverUnder( OGRTigerDataSource * poDSIn,
-                              const char * pszPrototypeModule ) : TigerPoint(TRUE, &rtU_info, FILE_CODE)
+                                CPL_UNUSED const char * pszPrototypeModule )
+  : TigerPoint(TRUE, &rtU_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "OverUnder" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerpip.cpp b/ogr/ogrsf_frmts/tiger/tigerpip.cpp
index 9286bb9..491c88f 100644
--- a/ogr/ogrsf_frmts/tiger/tigerpip.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerpip.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerpip.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerpip.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerPIP, providing access to .RTP files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerpip.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerpip.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "P"
 
@@ -73,7 +73,7 @@ static const TigerRecordInfo rtP_info =
 /************************************************************************/
 
 TigerPIP::TigerPIP( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) 
+                    CPL_UNUSED const char * pszPrototypeModule ) 
   : TigerPoint(TRUE, NULL, FILE_CODE)
 {
     poDS = poDSIn;
diff --git a/ogr/ogrsf_frmts/tiger/tigerpolychainlink.cpp b/ogr/ogrsf_frmts/tiger/tigerpolychainlink.cpp
index 411eca9..7584e2b 100644
--- a/ogr/ogrsf_frmts/tiger/tigerpolychainlink.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerpolychainlink.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerpolychainlink.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerpolychainlink.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerPolyChainLink, providing access to .RTI files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerpolychainlink.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerpolychainlink.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "I"
 
@@ -84,8 +84,8 @@ static const TigerRecordInfo rtI_info =
 /************************************************************************/
 
 TigerPolyChainLink::TigerPolyChainLink( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
-
+                                        CPL_UNUSED const char * pszPrototypeModule )
+  : TigerFileBase(NULL, FILE_CODE)
 {
     OGRFieldDefn        oField("",OFTInteger);
 
diff --git a/ogr/ogrsf_frmts/tiger/tigerpolygon.cpp b/ogr/ogrsf_frmts/tiger/tigerpolygon.cpp
index a288df7..ae8d7f2 100644
--- a/ogr/ogrsf_frmts/tiger/tigerpolygon.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerpolygon.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerpolygon.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: tigerpolygon.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerPolygon, providing access to .RTA files.
@@ -31,7 +31,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerpolygon.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: tigerpolygon.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 static const TigerFieldInfo rtA_2002_fields[] = {
   // fieldname    fmt  type OFTType      beg  end  len  bDefine bSet bWrite
@@ -382,8 +382,7 @@ static const TigerRecordInfo rtS_info =
 /************************************************************************/
 
 TigerPolygon::TigerPolygon( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule )
-
+                            CPL_UNUSED const char * pszPrototypeModule )
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "Polygon" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerpolygoncorrections.cpp b/ogr/ogrsf_frmts/tiger/tigerpolygoncorrections.cpp
index 497a3e0..d57a129 100644
--- a/ogr/ogrsf_frmts/tiger/tigerpolygoncorrections.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerpolygoncorrections.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerpolygoncorrections.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerpolygoncorrections.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerPolygonCorrections, providing access to .RTB files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerpolygoncorrections.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerpolygoncorrections.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE       "B"
 
@@ -70,8 +70,7 @@ static const TigerRecordInfo rtB_info =
 /************************************************************************/
 
 TigerPolygonCorrections::TigerPolygonCorrections( OGRTigerDataSource * poDSIn,
-                              const char * pszPrototypeModule ) : TigerFileBase(&rtB_info, FILE_CODE)
-
+                                                  CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rtB_info, FILE_CODE)
 {
     OGRFieldDefn        oField("",OFTInteger);
 
diff --git a/ogr/ogrsf_frmts/tiger/tigerpolygoneconomic.cpp b/ogr/ogrsf_frmts/tiger/tigerpolygoneconomic.cpp
index 0a7789f..7654d35 100644
--- a/ogr/ogrsf_frmts/tiger/tigerpolygoneconomic.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerpolygoneconomic.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerpolygoneconomic.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerpolygoneconomic.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerPolygonEconomic, providing access to .RTE files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerpolygoneconomic.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerpolygoneconomic.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE       "E"
 
@@ -84,8 +84,7 @@ static const TigerRecordInfo rtE_info =
 /************************************************************************/
 
 TigerPolygonEconomic::TigerPolygonEconomic( OGRTigerDataSource * poDSIn,
-                              const char * pszPrototypeModule ) : TigerFileBase(&rtE_info, FILE_CODE)
-
+                                            CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rtE_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "PolygonEconomic" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerspatialmetadata.cpp b/ogr/ogrsf_frmts/tiger/tigerspatialmetadata.cpp
index a3cec0c..5c3e085 100644
--- a/ogr/ogrsf_frmts/tiger/tigerspatialmetadata.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerspatialmetadata.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerspatialmetadata.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerspatialmetadata.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerSpatialMetadata, providing access to .RTM files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerspatialmetadata.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerspatialmetadata.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "M"
 
@@ -58,8 +58,8 @@ static const TigerRecordInfo rtM_info =
 /************************************************************************/
 
 TigerSpatialMetadata::TigerSpatialMetadata( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) : TigerFileBase(&rtM_info, FILE_CODE)
-
+                                            CPL_UNUSED const char * pszPrototypeModule )
+  : TigerFileBase(&rtM_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "SpatialMetadata" );
diff --git a/ogr/ogrsf_frmts/tiger/tigertlidrange.cpp b/ogr/ogrsf_frmts/tiger/tigertlidrange.cpp
index 58cd2ce..0559757 100644
--- a/ogr/ogrsf_frmts/tiger/tigertlidrange.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigertlidrange.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigertlidrange.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigertlidrange.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerTLIDRange, providing access to .RTR files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigertlidrange.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigertlidrange.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "R"
 
@@ -78,8 +78,8 @@ static const TigerRecordInfo rtR_info =
 /************************************************************************/
 
 TigerTLIDRange::TigerTLIDRange( OGRTigerDataSource * poDSIn,
-                            const char * pszPrototypeModule ) : TigerFileBase(NULL, FILE_CODE)
-
+                                CPL_UNUSED const char * pszPrototypeModule )
+  : TigerFileBase(NULL, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "TLIDRange" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerzerocellid.cpp b/ogr/ogrsf_frmts/tiger/tigerzerocellid.cpp
index 63c6e6d..c69c264 100644
--- a/ogr/ogrsf_frmts/tiger/tigerzerocellid.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerzerocellid.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerzerocellid.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerzerocellid.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerZeroCellID, providing access to .RTT files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerzerocellid.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerzerocellid.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE       "T"
 
@@ -54,8 +54,8 @@ static const TigerRecordInfo rtT_info =
 /************************************************************************/
 
 TigerZeroCellID::TigerZeroCellID( OGRTigerDataSource * poDSIn,
-                              const char * pszPrototypeModule ) : TigerFileBase(&rtT_info, FILE_CODE)
-
+                                  CPL_UNUSED const char * pszPrototypeModule )
+  : TigerFileBase(&rtT_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "ZeroCellID" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerzipcodes.cpp b/ogr/ogrsf_frmts/tiger/tigerzipcodes.cpp
index b1c5396..9722f93 100644
--- a/ogr/ogrsf_frmts/tiger/tigerzipcodes.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerzipcodes.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerzipcodes.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerzipcodes.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerZipCodes, providing access to .RT6 files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerzipcodes.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerzipcodes.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE "6"
 
@@ -62,8 +62,7 @@ static const TigerRecordInfo rt6_info =
 /************************************************************************/
 
 TigerZipCodes::TigerZipCodes( OGRTigerDataSource * poDSIn,
-                                  const char * pszPrototypeModule ) : TigerFileBase(&rt6_info, FILE_CODE)
-
+                              CPL_UNUSED const char * pszPrototypeModule ) : TigerFileBase(&rt6_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "ZipCodes" );
diff --git a/ogr/ogrsf_frmts/tiger/tigerzipplus4.cpp b/ogr/ogrsf_frmts/tiger/tigerzipplus4.cpp
index d109f1f..5a6bc82 100644
--- a/ogr/ogrsf_frmts/tiger/tigerzipplus4.cpp
+++ b/ogr/ogrsf_frmts/tiger/tigerzipplus4.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: tigerzipplus4.cpp 22961 2011-08-20 17:09:59Z rouault $
+ * $Id: tigerzipplus4.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  TIGER/Line Translator
  * Purpose:  Implements TigerZipPlus4, providing access to .RTZ files.
@@ -30,7 +30,7 @@
 #include "ogr_tiger.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: tigerzipplus4.cpp 22961 2011-08-20 17:09:59Z rouault $");
+CPL_CVSID("$Id: tigerzipplus4.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define FILE_CODE       "Z"
 
@@ -54,8 +54,8 @@ static const TigerRecordInfo rtZ_info =
 /************************************************************************/
 
 TigerZipPlus4::TigerZipPlus4( OGRTigerDataSource * poDSIn,
-                              const char * pszPrototypeModule ) : TigerFileBase(&rtZ_info, FILE_CODE)
-
+                              CPL_UNUSED const char * pszPrototypeModule )
+  : TigerFileBase(&rtZ_info, FILE_CODE)
 {
     poDS = poDSIn;
     poFeatureDefn = new OGRFeatureDefn( "ZipPlus4" );
diff --git a/ogr/ogrsf_frmts/vfk/ogrvfkdriver.cpp b/ogr/ogrsf_frmts/vfk/ogrvfkdriver.cpp
index 7f22ad3..91423e9 100644
--- a/ogr/ogrsf_frmts/vfk/ogrvfkdriver.cpp
+++ b/ogr/ogrsf_frmts/vfk/ogrvfkdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrvfkdriver.cpp 25340 2012-12-21 20:30:21Z rouault $
+ * $Id: ogrvfkdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRVFKDriver class.
@@ -33,7 +33,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: ogrvfkdriver.cpp 25340 2012-12-21 20:30:21Z rouault $");
+CPL_CVSID("$Id: ogrvfkdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          ~OGRVFKDriver()                             */
@@ -84,7 +84,7 @@ OGRDataSource *OGRVFKDriver::Open(const char * pszFilename,
 
   \return TRUE on success or FALSE on failure
 */
-int OGRVFKDriver::TestCapability(const char *pszCap)
+int OGRVFKDriver::TestCapability(CPL_UNUSED const char *pszCap)
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/vfk/vfkreader.cpp b/ogr/ogrsf_frmts/vfk/vfkreader.cpp
index e2a0bee..e321edb 100644
--- a/ogr/ogrsf_frmts/vfk/vfkreader.cpp
+++ b/ogr/ogrsf_frmts/vfk/vfkreader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vfkreader.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vfkreader.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  VFK Reader
  * Purpose:  Implements VFKReader class.
@@ -154,19 +154,24 @@ char *VFKReader::ReadLine(bool bRecode)
 int VFKReader::ReadDataBlocks()
 {
     char       *pszLine, *pszBlockName;
-
+    bool        bInHeader;
+    
     IVFKDataBlock *poNewDataBlock;
     
     CPLAssert(NULL != m_pszFilename);
 
     VSIFSeek(m_poFD, 0, SEEK_SET);
+    bInHeader = TRUE;
     while ((pszLine = ReadLine()) != NULL) {
-        if (strlen(pszLine) < 2 || pszLine[0] != '&')
-        {
+        if (strlen(pszLine) < 2 || pszLine[0] != '&') {
             CPLFree(pszLine);
             continue;
         }
+
         if (pszLine[1] == 'B') {
+            if (bInHeader)
+                bInHeader = FALSE; /* 'B' record closes the header section */
+
             pszBlockName = GetDataBlockName(pszLine);
             if (pszBlockName == NULL) { 
                 CPLError(CE_Failure, CPLE_NotSupported, 
@@ -189,6 +194,11 @@ int VFKReader::ReadDataBlocks()
             CPLFree(pszLine);
             break;
         }
+        else if (bInHeader && pszLine[1] == 'D') {
+            /* process 'D' records in the header section */
+            AddInfo(pszLine);
+        }
+        
         CPLFree(pszLine);
     }
     
@@ -212,6 +222,7 @@ int VFKReader::ReadDataRecords(IVFKDataBlock *poDataBlock)
     CPLString   osBlockNameLast;
     int         nLength, iLine, nSkipped, nDupl, nRecords;
     int         iDataBlock;
+    bool        bInHeader;
     
     IVFKDataBlock *poDataBlockCurrent;
     
@@ -235,14 +246,28 @@ int VFKReader::ReadDataRecords(IVFKDataBlock *poDataBlock)
     
     VSIFSeek(m_poFD, 0, SEEK_SET);
     iLine = nSkipped = nDupl = nRecords = 0;
+    bInHeader = TRUE;
     while ((pszLine = ReadLine()) != NULL) {
         iLine++;
         nLength = strlen(pszLine);
-        if (nLength < 2)
+        if (nLength < 2) {
+            CPLFree(pszLine);
             continue;
+        }
+        
+        if (bInHeader && pszLine[1] == 'B')
+            bInHeader = FALSE; /* 'B' record closes the header section */
         
         if (pszLine[1] == 'D') {
+            if (bInHeader) {
+                /* skip 'D' records from the header section, already
+                 * processed as metadata */
+                CPLFree(pszLine);
+                continue;
+            }
+
             pszBlockName = GetDataBlockName(pszLine);
+            
             if (pszBlockName && (!pszName || EQUAL(pszBlockName, pszName))) {
                 /* merge lines if needed */
                 if (pszLine[nLength - 2] == '\302' &&
@@ -315,6 +340,7 @@ int VFKReader::ReadDataRecords(IVFKDataBlock *poDataBlock)
             CPLFree(pszLine);
             break;
         }
+
         CPLFree(pszLine);
     }
 
@@ -354,7 +380,7 @@ IVFKDataBlock *VFKReader::CreateDataBlock(const char *pszBlockName)
   \param poNewDataBlock pointer to VFKDataBlock instance
   \param pszDefn unused (FIXME ?)
 */
-void VFKReader::AddDataBlock(IVFKDataBlock *poNewDataBlock, const char *pszDefn)
+void VFKReader::AddDataBlock(IVFKDataBlock *poNewDataBlock, CPL_UNUSED const char *pszDefn)
 {
     m_nDataBlockCount++;
     
@@ -434,12 +460,17 @@ int VFKReader::LoadGeometry()
 void VFKReader::AddInfo(const char *pszLine)
 {
     int         i, iKeyLength, iValueLength;
-    int         nSkip;
-    char       *pszKey, *pszValue;
+    int         nSkip, nOffset;
+    char       *pszKey, *pszValue, *pszValueEnc;
     const char *poChar, *poKey;
     CPLString   key, value;
     
-    poChar = poKey = pszLine + 2; /* &H */
+    if (pszLine[1] == 'H')
+        nOffset = 2;
+    else
+        nOffset = 1; /* &DKATUZE */
+    
+    poChar = poKey = pszLine + nOffset; /* &H */
     iKeyLength = 0;
     while (*poChar != '\0' && *poChar != ';') {
         iKeyLength++;
@@ -478,15 +509,43 @@ void VFKReader::AddInfo(const char *pszLine)
 
     pszValue[iValueLength] = '\0';
 
-    poInfo[pszKey] = pszValue;
 
+    /* recode values, assuming Latin2 */
     if (EQUAL(pszKey, "CODEPAGE")) {
         if (!EQUAL(pszValue, "WE8ISO8859P2"))
             m_bLatin2 = FALSE;
     }
 
+    pszValueEnc = CPLRecode(pszValue,
+                            m_bLatin2 ? "ISO-8859-2" : "WINDOWS-1250",
+                            CPL_ENC_UTF8);
+    if (poInfo.find(pszKey) == poInfo.end() ) {
+        poInfo[pszKey] = pszValueEnc;
+    }
+    else {
+        int nCount;
+        size_t iFound;
+        char *pszKeyUniq;
+        
+        /* max. number of duplicated keys can be 101 */
+        pszKeyUniq = (char *) CPLMalloc(strlen(pszKey) + 5); 
+
+        nCount = 1; /* assuming at least one match */
+        for(std::map<CPLString, CPLString>::iterator i = poInfo.begin();
+            i != poInfo.end(); ++i) {
+            iFound = i->first.find("_");
+            if (iFound != std::string::npos &&
+                EQUALN(pszKey, i->first.c_str(), iFound))
+                nCount += 1;
+        }
+        
+        sprintf(pszKeyUniq, "%s_%d", pszKey, nCount);
+        poInfo[pszKeyUniq] = pszValueEnc;
+    }
+
     CPLFree(pszKey);
     CPLFree(pszValue);
+    CPLFree(pszValueEnc);
 }
 
 /*!
diff --git a/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp b/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp
index fd60349..e6c2a46 100644
--- a/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp
+++ b/ogr/ogrsf_frmts/vfk/vfkreadersqlite.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: vfkreadersqlite.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: vfkreadersqlite.cpp 27206 2014-04-16 21:23:33Z martinl $
  *
  * Project:  VFK Reader (SQLite)
  * Purpose:  Implements VFKReaderSQLite class.
@@ -62,7 +62,7 @@ VFKReaderSQLite::VFKReaderSQLite(const char *pszFilename) : VFKReader(pszFilenam
 	pszDbName = pszDbNameConf;
     }
     else {
-	pszDbName.Printf("%s.db", m_pszFilename);
+	pszDbName = CPLResetExtension(m_pszFilename, "db");
     }
     m_pszDBname = new char [pszDbName.length()+1];
     std::strcpy(m_pszDBname, pszDbName.c_str());
diff --git a/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp b/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp
index 39555b1..45b652e 100644
--- a/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp
+++ b/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrvrtdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrvrtdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRVRTDataSource class.
@@ -34,7 +34,7 @@
 #include "ogrwarpedlayer.h"
 #include "ogrunionlayer.h"
 
-CPL_CVSID("$Id: ogrvrtdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrvrtdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                       OGRVRTGetGeometryType()                        */
@@ -870,8 +870,7 @@ int OGRVRTDataSource::Initialize( CPLXMLNode *psTree, const char *pszNewName,
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRVRTDataSource::TestCapability( const char * pszCap )
-
+int OGRVRTDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp b/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp
index 4159648..a71188d 100644
--- a/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp
+++ b/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrvrtdriver.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrvrtdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Implements OGRVRTDriver class.
@@ -31,14 +31,13 @@
 #include "ogr_vrt.h"
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: ogrvrtdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrvrtdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            ~OGRVRTDriver()                            */
 /************************************************************************/
 
 OGRVRTDriver::~OGRVRTDriver()
-
 {
 }
 
@@ -47,7 +46,6 @@ OGRVRTDriver::~OGRVRTDriver()
 /************************************************************************/
 
 const char *OGRVRTDriver::GetName()
-
 {
     return "VRT";
 }
@@ -56,7 +54,9 @@ const char *OGRVRTDriver::GetName()
 /*                           OGRVRTErrorHandler()                       */
 /************************************************************************/
 
-static void CPL_STDCALL OGRVRTErrorHandler(CPLErr eErr, int nType, const char* pszMsg)
+static void CPL_STDCALL OGRVRTErrorHandler(CPL_UNUSED CPLErr eErr,
+                                           CPL_UNUSED int nType,
+                                           const char* pszMsg)
 {
     std::vector<CPLString>* paosErrors = (std::vector<CPLString>* )CPLGetErrorHandlerUserData();
     paosErrors->push_back(pszMsg);
@@ -67,8 +67,7 @@ static void CPL_STDCALL OGRVRTErrorHandler(CPLErr eErr, int nType, const char* p
 /************************************************************************/
 
 OGRDataSource *OGRVRTDriver::Open( const char * pszFilename,
-                                     int bUpdate )
-
+                                   int bUpdate )
 {
     OGRVRTDataSource     *poDS;
     char *pszXML = NULL;
@@ -199,8 +198,7 @@ OGRDataSource *OGRVRTDriver::Open( const char * pszFilename,
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRVRTDriver::TestCapability( const char * pszCap )
-
+int OGRVRTDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
@@ -210,7 +208,6 @@ int OGRVRTDriver::TestCapability( const char * pszCap )
 /************************************************************************/
 
 void RegisterOGRVRT()
-
 {
     OGRSFDriverRegistrar::GetRegistrar()->RegisterDriver( new OGRVRTDriver );
 }
diff --git a/ogr/ogrsf_frmts/wasp/ogrwasplayer.cpp b/ogr/ogrsf_frmts/wasp/ogrwasplayer.cpp
index f06bf36..73b28b9 100644
--- a/ogr/ogrsf_frmts/wasp/ogrwasplayer.cpp
+++ b/ogr/ogrsf_frmts/wasp/ogrwasplayer.cpp
@@ -582,8 +582,7 @@ OGRErr OGRWAsPLayer::CreateFeature( OGRFeature * poFeature )
 /*                            CreateField()                            */
 /************************************************************************/
 
-OGRErr OGRWAsPLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
-
+OGRErr OGRWAsPLayer::CreateField( OGRFieldDefn *poField, CPL_UNUSED int bApproxOK )
 {
     poLayerDefn->AddFieldDefn( poField );
     
@@ -601,7 +600,7 @@ OGRErr OGRWAsPLayer::CreateField( OGRFieldDefn *poField, int bApproxOK )
 /************************************************************************/
 
 OGRErr OGRWAsPLayer::CreateGeomField( OGRGeomFieldDefn *poGeomFieldIn,
-                                      int bApproxOK )
+                                      CPL_UNUSED int bApproxOK )
 {
     poLayerDefn->AddGeomFieldDefn( poGeomFieldIn, FALSE );
 
diff --git a/ogr/ogrsf_frmts/wfs/ogrwfsdatasource.cpp b/ogr/ogrsf_frmts/wfs/ogrwfsdatasource.cpp
index d687e52..8dfa1f7 100644
--- a/ogr/ogrsf_frmts/wfs/ogrwfsdatasource.cpp
+++ b/ogr/ogrsf_frmts/wfs/ogrwfsdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrwfsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrwfsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WFS Translator
  * Purpose:  Implements OGRWFSDataSource class
@@ -37,7 +37,7 @@
 #include "swq.h"
 #include "ogr_p.h"
 
-CPL_CVSID("$Id: ogrwfsdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrwfsdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 #define DEFAULT_BASE_START_INDEX     0
 #define DEFAULT_PAGE_SIZE            100
@@ -213,8 +213,7 @@ OGRWFSDataSource::~OGRWFSDataSource()
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRWFSDataSource::TestCapability( const char * pszCap )
-
+int OGRWFSDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/wfs/ogrwfsdriver.cpp b/ogr/ogrsf_frmts/wfs/ogrwfsdriver.cpp
index c66c78d..bd85925 100644
--- a/ogr/ogrsf_frmts/wfs/ogrwfsdriver.cpp
+++ b/ogr/ogrsf_frmts/wfs/ogrwfsdriver.cpp
@@ -32,7 +32,7 @@
 
 // g++ -fPIC -g -Wall ogr/ogrsf_frmts/wfs/*.cpp -shared -o ogr_WFS.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts -Iogr/ogrsf_frmts/gml -Iogr/ogrsf_frmts/wfs -L. -lgdal
 
-CPL_CVSID("$Id: ogrwfsdriver.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrwfsdriver.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 extern "C" void RegisterOGRWFS();
 
@@ -77,8 +77,7 @@ OGRDataSource *OGRWFSDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRWFSDriver::TestCapability( const char * pszCap )
-
+int OGRWFSDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp b/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp
index 081d0b0..3426677 100644
--- a/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp
+++ b/ogr/ogrsf_frmts/wfs/ogrwfslayer.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrwfslayer.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrwfslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  WFS Translator
  * Purpose:  Implements OGRWFSLayer class.
@@ -34,7 +34,7 @@
 #include "cpl_http.h"
 #include "parsexsd.h"
 
-CPL_CVSID("$Id: ogrwfslayer.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrwfslayer.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 
 /************************************************************************/
@@ -189,7 +189,7 @@ OGRWFSLayer::~OGRWFSLayer()
 /*                    GetDescribeFeatureTypeURL()                       */
 /************************************************************************/
 
-CPLString OGRWFSLayer::GetDescribeFeatureTypeURL(int bWithNS)
+CPLString OGRWFSLayer::GetDescribeFeatureTypeURL(CPL_UNUSED int bWithNS)
 {
     CPLString osURL(pszBaseURL);
     osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS");
diff --git a/ogr/ogrsf_frmts/xlsx/ogrxlsxdatasource.cpp b/ogr/ogrsf_frmts/xlsx/ogrxlsxdatasource.cpp
index 091ff46..4ba8a47 100644
--- a/ogr/ogrsf_frmts/xlsx/ogrxlsxdatasource.cpp
+++ b/ogr/ogrsf_frmts/xlsx/ogrxlsxdatasource.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrxlsxdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: ogrxlsxdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  XLSX Translator
  * Purpose:  Implements OGRXLSXDataSource class
@@ -32,7 +32,7 @@
 #include "cpl_conv.h"
 #include "cpl_time.h"
 
-CPL_CVSID("$Id: ogrxlsxdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrxlsxdatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                            OGRXLSXLayer()                            */
@@ -273,7 +273,7 @@ int OGRXLSXDataSource::Open( const char * pszFilename,
 /*                             Create()                                 */
 /************************************************************************/
 
-int OGRXLSXDataSource::Create( const char * pszFilename, char **papszOptions )
+int OGRXLSXDataSource::Create( const char * pszFilename, CPL_UNUSED char **papszOptions )
 {
     bUpdated = TRUE;
     bUpdatable = TRUE;
@@ -560,7 +560,7 @@ void OGRXLSXDataSource::DetectHeaderLine()
 /************************************************************************/
 
 void OGRXLSXDataSource::startElementDefault(const char *pszName,
-                                           const char **ppszAttr)
+                                            CPL_UNUSED const char **ppszAttr)
 {
     if (strcmp(pszName, "sheetData") == 0)
     {
@@ -601,7 +601,7 @@ void OGRXLSXDataSource::startElementTable(const char *pszName,
 /*                           endElementTable()                          */
 /************************************************************************/
 
-void OGRXLSXDataSource::endElementTable(const char *pszName)
+void OGRXLSXDataSource::endElementTable(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -706,7 +706,7 @@ void OGRXLSXDataSource::startElementRow(const char *pszName,
 /*                            endElementRow()                           */
 /************************************************************************/
 
-void OGRXLSXDataSource::endElementRow(const char *pszName)
+void OGRXLSXDataSource::endElementRow(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -859,7 +859,7 @@ void OGRXLSXDataSource::endElementRow(const char *pszName)
 /************************************************************************/
 
 void OGRXLSXDataSource::startElementCell(const char *pszName,
-                                        const char **ppszAttr)
+                                         CPL_UNUSED const char **ppszAttr)
 {
     if (osValue.size() == 0 && strcmp(pszName, "v") == 0)
     {
@@ -875,7 +875,7 @@ void OGRXLSXDataSource::startElementCell(const char *pszName,
 /*                            endElementCell()                          */
 /************************************************************************/
 
-void OGRXLSXDataSource::endElementCell(const char *pszName)
+void OGRXLSXDataSource::endElementCell(CPL_UNUSED const char *pszName)
 {
     if (stateStack[nStackDepth].nBeginDepth == nDepth)
     {
@@ -986,7 +986,7 @@ static void XMLCALL startElementSSCbk(void *pUserData, const char *pszName,
 }
 
 void OGRXLSXDataSource::startElementSSCbk(const char *pszName,
-                                       const char **ppszAttr)
+                                          CPL_UNUSED const char **ppszAttr)
 {
     if (bStopParsing) return;
 
@@ -1017,7 +1017,7 @@ static void XMLCALL endElementSSCbk(void *pUserData, const char *pszName)
     ((OGRXLSXDataSource*)pUserData)->endElementSSCbk(pszName);
 }
 
-void OGRXLSXDataSource::endElementSSCbk(const char *pszName)
+void OGRXLSXDataSource::endElementSSCbk(CPL_UNUSED const char *pszName)
 {
     if (bStopParsing) return;
 
@@ -1368,8 +1368,8 @@ void OGRXLSXDataSource::AnalyseStyles(VSILFILE* fpStyles)
 
 OGRLayer *
 OGRXLSXDataSource::CreateLayer( const char * pszLayerName,
-                                OGRSpatialReference *poSRS,
-                                OGRwkbGeometryType eType,
+                                CPL_UNUSED OGRSpatialReference *poSRS,
+                                CPL_UNUSED OGRwkbGeometryType eType,
                                 char ** papszOptions )
 
 {
@@ -1797,8 +1797,8 @@ static void WriteLayer(const char* pszName, OGRLayer* poLayer, int iLayer,
 /************************************************************************/
 
 static void WriteSharedStrings(const char* pszName,
-                       std::map<std::string,int>& oStringMap,
-                       std::vector<std::string>& oStringList)
+                               CPL_UNUSED std::map<std::string,int>& oStringMap,
+                               std::vector<std::string>& oStringList)
 {
     VSILFILE* fp;
 
diff --git a/ogr/ogrsf_frmts/xplane/ogrxplanedatasource.cpp b/ogr/ogrsf_frmts/xplane/ogrxplanedatasource.cpp
index dce05b4..f430933 100644
--- a/ogr/ogrsf_frmts/xplane/ogrxplanedatasource.cpp
+++ b/ogr/ogrsf_frmts/xplane/ogrxplanedatasource.cpp
@@ -30,7 +30,7 @@
 #include "ogr_xplane.h"
 #include "ogr_xplane_reader.h"
 
-CPL_CVSID("$Id: ogrxplanedatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: ogrxplanedatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                          OGRXPlaneDataSource()                          */
@@ -164,8 +164,7 @@ int OGRXPlaneDataSource::Open( const char * pszFilename, int bReadWholeFile )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRXPlaneDataSource::TestCapability( const char * pszCap )
-
+int OGRXPlaneDataSource::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrsf_frmts/xplane/ogrxplanedriver.cpp b/ogr/ogrsf_frmts/xplane/ogrxplanedriver.cpp
index 6acbdf5..bf2d52a 100644
--- a/ogr/ogrsf_frmts/xplane/ogrxplanedriver.cpp
+++ b/ogr/ogrsf_frmts/xplane/ogrxplanedriver.cpp
@@ -69,7 +69,7 @@ OGRDataSource *OGRXPlaneDriver::Open( const char * pszFilename, int bUpdate )
 /*                           TestCapability()                           */
 /************************************************************************/
 
-int OGRXPlaneDriver::TestCapability( const char * pszCap )
+int OGRXPlaneDriver::TestCapability( CPL_UNUSED const char * pszCap )
 {
     return FALSE;
 }
diff --git a/ogr/ogrutils.cpp b/ogr/ogrutils.cpp
index 98f3a0c..2a6d043 100644
--- a/ogr/ogrutils.cpp
+++ b/ogr/ogrutils.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: ogrutils.cpp 27121 2014-04-03 22:08:55Z rouault $
+ * $Id: ogrutils.cpp 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  Utility functions for OGR classes, including some related to
@@ -41,7 +41,7 @@
 # include "ogrsf_frmts.h"
 #endif /* OGR_ENABLED */
 
-CPL_CVSID("$Id: ogrutils.cpp 27121 2014-04-03 22:08:55Z rouault $");
+CPL_CVSID("$Id: ogrutils.cpp 27729 2014-09-24 00:40:16Z goatbar $");
 
 /************************************************************************/
 /*                        OGRFormatDouble()                             */
@@ -811,8 +811,7 @@ int OGRGeneralCmdLineProcessor( int nArgc, char ***ppapszArgv, int nOptions )
  * @return TRUE if apparently successful or FALSE on failure.
  */
 
-int OGRParseDate( const char *pszInput, OGRField *psField, int nOptions )
-
+int OGRParseDate( const char *pszInput, OGRField *psField, CPL_UNUSED int nOptions )
 {
     int bGotSomething = FALSE;
 
diff --git a/ogr/osr_cs_wkt.c b/ogr/osr_cs_wkt.c
index bbca2c2..ac83385 100644
--- a/ogr/osr_cs_wkt.c
+++ b/ogr/osr_cs_wkt.c
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: osr_cs_wkt.c 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: osr_cs_wkt.c 27729 2014-09-24 00:40:16Z goatbar $
  *
  * Project:  OpenGIS Simple Features Reference Implementation
  * Purpose:  CS WKT parser
@@ -36,6 +36,8 @@
 
 #include "osr_cs_wkt.h"
 
+#include "cpl_port.h"
+
 /************************************************************************/
 /*                        osr_cs_wkt_error()                            */
 /************************************************************************/
@@ -99,7 +101,7 @@ static const osr_cs_wkt_tokens tokens[] =
 /*                         osr_cs_wkt_lex()                             */
 /************************************************************************/
 
-int osr_cs_wkt_lex(YYSTYPE* pNode, osr_cs_wkt_parse_context *context)
+int osr_cs_wkt_lex(CPL_UNUSED YYSTYPE* pNode, osr_cs_wkt_parse_context *context)
 {
     size_t i;
     const char *pszInput = context->pszNext;
diff --git a/ogr/swq_select.cpp b/ogr/swq_select.cpp
index 922a369..59068e9 100644
--- a/ogr/swq_select.cpp
+++ b/ogr/swq_select.cpp
@@ -827,8 +827,7 @@ CPLErr swq_select::expand_wildcard( swq_field_list *field_list )
 /************************************************************************/
 
 CPLErr swq_select::parse( swq_field_list *field_list,
-                          int parse_flags )
-
+                          CPL_UNUSED int parse_flags )
 {
     int  i;
     CPLErr eError;
diff --git a/port/cpl_conv.cpp b/port/cpl_conv.cpp
index 446e8d5..876434e 100644
--- a/port/cpl_conv.cpp
+++ b/port/cpl_conv.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_conv.cpp 27121 2014-04-03 22:08:55Z rouault $
+ * $Id: cpl_conv.cpp 27550 2014-07-25 20:43:52Z rouault $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Convenience functions.
@@ -35,7 +35,7 @@
 #include "cpl_vsi.h"
 #include "cpl_multiproc.h"
 
-CPL_CVSID("$Id: cpl_conv.cpp 27121 2014-04-03 22:08:55Z rouault $");
+CPL_CVSID("$Id: cpl_conv.cpp 27550 2014-07-25 20:43:52Z rouault $");
 
 #if defined(WIN32CE)
 #  include "cpl_wince.h"
@@ -1619,6 +1619,16 @@ CPLSetConfigOption( const char *pszKey, const char *pszValue )
 }
 
 /************************************************************************/
+/*                   CPLSetThreadLocalTLSFreeFunc()                     */
+/************************************************************************/
+
+/* non-stdcall wrapper function for CSLDestroy() (#5590) */
+static void CPLSetThreadLocalTLSFreeFunc( void* pData )
+{
+    CSLDestroy( (char**) pData );
+}
+
+/************************************************************************/
 /*                   CPLSetThreadLocalConfigOption()                    */
 /************************************************************************/
 
@@ -1653,7 +1663,8 @@ CPLSetThreadLocalConfigOption( const char *pszKey, const char *pszValue )
     papszTLConfigOptions = 
         CSLSetNameValue( papszTLConfigOptions, pszKey, pszValue );
 
-    CPLSetTLSWithFreeFunc( CTLS_CONFIGOPTIONS, papszTLConfigOptions, (CPLTLSFreeFunc)CSLDestroy );
+    CPLSetTLSWithFreeFunc( CTLS_CONFIGOPTIONS, papszTLConfigOptions,
+                           CPLSetThreadLocalTLSFreeFunc );
 }
 
 /************************************************************************/
diff --git a/port/cpl_getexecpath.cpp b/port/cpl_getexecpath.cpp
index e182b58..5ffa9a5 100644
--- a/port/cpl_getexecpath.cpp
+++ b/port/cpl_getexecpath.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_getexecpath.cpp 21915 2011-03-08 21:58:16Z warmerdam $
+ * $Id: cpl_getexecpath.cpp 27720 2014-09-21 17:58:47Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement CPLGetExecPath().
@@ -30,7 +30,7 @@
 #include "cpl_conv.h"
 #include "cpl_string.h"
 
-CPL_CVSID("$Id: cpl_getexecpath.cpp 21915 2011-03-08 21:58:16Z warmerdam $");
+CPL_CVSID("$Id: cpl_getexecpath.cpp 27720 2014-09-21 17:58:47Z goatbar $");
 
 #if defined(WIN32) || defined(WIN32CE)
 
@@ -135,8 +135,7 @@ int CPLGetExecPath( char *pszPathBuf, int nMaxLength )
 
 #ifndef HAVE_IMPLEMENTATION
 
-int CPLGetExecPath( char *pszPathBuf, int nMaxLength )
-
+int CPLGetExecPath( CPL_UNUSED char *pszPathBuf, CPL_UNUSED int nMaxLength )
 {
     return FALSE;
 }
diff --git a/port/cpl_google_oauth2.cpp b/port/cpl_google_oauth2.cpp
index 372ee83..1be6acf 100644
--- a/port/cpl_google_oauth2.cpp
+++ b/port/cpl_google_oauth2.cpp
@@ -271,7 +271,7 @@ char CPL_DLL *GOA2GetRefreshToken( const char *pszAuthToken,
  */
 
 char *GOA2GetAccessToken( const char *pszRefreshToken, 
-                          const char *pszScope )
+                          CPL_UNUSED const char *pszScope )
 {
 /* -------------------------------------------------------------------- */
 /*      Prepare request.                                                */
diff --git a/port/cpl_http.cpp b/port/cpl_http.cpp
index 36105bf..498400e 100644
--- a/port/cpl_http.cpp
+++ b/port/cpl_http.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_http.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_http.cpp 27517 2014-07-11 18:12:54Z kyle $
  *
  * Project:  libcurl based HTTP client
  * Purpose:  libcurl based HTTP client
@@ -44,7 +44,7 @@ void CPLHTTPSetOptions(CURL *http_handle, char** papszOptions);
 
 #endif
 
-CPL_CVSID("$Id: cpl_http.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_http.cpp 27517 2014-07-11 18:12:54Z kyle $");
 
 // list of named persistent http sessions 
 
@@ -494,9 +494,9 @@ void CPLHTTPSetOptions(CURL *http_handle, char** papszOptions)
 
     /* NOSIGNAL should be set to true for timeout to work in multithread
      * environments on Unix, requires libcurl 7.10 or more recent.
-     * (this force avoiding the use of sgnal handlers)
+     * (this force avoiding the use of signal handlers)
      */
-#ifdef CURLOPT_NOSIGNAL
+#if LIBCURL_VERSION_NUM >= 0x070A00
     curl_easy_setopt(http_handle, CURLOPT_NOSIGNAL, 1 );
 #endif
 
diff --git a/port/cpl_minizip_ioapi.cpp b/port/cpl_minizip_ioapi.cpp
index 56f878a..32a5e56 100644
--- a/port/cpl_minizip_ioapi.cpp
+++ b/port/cpl_minizip_ioapi.cpp
@@ -71,7 +71,7 @@ int ZCALLBACK ferror_file_func OF((
    voidpf stream));
 
 static
-voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
+voidpf ZCALLBACK fopen_file_func (CPL_UNUSED voidpf opaque, const char* filename, int mode)
 {
     VSILFILE* file = NULL;
     const char* mode_fopen = NULL;
@@ -90,7 +90,7 @@ voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
 }
 
 static
-uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
+uLong ZCALLBACK fread_file_func (CPL_UNUSED voidpf opaque, voidpf stream, void* buf, uLong size)
 {
     uLong ret;
     ret = (uLong)VSIFReadL(buf, 1, (size_t)size, (VSILFILE *)stream);
@@ -98,7 +98,7 @@ uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong
 }
 
 static
-uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
+uLong ZCALLBACK fwrite_file_func (CPL_UNUSED voidpf opaque, voidpf stream, const void* buf, uLong size)
 {
     uLong ret;
     ret = (uLong)VSIFWriteL(buf, 1, (size_t)size, (VSILFILE *)stream);
@@ -106,7 +106,7 @@ uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf,
 }
 
 static
-uLong64 ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
+uLong64 ZCALLBACK ftell_file_func (CPL_UNUSED voidpf opaque, voidpf stream)
 {
     uLong64 ret;
     ret = VSIFTellL((VSILFILE *)stream);
@@ -114,7 +114,7 @@ uLong64 ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
 }
 
 static
-long ZCALLBACK fseek_file_func (voidpf  opaque, voidpf stream, uLong64 offset, int origin)
+long ZCALLBACK fseek_file_func (CPL_UNUSED voidpf  opaque, voidpf stream, uLong64 offset, int origin)
 {
     int fseek_origin=0;
     long ret;
@@ -137,7 +137,7 @@ long ZCALLBACK fseek_file_func (voidpf  opaque, voidpf stream, uLong64 offset, i
 }
 
 static
-int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
+int ZCALLBACK fclose_file_func (CPL_UNUSED voidpf opaque, voidpf stream)
 {
     int ret;
     ret = VSIFCloseL((VSILFILE *)stream);
@@ -145,7 +145,7 @@ int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
 }
 
 static
-int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
+int ZCALLBACK ferror_file_func (CPL_UNUSED voidpf opaque, CPL_UNUSED voidpf stream)
 {
     int ret;
     ret = 0; // FIXME
diff --git a/port/cpl_minizip_unzip.cpp b/port/cpl_minizip_unzip.cpp
index e30b78c..371bbf3 100644
--- a/port/cpl_minizip_unzip.cpp
+++ b/port/cpl_minizip_unzip.cpp
@@ -6,6 +6,7 @@
      - Add support for ZIP64
      - Recode filename to UTF-8 if GP 11 is unset
      - Use Info-ZIP Unicode Path Extra Field (0x7075) to get UTF-8 filenames
+     - ZIP64: accept number_disk == 0 in unzlocal_SearchCentralDir64()
 
  * Copyright (c) 2008-2014, Even Rouault <even dot rouault at mines-paris dot org>
 
@@ -536,7 +537,8 @@ local uLong64 unzlocal_SearchCentralDir64(const zlib_filefunc_def* pzlib_filefun
     /* total number of disks */
     if (unzlocal_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK)
         return 0;
-    if (uL != 1)
+    /* Some .zip declare 0 disks, such as in http://trac.osgeo.org/gdal/ticket/5615 */
+    if (uL != 1 && uL != 0)
         return 0;
 
     /* Goto end of central directory record */
@@ -808,15 +810,15 @@ local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file,
                                                   uLong commentBufferSize));
 
 local int unzlocal_GetCurrentFileInfoInternal (unzFile file,
-                                                  unz_file_info *pfile_info,
-                                                  unz_file_info_internal
-                                                  *pfile_info_internal,
-                                                  char *szFileName,
-                                                  uLong fileNameBufferSize,
-                                                  void *extraField,
-                                                  uLong extraFieldBufferSize,
-                                                  char *szComment,
-                                                  uLong commentBufferSize)
+                                               unz_file_info *pfile_info,
+                                               unz_file_info_internal
+                                               *pfile_info_internal,
+                                               char *szFileName,
+                                               uLong fileNameBufferSize,
+                                               CPL_UNUSED void *extraField,
+                                               CPL_UNUSED uLong extraFieldBufferSize,
+                                               CPL_UNUSED char *szComment,
+                                               CPL_UNUSED uLong commentBufferSize)
 {
     unz_s* s;
     unz_file_info file_info;
diff --git a/port/cpl_minizip_zip.cpp b/port/cpl_minizip_zip.cpp
index 5575ab8..fe0aadd 100644
--- a/port/cpl_minizip_zip.cpp
+++ b/port/cpl_minizip_zip.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_minizip_zip.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_minizip_zip.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Author:   Frank Warmerdam, warmerdam at pobox.com
@@ -33,8 +33,9 @@
 #include <string.h>
 #include <time.h>
 #include "zlib.h"
-#include "cpl_minizip_zip.h"
 #include "cpl_conv.h"
+#include "cpl_minizip_zip.h"
+#include "cpl_port.h"
 #include "cpl_string.h"
 
 #ifdef STDC
@@ -98,7 +99,8 @@
 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
 #endif
 #endif
-const char zip_copyright[] =
+
+CPL_UNUSED const char zip_copyright[] =
    " zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
 
 
@@ -317,7 +319,7 @@ local void ziplocal_putValue_inmemory (void *dest, uLong x, int nbByte)
 /****************************************************************************/
 
 
-local uLong ziplocal_TmzDateToDosDate(const tm_zip*ptm,uLong dosDate)
+local uLong ziplocal_TmzDateToDosDate(const tm_zip*ptm, CPL_UNUSED uLong dosDate)
 {
     uLong year = (uLong)ptm->tm_year;
     if (year>1980)
@@ -697,7 +699,7 @@ extern int ZEXPORT cpl_zipOpenNewFileInZip3 (
     int memLevel,
     int strategy,
     const char* password,
-    uLong crcForCrypting )
+    CPL_UNUSED uLong crcForCrypting )
 {
     zip_internal* zi;
     uInt size_filename;
diff --git a/port/cpl_multiproc.cpp b/port/cpl_multiproc.cpp
index 421a201..5b90159 100644
--- a/port/cpl_multiproc.cpp
+++ b/port/cpl_multiproc.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_multiproc.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_multiproc.cpp 27720 2014-09-21 17:58:47Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  CPL Multi-Threading, and process handling portability functions.
@@ -41,7 +41,7 @@
 #  include <wce_time.h>
 #endif
 
-CPL_CVSID("$Id: cpl_multiproc.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_multiproc.cpp 27720 2014-09-21 17:58:47Z goatbar $");
 
 #if defined(CPL_MULTIPROC_STUB) && !defined(DEBUG)
 #  define MUTEX_NONE
@@ -1206,8 +1206,7 @@ void *CPLCreateMutex()
 /*                          CPLAcquireMutex()                           */
 /************************************************************************/
 
-int CPLAcquireMutex( void *hMutexIn, double dfWaitInSeconds )
-
+int CPLAcquireMutex( void *hMutexIn, CPL_UNUSED double dfWaitInSeconds )
 {
     int err;
 
diff --git a/port/cpl_port.h b/port/cpl_port.h
index 00edcac..7f0fe75 100644
--- a/port/cpl_port.h
+++ b/port/cpl_port.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_port.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_port.h 27701 2014-09-20 15:07:02Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Author:   Frank Warmerdam, warmerdam at pobox.com
@@ -574,6 +574,13 @@ static char *cvsid_aw() { return( cvsid_aw() ? ((char *) NULL) : cpl_cvsid ); }
 #define CPL_WARN_UNUSED_RESULT
 #endif
 
+#if defined(__GNUC__) && __GNUC__ >= 4
+#  define CPL_UNUSED __attribute((__unused__))
+#else
+/* TODO: add cases for other compilers */
+#  define CPL_UNUSED
+#endif
+
 #if defined(__GNUC__) && __GNUC__ >= 3 && !defined(DOXYGEN_SKIP)
 #define CPL_NO_RETURN                                __attribute__((noreturn))
 #else
diff --git a/port/cpl_progress.cpp b/port/cpl_progress.cpp
index c9ec491..8b97fc5 100644
--- a/port/cpl_progress.cpp
+++ b/port/cpl_progress.cpp
@@ -45,9 +45,8 @@ CPL_CVSID("$Id: gdal_misc.cpp 25494 2013-01-13 12:55:17Z etourigny $");
  * to use one of the other progress functions that actually do something.
  */
 
-int CPL_STDCALL GDALDummyProgress( double dfComplete, const char *pszMessage,
-                                   void *pData )
-
+int CPL_STDCALL GDALDummyProgress( CPL_UNUSED double dfComplete, CPL_UNUSED const char *pszMessage,
+                                   CPL_UNUSED void *pData )
 {
     return TRUE;
 }
@@ -200,9 +199,8 @@ void CPL_STDCALL GDALDestroyScaledProgress( void * pData )
  * @return Always returns TRUE indicating the process should continue.
  */
 
-int CPL_STDCALL GDALTermProgress( double dfComplete, const char *pszMessage,
-                      void * pProgressArg )
-
+int CPL_STDCALL GDALTermProgress( double dfComplete, CPL_UNUSED const char *pszMessage,
+                                  void * pProgressArg )
 {
     static int nLastTick = -1;
     int nThisTick = (int) (dfComplete * 40.0);
diff --git a/port/cpl_spawn.cpp b/port/cpl_spawn.cpp
index 77d43b8..6f61aa6 100644
--- a/port/cpl_spawn.cpp
+++ b/port/cpl_spawn.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_spawn.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_spawn.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement CPLSystem().
@@ -39,7 +39,7 @@
 #define IN_FOR_PARENT   0
 #define OUT_FOR_PARENT  1
 
-CPL_CVSID("$Id: cpl_spawn.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_spawn.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 static void FillFileFromPipe(CPL_FILE_HANDLE pipe_fd, VSILFILE* fout);
 
@@ -328,7 +328,16 @@ CPLSpawnedProcess* CPLSpawnAsync(int (*pfnMain)(CPL_FILE_HANDLE, CPL_FILE_HANDLE
     {
         if (i > 0)
             osCommandLine += " ";
-        osCommandLine += papszArgv[i];
+        /* We need to quote arguments with spaces in them (if not already done) */
+        if( strchr(papszArgv[i], ' ') != NULL &&
+            papszArgv[i][0] != '"' )
+        {
+            osCommandLine += "\"";
+            osCommandLine += papszArgv[i];
+            osCommandLine += "\"";
+        }
+        else
+            osCommandLine += papszArgv[i];
     }
 
     if (!CreateProcess(NULL, 
@@ -644,7 +653,7 @@ CPLSpawnedProcess* CPLSpawnAsync(int (*pfnMain)(CPL_FILE_HANDLE, CPL_FILE_HANDLE
                                  int bCreateInputPipe,
                                  int bCreateOutputPipe,
                                  int bCreateErrorPipe,
-                                 char** papszOptions)
+                                 CPL_UNUSED char** papszOptions)
 {
     pid_t pid;
     int pipe_in[2] = { -1, -1 };
@@ -878,7 +887,7 @@ CPL_PID CPLSpawnAsyncGetChildProcessId(CPLSpawnedProcess* p)
  *
  * @since GDAL 1.10.0
  */
-int CPLSpawnAsyncFinish(CPLSpawnedProcess* p, int bWait, int bKill)
+int CPLSpawnAsyncFinish(CPLSpawnedProcess* p, int bWait, CPL_UNUSED int bKill)
 {
     int status = 0;
 
diff --git a/port/cpl_virtualmem.cpp b/port/cpl_virtualmem.cpp
index 022f01d..4aed6ed 100644
--- a/port/cpl_virtualmem.cpp
+++ b/port/cpl_virtualmem.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_virtualmem.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_virtualmem.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Name:     cpl_virtualmem.cpp
  * Project:  CPL - Common Portability Library
@@ -1962,15 +1962,15 @@ size_t CPLGetPageSize(void)
     return 0;
 }
 
-CPLVirtualMem *CPLVirtualMemNew(size_t nSize,
-                                size_t nCacheSize,
-                                size_t nPageSizeHint,
-                                int bSingleThreadUsage,
-                                CPLVirtualMemAccessMode eAccessMode,
-                                CPLVirtualMemCachePageCbk pfnCachePage,
-                                CPLVirtualMemUnCachePageCbk pfnUnCachePage,
-                                CPLVirtualMemFreeUserData pfnFreeUserData,
-                                void *pCbkUserData)
+CPLVirtualMem *CPLVirtualMemNew(CPL_UNUSED size_t nSize,
+                                CPL_UNUSED size_t nCacheSize,
+                                CPL_UNUSED size_t nPageSizeHint,
+                                CPL_UNUSED int bSingleThreadUsage,
+                                CPL_UNUSED CPLVirtualMemAccessMode eAccessMode,
+                                CPL_UNUSED CPLVirtualMemCachePageCbk pfnCachePage,
+                                CPL_UNUSED CPLVirtualMemUnCachePageCbk pfnUnCachePage,
+                                CPL_UNUSED CPLVirtualMemFreeUserData pfnFreeUserData,
+                                CPL_UNUSED void *pCbkUserData)
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "CPLVirtualMemNew() unsupported on this operating system / configuration");
@@ -1982,73 +1982,73 @@ int CPLIsVirtualMemFileMapAvailable(void)
     return FALSE;
 }
 
-CPLVirtualMem *CPLVirtualMemFileMapNew(VSILFILE* fp,
-                                    vsi_l_offset nOffset,
-                                    vsi_l_offset nLength,
-                                    CPLVirtualMemAccessMode eAccessMode,
-                                    CPLVirtualMemFreeUserData pfnFreeUserData,
-                                    void *pCbkUserData)
+CPLVirtualMem *CPLVirtualMemFileMapNew(CPL_UNUSED VSILFILE* fp,
+                                       CPL_UNUSED vsi_l_offset nOffset,
+                                       CPL_UNUSED vsi_l_offset nLength,
+                                       CPL_UNUSED CPLVirtualMemAccessMode eAccessMode,
+                                       CPL_UNUSED CPLVirtualMemFreeUserData pfnFreeUserData,
+                                       CPL_UNUSED void *pCbkUserData)
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "CPLVirtualMemFileMapNew() unsupported on this operating system / configuration");
     return NULL;
 }
 
-CPLVirtualMem *CPLVirtualMemDerivedNew(CPLVirtualMem* pVMemBase,
-                                       vsi_l_offset nOffset,
-                                       vsi_l_offset nSize,
-                                       CPLVirtualMemFreeUserData pfnFreeUserData,
-                                       void *pCbkUserData)
+CPLVirtualMem *CPLVirtualMemDerivedNew(CPL_UNUSED CPLVirtualMem* pVMemBase,
+                                       CPL_UNUSED vsi_l_offset nOffset,
+                                       CPL_UNUSED vsi_l_offset nSize,
+                                       CPL_UNUSED CPLVirtualMemFreeUserData pfnFreeUserData,
+                                       CPL_UNUSED void *pCbkUserData)
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "CPLVirtualMemDerivedNew() unsupported on this operating system / configuration");
     return NULL;
 }
 
-void CPLVirtualMemFree(CPLVirtualMem* ctxt)
+void CPLVirtualMemFree(CPL_UNUSED CPLVirtualMem* ctxt)
 {
 }
 
-void* CPLVirtualMemGetAddr(CPLVirtualMem* ctxt)
+void* CPLVirtualMemGetAddr(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return NULL;
 }
 
-size_t CPLVirtualMemGetSize(CPLVirtualMem* ctxt)
+size_t CPLVirtualMemGetSize(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return 0;
 }
 
-int CPLVirtualMemIsFileMapping(CPLVirtualMem* ctxt)
+int CPLVirtualMemIsFileMapping(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return FALSE;
 }
 
-CPLVirtualMemAccessMode CPLVirtualMemGetAccessMode(CPLVirtualMem* ctxt)
+CPLVirtualMemAccessMode CPLVirtualMemGetAccessMode(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return VIRTUALMEM_READONLY;
 }
 
-size_t CPLVirtualMemGetPageSize(CPLVirtualMem* ctxt)
+size_t CPLVirtualMemGetPageSize(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return 0;
 }
 
-int CPLVirtualMemIsAccessThreadSafe(CPLVirtualMem* ctxt)
+int CPLVirtualMemIsAccessThreadSafe(CPL_UNUSED CPLVirtualMem* ctxt)
 {
     return FALSE;
 }
 
-void CPLVirtualMemDeclareThread(CPLVirtualMem* ctxt)
+void CPLVirtualMemDeclareThread(CPL_UNUSED CPLVirtualMem* ctxt)
 {
 }
 
-void CPLVirtualMemUnDeclareThread(CPLVirtualMem* ctxt)
+void CPLVirtualMemUnDeclareThread(CPL_UNUSED CPLVirtualMem* ctxt)
 {
 }
 
-void CPLVirtualMemPin(CPLVirtualMem* ctxt,
-                      void* pAddr, size_t nSize, int bWriteOp)
+void CPLVirtualMemPin(CPL_UNUSED CPLVirtualMem* ctxt,
+                      CPL_UNUSED void* pAddr, CPL_UNUSED size_t nSize, CPL_UNUSED int bWriteOp)
 {
 }
 
diff --git a/port/cpl_vsi_virtual.h b/port/cpl_vsi_virtual.h
index 8bcdd32..9911906 100644
--- a/port/cpl_vsi_virtual.h
+++ b/port/cpl_vsi_virtual.h
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsi_virtual.h 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsi_virtual.h 27720 2014-09-21 17:58:47Z goatbar $
  *
  * Project:  VSI Virtual File System
  * Purpose:  Declarations for classes related to the virtual filesystem.
@@ -61,7 +61,7 @@ class CPL_DLL VSIVirtualHandle {
     virtual int       Eof() = 0;
     virtual int       Flush() {return 0;}
     virtual int       Close() = 0;
-    virtual int       Truncate( vsi_l_offset nNewSize ) { return -1; }
+    virtual int       Truncate( CPL_UNUSED vsi_l_offset nNewSize ) { return -1; }
     virtual void     *GetNativeFileDescriptor() { return NULL; }
     virtual           ~VSIVirtualHandle() { }
 };
diff --git a/port/cpl_vsil_abstract_archive.cpp b/port/cpl_vsil_abstract_archive.cpp
index 1a813f6..a52dd55 100644
--- a/port/cpl_vsil_abstract_archive.cpp
+++ b/port/cpl_vsil_abstract_archive.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_abstract_archive.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_abstract_archive.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for archive files.
@@ -35,7 +35,7 @@
 
 #define ENABLE_DEBUG 0
 
-CPL_CVSID("$Id: cpl_vsil_abstract_archive.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_abstract_archive.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 /************************************************************************/
 /*                    ~VSIArchiveEntryFileOffset()                      */
@@ -444,7 +444,7 @@ VSIArchiveReader* VSIArchiveFilesystemHandler::OpenArchiveFile(const char* archi
 /*                                 Stat()                               */
 /************************************************************************/
 
-int VSIArchiveFilesystemHandler::Stat( const char *pszFilename, VSIStatBufL *pStatBuf, int nFlags )
+int VSIArchiveFilesystemHandler::Stat( const char *pszFilename, VSIStatBufL *pStatBuf, CPL_UNUSED int nFlags )
 {
     int ret = -1;
     CPLString osFileInArchive;
@@ -521,7 +521,7 @@ int VSIArchiveFilesystemHandler::Stat( const char *pszFilename, VSIStatBufL *pSt
 /*                              Unlink()                                */
 /************************************************************************/
 
-int VSIArchiveFilesystemHandler::Unlink( const char *pszFilename )
+int VSIArchiveFilesystemHandler::Unlink( CPL_UNUSED const char *pszFilename )
 {
     return -1;
 }
@@ -530,7 +530,7 @@ int VSIArchiveFilesystemHandler::Unlink( const char *pszFilename )
 /*                             Rename()                                 */
 /************************************************************************/
 
-int VSIArchiveFilesystemHandler::Rename( const char *oldpath, const char *newpath )
+int VSIArchiveFilesystemHandler::Rename( CPL_UNUSED const char *oldpath, CPL_UNUSED const char *newpath )
 {
     return -1;
 }
@@ -539,7 +539,7 @@ int VSIArchiveFilesystemHandler::Rename( const char *oldpath, const char *newpat
 /*                             Mkdir()                                  */
 /************************************************************************/
 
-int VSIArchiveFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
+int VSIArchiveFilesystemHandler::Mkdir( CPL_UNUSED const char *pszDirname, CPL_UNUSED long nMode )
 {
     return -1;
 }
@@ -548,7 +548,7 @@ int VSIArchiveFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
 /*                             Rmdir()                                  */
 /************************************************************************/
 
-int VSIArchiveFilesystemHandler::Rmdir( const char *pszDirname )
+int VSIArchiveFilesystemHandler::Rmdir( CPL_UNUSED const char *pszDirname )
 {
     return -1;
 }
diff --git a/port/cpl_vsil_buffered_reader.cpp b/port/cpl_vsil_buffered_reader.cpp
index 527a121..f722295 100644
--- a/port/cpl_vsil_buffered_reader.cpp
+++ b/port/cpl_vsil_buffered_reader.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_buffered_reader.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_buffered_reader.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  VSI Virtual File System
  * Purpose:  Implementation of buffered reader IO functions.
@@ -37,7 +37,7 @@
 
 #define MAX_BUFFER_SIZE 65536
 
-CPL_CVSID("$Id: cpl_vsil_buffered_reader.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_buffered_reader.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 class VSIBufferedReaderHandle : public VSIVirtualHandle
 {
@@ -201,7 +201,7 @@ size_t VSIBufferedReaderHandle::Read( void *pBuffer, size_t nSize, size_t nMemb
 /*                              Write()                                 */
 /************************************************************************/
 
-size_t VSIBufferedReaderHandle::Write( const void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSIBufferedReaderHandle::Write( CPL_UNUSED const void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "VSIFWriteL is not supported on buffer reader streams\n");
diff --git a/port/cpl_vsil_cache.cpp b/port/cpl_vsil_cache.cpp
index 8b92bcf..2387ca1 100644
--- a/port/cpl_vsil_cache.cpp
+++ b/port/cpl_vsil_cache.cpp
@@ -478,8 +478,7 @@ size_t VSICachedFile::Read( void * pBuffer, size_t nSize, size_t nCount )
 /*                               Write()                                */
 /************************************************************************/
 
-size_t VSICachedFile::Write( const void * pBuffer, size_t nSize, size_t nCount )
-
+size_t VSICachedFile::Write( CPL_UNUSED const void * pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nCount )
 {
     return 0;
 }
diff --git a/port/cpl_vsil_curl.cpp b/port/cpl_vsil_curl.cpp
index a88cf25..e45430d 100644
--- a/port/cpl_vsil_curl.cpp
+++ b/port/cpl_vsil_curl.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_curl.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_curl.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for HTTP/FTP files
@@ -34,7 +34,7 @@
 #include "cpl_time.h"
 #include "cpl_vsil_curl_priv.h"
 
-CPL_CVSID("$Id: cpl_vsil_curl.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_curl.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 #ifndef HAVE_CURL
 
@@ -1381,7 +1381,7 @@ end:
 /*                               Write()                                */
 /************************************************************************/
 
-size_t VSICurlHandle::Write( const void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSICurlHandle::Write( CPL_UNUSED const void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 {
     return 0;
 }
@@ -2534,7 +2534,7 @@ int VSICurlFilesystemHandler::Stat( const char *pszFilename, VSIStatBufL *pStatB
 /*                               Unlink()                               */
 /************************************************************************/
 
-int VSICurlFilesystemHandler::Unlink( const char *pszFilename )
+int VSICurlFilesystemHandler::Unlink( CPL_UNUSED const char *pszFilename )
 {
     return -1;
 }
@@ -2543,7 +2543,7 @@ int VSICurlFilesystemHandler::Unlink( const char *pszFilename )
 /*                               Rename()                               */
 /************************************************************************/
 
-int VSICurlFilesystemHandler::Rename( const char *oldpath, const char *newpath )
+int VSICurlFilesystemHandler::Rename( CPL_UNUSED const char *oldpath, CPL_UNUSED const char *newpath )
 {
     return -1;
 }
@@ -2552,7 +2552,7 @@ int VSICurlFilesystemHandler::Rename( const char *oldpath, const char *newpath )
 /*                               Mkdir()                                */
 /************************************************************************/
 
-int VSICurlFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
+int VSICurlFilesystemHandler::Mkdir( CPL_UNUSED const char *pszDirname, CPL_UNUSED long nMode )
 {
     return -1;
 }
@@ -2560,7 +2560,7 @@ int VSICurlFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
 /*                               Rmdir()                                */
 /************************************************************************/
 
-int VSICurlFilesystemHandler::Rmdir( const char *pszDirname )
+int VSICurlFilesystemHandler::Rmdir( CPL_UNUSED const char *pszDirname )
 {
     return -1;
 }
diff --git a/port/cpl_vsil_curl_streaming.cpp b/port/cpl_vsil_curl_streaming.cpp
index e2a9f47..ded5eb6 100644
--- a/port/cpl_vsil_curl_streaming.cpp
+++ b/port/cpl_vsil_curl_streaming.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_curl_streaming.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_curl_streaming.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for HTTP/FTP files in streaming mode
@@ -33,7 +33,7 @@
 #include "cpl_hash_set.h"
 #include "cpl_time.h"
 
-CPL_CVSID("$Id: cpl_vsil_curl_streaming.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_curl_streaming.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 #if !defined(HAVE_CURL) || defined(CPL_MULTIPROC_STUB)
 
@@ -1265,7 +1265,7 @@ void  VSICurlStreamingHandle::AddRegion( vsi_l_offset    nFileOffsetStart,
 /*                               Write()                                */
 /************************************************************************/
 
-size_t VSICurlStreamingHandle::Write( const void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSICurlStreamingHandle::Write( CPL_UNUSED const void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 {
     return 0;
 }
diff --git a/port/cpl_vsil_gzip.cpp b/port/cpl_vsil_gzip.cpp
index 97b4009..fe76fa7 100644
--- a/port/cpl_vsil_gzip.cpp
+++ b/port/cpl_vsil_gzip.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_gzip.cpp 27048 2014-03-17 23:07:47Z rouault $
+ * $Id: cpl_vsil_gzip.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for gz/zip files (.gz and .zip).
@@ -84,7 +84,7 @@
 #include "cpl_minizip_unzip.h"
 #include "cpl_time.h"
 
-CPL_CVSID("$Id: cpl_vsil_gzip.cpp 27048 2014-03-17 23:07:47Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_gzip.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 #define Z_BUFSIZE 65536  /* original size is 16384 */
 static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
@@ -100,8 +100,8 @@ static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
 #define ALLOC(size) malloc(size)
 #define TRYFREE(p) {if (p) free(p);}
 
-#define CPL_VSIL_GZ_RETURN_MINUS_ONE()   \
-        CPLError(CE_Failure, CPLE_AppDefined, "In file %s, at line %d, return -1", __FILE__, __LINE__)
+#define CPL_VSIL_GZ_RETURN(ret)   \
+        CPLError(CE_Failure, CPLE_AppDefined, "In file %s, at line %d, return %d", __FILE__, __LINE__, ret)
 
 #define ENABLE_DEBUG 0
 
@@ -134,7 +134,7 @@ class VSIGZipHandle : public VSIVirtualHandle
     /* Fields from gz_stream structure */
     z_stream stream;
     int      z_err;   /* error code for last stream operation */
-    int      z_eof;   /* set if end of input file */
+    int      z_eof;   /* set if end of input file (but not necessarily of the uncompressed stream ! "in" must be null too ) */
     Byte     *inbuf;  /* input buffer */
     Byte     *outbuf; /* output buffer */
     uLong    crc;     /* crc32 of uncompressed data */
@@ -534,7 +534,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
         {
             if (out + offset > compressed_size)
             {
-                CPL_VSIL_GZ_RETURN_MINUS_ONE();
+                CPL_VSIL_GZ_RETURN(-1);
                 return -1L;
             }
 
@@ -544,7 +544,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
         {
             if (offset > compressed_size)
             {
-                CPL_VSIL_GZ_RETURN_MINUS_ONE();
+                CPL_VSIL_GZ_RETURN(-1);
                 return -1L;
             }
 
@@ -556,7 +556,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
             /* so no way to seek backward. See #1590 */
             if (offset > 0 /*|| -offset > compressed_size*/)
             {
-                CPL_VSIL_GZ_RETURN_MINUS_ONE();
+                CPL_VSIL_GZ_RETURN(-1);
                 return -1L;
             }
 
@@ -564,12 +564,12 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
         }
         else
         {
-            CPL_VSIL_GZ_RETURN_MINUS_ONE();
+            CPL_VSIL_GZ_RETURN(-1);
             return -1L;
         }
         if (VSIFSeekL((VSILFILE*)poBaseHandle, offset, SEEK_SET) < 0)
         {
-            CPL_VSIL_GZ_RETURN_MINUS_ONE();
+            CPL_VSIL_GZ_RETURN(-1);
             return -1L;
         }
 
@@ -605,7 +605,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
 
     if (/*whence == SEEK_END ||*/
         z_err == Z_ERRNO || z_err == Z_DATA_ERROR) {
-        CPL_VSIL_GZ_RETURN_MINUS_ONE();
+        CPL_VSIL_GZ_RETURN(-1);
         return -1L;
     }
 
@@ -620,7 +620,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
     if (offset >= out) {
         offset -= out;
     } else if (gzrewind() < 0) {
-            CPL_VSIL_GZ_RETURN_MINUS_ONE();
+            CPL_VSIL_GZ_RETURN(-1);
             return -1L;
     }
     
@@ -659,7 +659,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
     if (offset != 0 && outbuf == Z_NULL) {
         outbuf = (Byte*)ALLOC(Z_BUFSIZE);
         if (outbuf == Z_NULL) {
-            CPL_VSIL_GZ_RETURN_MINUS_ONE();
+            CPL_VSIL_GZ_RETURN(-1);
             return -1L;
         }
     }
@@ -676,7 +676,7 @@ int VSIGZipHandle::gzseek( vsi_l_offset offset, int whence )
 
         int read_size = Read(outbuf, 1, (uInt)size);
         if (read_size == 0) {
-            //CPL_VSIL_GZ_RETURN_MINUS_ONE();
+            //CPL_VSIL_GZ_RETURN(-1);
             return -1L;
         }
         if (original_nWhence == SEEK_END)
@@ -751,12 +751,15 @@ size_t VSIGZipHandle::Read( void *buf, size_t nSize, size_t nMemb )
 
     if  (z_err == Z_DATA_ERROR || z_err == Z_ERRNO)
     {
-        CPL_VSIL_GZ_RETURN_MINUS_ONE();
+        z_eof = 1; /* to avoid infinite loop in reader code */
+        in = 0;
+        CPL_VSIL_GZ_RETURN(0);
         return 0;
     }
-    if  (z_eof || z_err == Z_STREAM_END)
+    if  ((z_eof && in == 0) || z_err == Z_STREAM_END)
     {
         z_eof = 1;
+        in = 0;
         if (ENABLE_DEBUG) CPLDebug("GZIP", "Read: Eof");
         return 0;  /* EOF */
     }
@@ -894,7 +897,9 @@ size_t VSIGZipHandle::Read( void *buf, size_t nSize, size_t nMemb )
     if (len == stream.avail_out &&
             (z_err == Z_DATA_ERROR || z_err == Z_ERRNO))
     {
-        CPL_VSIL_GZ_RETURN_MINUS_ONE();
+        z_eof = 1;
+        in = 0;
+        CPL_VSIL_GZ_RETURN(0);
         return 0;
     }
     if (ENABLE_DEBUG)
@@ -924,7 +929,7 @@ uLong VSIGZipHandle::getLong ()
 /*                              Write()                                 */
 /************************************************************************/
 
-size_t VSIGZipHandle::Write( const void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSIGZipHandle::Write( CPL_UNUSED const void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 {
     CPLError(CE_Failure, CPLE_NotSupported, "VSIFWriteL is not supported on GZip streams");
     return 0;
@@ -938,7 +943,7 @@ size_t VSIGZipHandle::Write( const void *pBuffer, size_t nSize, size_t nMemb )
 int VSIGZipHandle::Eof()
 {
     if (ENABLE_DEBUG) CPLDebug("GZIP", "Eof()");
-    return z_eof;
+    return z_eof && in == 0;
 }
 
 /************************************************************************/
@@ -1116,7 +1121,7 @@ int VSIGZipWriteHandle::Close()
 /*                                Read()                                */
 /************************************************************************/
 
-size_t VSIGZipWriteHandle::Read( void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSIGZipWriteHandle::Read( CPL_UNUSED void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 
 {
     CPLError(CE_Failure, CPLE_NotSupported, "VSIFReadL is not supported on GZip write streams\n");
@@ -1492,7 +1497,7 @@ int VSIGZipFilesystemHandler::Stat( const char *pszFilename,
 /*                               Unlink()                               */
 /************************************************************************/
 
-int VSIGZipFilesystemHandler::Unlink( const char *pszFilename )
+int VSIGZipFilesystemHandler::Unlink( CPL_UNUSED const char *pszFilename )
 {
     return -1;
 }
@@ -1501,7 +1506,7 @@ int VSIGZipFilesystemHandler::Unlink( const char *pszFilename )
 /*                               Rename()                               */
 /************************************************************************/
 
-int VSIGZipFilesystemHandler::Rename( const char *oldpath, const char *newpath )
+int VSIGZipFilesystemHandler::Rename( CPL_UNUSED const char *oldpath, CPL_UNUSED const char *newpath )
 {
     return -1;
 }
@@ -1510,7 +1515,7 @@ int VSIGZipFilesystemHandler::Rename( const char *oldpath, const char *newpath )
 /*                               Mkdir()                                */
 /************************************************************************/
 
-int VSIGZipFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
+int VSIGZipFilesystemHandler::Mkdir( CPL_UNUSED const char *pszDirname, CPL_UNUSED long nMode )
 {
     return -1;
 }
@@ -1518,7 +1523,7 @@ int VSIGZipFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
 /*                               Rmdir()                                */
 /************************************************************************/
 
-int VSIGZipFilesystemHandler::Rmdir( const char *pszDirname )
+int VSIGZipFilesystemHandler::Rmdir( CPL_UNUSED const char *pszDirname )
 {
     return -1;
 }
@@ -1527,7 +1532,7 @@ int VSIGZipFilesystemHandler::Rmdir( const char *pszDirname )
 /*                             ReadDir()                                */
 /************************************************************************/
 
-char** VSIGZipFilesystemHandler::ReadDir( const char *pszDirname )
+char** VSIGZipFilesystemHandler::ReadDir( CPL_UNUSED const char *pszDirname )
 {
     return NULL;
 }
@@ -1940,7 +1945,7 @@ VSIVirtualHandle* VSIZipFilesystemHandler::Open( const char *pszFilename,
 /*                                Mkdir()                               */
 /************************************************************************/
 
-int VSIZipFilesystemHandler::Mkdir( const char *pszDirname, long nMode )
+int VSIZipFilesystemHandler::Mkdir( const char *pszDirname, CPL_UNUSED long nMode )
 {
     CPLString osDirname = pszDirname;
     if (osDirname.size() != 0 && osDirname[osDirname.size() - 1] != '/')
@@ -2200,7 +2205,7 @@ vsi_l_offset VSIZipWriteHandle::Tell()
 /*                               Read()                                 */
 /************************************************************************/
 
-size_t    VSIZipWriteHandle::Read( void *pBuffer, size_t nSize, size_t nMemb )
+size_t VSIZipWriteHandle::Read( CPL_UNUSED void *pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nMemb )
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "VSIFReadL() is not supported on writable Zip files");
@@ -2367,7 +2372,7 @@ void VSIInstallZipFileHandler(void)
  * @since GDAL 1.10.0
  */
 
-void* CPLZLibDeflate( const void* ptr, size_t nBytes, int nLevel,
+void* CPLZLibDeflate( const void* ptr, size_t nBytes, CPL_UNUSED int nLevel,
                       void* outptr, size_t nOutAvailableBytes,
                       size_t* pnOutBytes )
 {
diff --git a/port/cpl_vsil_sparsefile.cpp b/port/cpl_vsil_sparsefile.cpp
index db855b1..9a2c07e 100644
--- a/port/cpl_vsil_sparsefile.cpp
+++ b/port/cpl_vsil_sparsefile.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_sparsefile.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_sparsefile.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  VSI Virtual File System
  * Purpose:  Implementation of sparse file virtual io driver.
@@ -38,7 +38,7 @@
 #  include <wce_errno.h>
 #endif
 
-CPL_CVSID("$Id: cpl_vsil_sparsefile.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_sparsefile.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 class SFRegion { 
 public:
@@ -291,8 +291,7 @@ size_t VSISparseFileHandle::Read( void * pBuffer, size_t nSize, size_t nCount )
 /*                               Write()                                */
 /************************************************************************/
 
-size_t VSISparseFileHandle::Write( const void * pBuffer, size_t nSize, size_t nCount )
-
+size_t VSISparseFileHandle::Write( CPL_UNUSED const void * pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nCount )
 {
     errno = EBADF;
     return 0;
@@ -472,8 +471,7 @@ int VSISparseFileFilesystemHandler::Stat( const char * pszFilename,
 /*                               Unlink()                               */
 /************************************************************************/
 
-int VSISparseFileFilesystemHandler::Unlink( const char * pszFilename )
-
+int VSISparseFileFilesystemHandler::Unlink( CPL_UNUSED const char * pszFilename )
 {
     errno = EACCES;
     return -1;
@@ -483,9 +481,8 @@ int VSISparseFileFilesystemHandler::Unlink( const char * pszFilename )
 /*                               Mkdir()                                */
 /************************************************************************/
 
-int VSISparseFileFilesystemHandler::Mkdir( const char * pszPathname,
-                                    long nMode )
-
+int VSISparseFileFilesystemHandler::Mkdir( CPL_UNUSED const char * pszPathname,
+                                           CPL_UNUSED long nMode )
 {
     errno = EACCES;
     return -1;
@@ -495,8 +492,7 @@ int VSISparseFileFilesystemHandler::Mkdir( const char * pszPathname,
 /*                               Rmdir()                                */
 /************************************************************************/
 
-int VSISparseFileFilesystemHandler::Rmdir( const char * pszPathname )
-
+int VSISparseFileFilesystemHandler::Rmdir( CPL_UNUSED const char * pszPathname )
 {
     errno = EACCES;
     return -1;
@@ -506,8 +502,7 @@ int VSISparseFileFilesystemHandler::Rmdir( const char * pszPathname )
 /*                              ReadDir()                               */
 /************************************************************************/
 
-char **VSISparseFileFilesystemHandler::ReadDir( const char *pszPath )
-
+char **VSISparseFileFilesystemHandler::ReadDir( CPL_UNUSED const char *pszPath )
 {
     errno = EACCES;
     return NULL;
diff --git a/port/cpl_vsil_stdin.cpp b/port/cpl_vsil_stdin.cpp
index 5390a97..10a7f7d 100644
--- a/port/cpl_vsil_stdin.cpp
+++ b/port/cpl_vsil_stdin.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_vsil_stdin.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_stdin.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for stdin
@@ -37,7 +37,7 @@
 #include <fcntl.h>
 #endif
 
-CPL_CVSID("$Id: cpl_vsil_stdin.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_stdin.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 /* We buffer the first 1MB of standard input to enable drivers */
 /* to autodetect data. In the first MB, backward and forward seeking */
@@ -264,9 +264,8 @@ size_t VSIStdinHandle::Read( void * pBuffer, size_t nSize, size_t nCount )
 /*                               Write()                                */
 /************************************************************************/
 
-size_t VSIStdinHandle::Write( const void * pBuffer, size_t nSize, 
-                                  size_t nCount )
-
+size_t VSIStdinHandle::Write( CPL_UNUSED const void * pBuffer, CPL_UNUSED size_t nSize, 
+                              CPL_UNUSED size_t nCount )
 {
     CPLError(CE_Failure, CPLE_NotSupported,
              "Write() unsupported on /vsistdin");
diff --git a/port/cpl_vsil_stdout.cpp b/port/cpl_vsil_stdout.cpp
index 8ab16d3..16e16e8 100644
--- a/port/cpl_vsil_stdout.cpp
+++ b/port/cpl_vsil_stdout.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_vsil_stdout.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_stdout.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for stdout
@@ -37,7 +37,7 @@
 #include <fcntl.h>
 #endif
 
-CPL_CVSID("$Id: cpl_vsil_stdout.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_stdout.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -110,8 +110,7 @@ int VSIStdoutHandle::Flush()
 /*                                Read()                                */
 /************************************************************************/
 
-size_t VSIStdoutHandle::Read( void * pBuffer, size_t nSize, size_t nCount )
-
+size_t VSIStdoutHandle::Read( CPL_UNUSED void * pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nCount )
 {
     CPLError(CE_Failure, CPLE_NotSupported, "Read() unsupported on /vsistdout");
     return 0;
@@ -159,9 +158,8 @@ int VSIStdoutHandle::Close()
 /************************************************************************/
 
 VSIVirtualHandle *
-VSIStdoutFilesystemHandler::Open( const char *pszFilename, 
+VSIStdoutFilesystemHandler::Open( CPL_UNUSED const char *pszFilename, 
                                   const char *pszAccess )
-
 {
     if ( strchr(pszAccess, 'r') != NULL ||
          strchr(pszAccess, '+') != NULL )
@@ -183,10 +181,9 @@ VSIStdoutFilesystemHandler::Open( const char *pszFilename,
 /*                                Stat()                                */
 /************************************************************************/
 
-int VSIStdoutFilesystemHandler::Stat( const char * pszFilename,
+int VSIStdoutFilesystemHandler::Stat( CPL_UNUSED const char * pszFilename,
                                       VSIStatBufL * pStatBuf,
-                                      int nFlags )
-
+                                      CPL_UNUSED int nFlags )
 {
     memset( pStatBuf, 0, sizeof(VSIStatBufL) );
 
@@ -253,8 +250,7 @@ VSIStdoutRedirectHandle::~VSIStdoutRedirectHandle()
 /*                                Seek()                                */
 /************************************************************************/
 
-int VSIStdoutRedirectHandle::Seek( vsi_l_offset nOffset, int nWhence )
-
+int VSIStdoutRedirectHandle::Seek( CPL_UNUSED vsi_l_offset nOffset, CPL_UNUSED int nWhence )
 {
     CPLError(CE_Failure, CPLE_NotSupported, "Seek() unsupported on /vsistdout_redirect");
     return -1;
@@ -283,8 +279,7 @@ int VSIStdoutRedirectHandle::Flush()
 /*                                Read()                                */
 /************************************************************************/
 
-size_t VSIStdoutRedirectHandle::Read( void * pBuffer, size_t nSize, size_t nCount )
-
+size_t VSIStdoutRedirectHandle::Read( CPL_UNUSED void * pBuffer, CPL_UNUSED size_t nSize, CPL_UNUSED size_t nCount )
 {
     CPLError(CE_Failure, CPLE_NotSupported, "Read() unsupported on /vsistdout_redirect");
     return 0;
@@ -356,10 +351,9 @@ VSIStdoutRedirectFilesystemHandler::Open( const char *pszFilename,
 /*                                Stat()                                */
 /************************************************************************/
 
-int VSIStdoutRedirectFilesystemHandler::Stat( const char * pszFilename,
+int VSIStdoutRedirectFilesystemHandler::Stat( CPL_UNUSED const char * pszFilename,
                                       VSIStatBufL * pStatBuf,
-                                      int nFlags )
-
+                                      CPL_UNUSED int nFlags )
 {
     memset( pStatBuf, 0, sizeof(VSIStatBufL) );
 
diff --git a/port/cpl_vsil_subfile.cpp b/port/cpl_vsil_subfile.cpp
index db488de..dd9a3ad 100644
--- a/port/cpl_vsil_subfile.cpp
+++ b/port/cpl_vsil_subfile.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_vsil_subfile.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_subfile.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  VSI Virtual File System
  * Purpose:  Implementation of subfile virtual IO functions.
@@ -37,7 +37,7 @@
 #  include <wce_errno.h>
 #endif
 
-CPL_CVSID("$Id: cpl_vsil_subfile.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_subfile.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 /************************************************************************/
 /* ==================================================================== */
@@ -385,8 +385,7 @@ int VSISubFileFilesystemHandler::Stat( const char * pszFilename,
 /*                               Unlink()                               */
 /************************************************************************/
 
-int VSISubFileFilesystemHandler::Unlink( const char * pszFilename )
-
+int VSISubFileFilesystemHandler::Unlink( CPL_UNUSED const char * pszFilename )
 {
     errno = EACCES;
     return -1;
@@ -396,9 +395,8 @@ int VSISubFileFilesystemHandler::Unlink( const char * pszFilename )
 /*                               Mkdir()                                */
 /************************************************************************/
 
-int VSISubFileFilesystemHandler::Mkdir( const char * pszPathname,
-                                    long nMode )
-
+int VSISubFileFilesystemHandler::Mkdir( CPL_UNUSED const char * pszPathname,
+                                        CPL_UNUSED long nMode )
 {
     errno = EACCES;
     return -1;
@@ -408,8 +406,7 @@ int VSISubFileFilesystemHandler::Mkdir( const char * pszPathname,
 /*                               Rmdir()                                */
 /************************************************************************/
 
-int VSISubFileFilesystemHandler::Rmdir( const char * pszPathname )
-
+int VSISubFileFilesystemHandler::Rmdir( CPL_UNUSED const char * pszPathname )
 {
     errno = EACCES;
     return -1;
@@ -419,8 +416,7 @@ int VSISubFileFilesystemHandler::Rmdir( const char * pszPathname )
 /*                              ReadDir()                               */
 /************************************************************************/
 
-char **VSISubFileFilesystemHandler::ReadDir( const char *pszPath )
-
+char **VSISubFileFilesystemHandler::ReadDir( CPL_UNUSED const char *pszPath )
 {
     errno = EACCES;
     return NULL;
diff --git a/port/cpl_vsil_unix_stdio_64.cpp b/port/cpl_vsil_unix_stdio_64.cpp
index 365497a..99cf0c2 100644
--- a/port/cpl_vsil_unix_stdio_64.cpp
+++ b/port/cpl_vsil_unix_stdio_64.cpp
@@ -1,5 +1,5 @@
 /**********************************************************************
- * $Id: cpl_vsil_unix_stdio_64.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_vsil_unix_stdio_64.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement VSI large file api for Unix platforms with fseek64()
@@ -52,7 +52,7 @@
 #include <dirent.h>
 #include <errno.h>
 
-CPL_CVSID("$Id: cpl_vsil_unix_stdio_64.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_vsil_unix_stdio_64.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 #if defined(UNIX_STDIO_64)
 
@@ -169,7 +169,11 @@ class VSIUnixStdioHandle : public VSIVirtualHandle
 /*                       VSIUnixStdioHandle()                           */
 /************************************************************************/
 
-VSIUnixStdioHandle::VSIUnixStdioHandle(VSIUnixStdioFilesystemHandler *poFSIn,
+VSIUnixStdioHandle::VSIUnixStdioHandle(
+#ifndef VSI_COUNT_BYTES_READ
+CPL_UNUSED
+#endif
+                                       VSIUnixStdioFilesystemHandler *poFSIn,
                                        FILE* fpIn, int bReadOnlyIn) :
     fp(fpIn), nOffset(0), bReadOnly(bReadOnlyIn), bLastOpWrite(FALSE), bLastOpRead(FALSE), bAtEOF(FALSE)
 #ifdef VSI_COUNT_BYTES_READ
@@ -504,7 +508,7 @@ VSIUnixStdioFilesystemHandler::Open( const char *pszFilename,
 
 int VSIUnixStdioFilesystemHandler::Stat( const char * pszFilename, 
                                          VSIStatBufL * pStatBuf,
-                                         int nFlags)
+                                         CPL_UNUSED int nFlags)
 
 {
     return( VSI_STAT64( pszFilename, pStatBuf ) );
diff --git a/port/cpl_xml_validate.cpp b/port/cpl_xml_validate.cpp
index 4df7fcb..77c4bfa 100644
--- a/port/cpl_xml_validate.cpp
+++ b/port/cpl_xml_validate.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cpl_xml_validate.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cpl_xml_validate.cpp 27722 2014-09-22 15:37:31Z goatbar $
  *
  * Project:  CPL - Common Portability Library
  * Purpose:  Implement XML validation against XSD schema
@@ -29,7 +29,7 @@
 
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: cpl_xml_validate.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cpl_xml_validate.cpp 27722 2014-09-22 15:37:31Z goatbar $");
 
 #ifdef HAVE_LIBXML2
 #include <libxml/xmlversion.h>
@@ -984,7 +984,7 @@ void CPLFreeXMLSchema(CPLXMLSchemaPtr pSchema)
 
 int CPLValidateXML(const char* pszXMLFilename,
                    const char* pszXSDFilename,
-                   char** papszOptions)
+                   CPL_UNUSED char** papszOptions)
 {
     char szHeader[2048];
     CPLString osTmpXSDFilename;
diff --git a/port/cplgetsymbol.cpp b/port/cplgetsymbol.cpp
index 843c709..9ec2a66 100644
--- a/port/cplgetsymbol.cpp
+++ b/port/cplgetsymbol.cpp
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: cplgetsymbol.cpp 27044 2014-03-16 23:41:27Z rouault $
+ * $Id: cplgetsymbol.cpp 27461 2014-06-18 12:38:34Z rouault $
  *
  * Project:  Common Portability Library
  * Purpose:  Fetch a function pointer from a shared library / DLL.
@@ -30,7 +30,7 @@
 
 #include "cpl_conv.h"
 
-CPL_CVSID("$Id: cplgetsymbol.cpp 27044 2014-03-16 23:41:27Z rouault $");
+CPL_CVSID("$Id: cplgetsymbol.cpp 27461 2014-06-18 12:38:34Z rouault $");
 
 
 /* ==================================================================== */
@@ -143,8 +143,8 @@ void *CPLGetSymbol( const char * pszLibrary, const char * pszSymbolName )
     void        *pSymbol;
     UINT        uOldErrorMode;
 
-    /* Avoid error boxes to pop up (#5122) */
-    uOldErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX);
+    /* Avoid error boxes to pop up (#5211, #5525) */
+    uOldErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
 
     pLibrary = LoadLibrary(pszLibrary);
 
diff --git a/swig/include/java/gdal_java.i b/swig/include/java/gdal_java.i
index 840ba98..9ffa91a 100644
--- a/swig/include/java/gdal_java.i
+++ b/swig/include/java/gdal_java.i
@@ -1,5 +1,5 @@
 /******************************************************************************
- * $Id: gdal_java.i 26749 2013-12-27 10:17:31Z rouault $
+ * $Id: gdal_java.i 27432 2014-06-03 18:28:26Z goatbar $
  *
  * Name:     gdal_java.i
  * Project:  GDAL SWIG Interface
@@ -252,7 +252,7 @@ static CPLErr DatasetRasterIO( GDALDatasetH hDS, GDALRWFlag eRWFlag,
               "Buffer is too small");
       return CE_Failure;
   }
-  return  GDALDatasetRasterIO( hDS, GF_Read, xoff, yoff, xsize, ysize,
+  return  GDALDatasetRasterIO( hDS, eRWFlag, xoff, yoff, xsize, ysize,
                                 regularArray, buf_xsize, buf_ysize,
                                 buf_type, band_list, pband_list, nPixelSpace, nLineSpace, nBandSpace );
 
diff --git a/swig/include/perl/gdal_perl.i b/swig/include/perl/gdal_perl.i
index 4995115..255f2a6 100644
--- a/swig/include/perl/gdal_perl.i
+++ b/swig/include/perl/gdal_perl.i
@@ -116,8 +116,8 @@ ALTERED_DESTROY(GDALRasterAttributeTableShadow, GDALc, delete_RasterAttributeTab
     # etc.  GDAL 2.0 should then get VERSION 2.000 and 2.1 should get
     # 2.001 etc.
 
-    our $VERSION = '1.992';
-    our $GDAL_VERSION = '1.11.0';
+    our $VERSION = '1.9921';
+    our $GDAL_VERSION = '1.11.1';
     use vars qw/
 	%TYPE_STRING2INT %TYPE_INT2STRING
 	%ACCESS_STRING2INT %ACCESS_INT2STRING
diff --git a/swig/include/perl/ogr_perl.i b/swig/include/perl/ogr_perl.i
index fd84aec..79d6fbc 100644
--- a/swig/include/perl/ogr_perl.i
+++ b/swig/include/perl/ogr_perl.i
@@ -884,7 +884,7 @@ ALTERED_DESTROY(OGRGeometryShadow, OGRc, delete_Geometry)
 	    } elsif (@_ == 1) {
 		$param{Name} = shift;
 	    } else {
-		my %known = map {$_ => 1} qw/Name Type Justify Width Precision/;
+		my %known = map {$_ => 1} qw/Index Name Type Justify Width Precision/;
 		unless ($known{$_[0]}) {
 		    $param{Name} = shift;
 		    $param{Type} = shift;
diff --git a/swig/include/perl/typemaps_perl.i b/swig/include/perl/typemaps_perl.i
index 95ca8bd..ff49ef7 100644
--- a/swig/include/perl/typemaps_perl.i
+++ b/swig/include/perl/typemaps_perl.i
@@ -946,7 +946,7 @@ static AV *XMLTreeToAV( CPLXMLNode *psTree )
 %define IF_UNDEF_SET_EMPTY_STRING(type, param)
 %typemap(default) type param {
     /* %typemap(default) type param */
-    $1 = (type)"";
+    $1 = (char *)"";
 }
 %enddef
 
diff --git a/swig/perl/gdal_wrap.cpp b/swig/perl/gdal_wrap.cpp
index cdd8b5b..afb74a6 100644
--- a/swig/perl/gdal_wrap.cpp
+++ b/swig/perl/gdal_wrap.cpp
@@ -4505,7 +4505,7 @@ XS(_wrap_PushFinderLocation) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 1)) {
       SWIG_croak("Usage: PushFinderLocation(utf8_path);");
@@ -4653,7 +4653,7 @@ XS(_wrap_FindFile) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: FindFile(pszClass,utf8_path);");
@@ -4724,7 +4724,7 @@ XS(_wrap_ReadDir) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 1)) {
       SWIG_croak("Usage: ReadDir(utf8_path);");
@@ -4811,7 +4811,7 @@ XS(_wrap_ReadDirRecursive) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 1)) {
       SWIG_croak("Usage: ReadDirRecursive(utf8_path);");
@@ -5178,7 +5178,7 @@ XS(_wrap_FileFromMemBuffer) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 3)) {
       SWIG_croak("Usage: FileFromMemBuffer(utf8_path,nBytes,pabyData);");
@@ -5256,7 +5256,7 @@ XS(_wrap_Unlink) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 1)) {
       SWIG_croak("Usage: Unlink(utf8_path);");
@@ -5358,7 +5358,7 @@ XS(_wrap_Mkdir) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: Mkdir(utf8_path,mode);");
@@ -5425,7 +5425,7 @@ XS(_wrap_Rmdir) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 1)) {
       SWIG_croak("Usage: Rmdir(utf8_path);");
@@ -5548,7 +5548,7 @@ XS(_wrap_Stat) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     {
       /* %typemap(in,numinputs=0) (VSIStatBufL *) (VSIStatBufL sStatBuf2) */
@@ -5644,7 +5644,7 @@ XS(_wrap_VSIFOpenL) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: VSIFOpenL(utf8_path,pszMode);");
@@ -6987,7 +6987,7 @@ XS(_wrap_Driver__Create) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 7)) {
       SWIG_croak("Usage: Driver__Create(self,utf8_path,xsize,ysize,bands,eType,options);");
@@ -7144,7 +7144,7 @@ XS(_wrap_Driver_CreateCopy) {
     arg7 = (void *)(&saved_env);
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 7)) {
       SWIG_croak("Usage: Driver_CreateCopy(self,utf8_path,src,strict,options,callback,callback_data);");
@@ -7300,7 +7300,7 @@ XS(_wrap_Driver_Delete) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: Driver_Delete(self,utf8_path);");
@@ -22143,7 +22143,7 @@ XS(_wrap__Open__SWIG_1) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: _Open(utf8_path,eAccess);");
@@ -22265,7 +22265,7 @@ XS(_wrap__OpenShared__SWIG_1) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: _OpenShared(utf8_path,eAccess);");
@@ -22385,7 +22385,7 @@ XS(_wrap_IdentifyDriver) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: IdentifyDriver(utf8_path,papszSiblings);");
diff --git a/swig/perl/lib/Geo/GDAL.pm b/swig/perl/lib/Geo/GDAL.pm
index 7dc5f95..eb7b7b6 100644
--- a/swig/perl/lib/Geo/GDAL.pm
+++ b/swig/perl/lib/Geo/GDAL.pm
@@ -612,8 +612,8 @@ package Geo::GDAL;
     # etc.  GDAL 2.0 should then get VERSION 2.000 and 2.1 should get
     # 2.001 etc.
 
-    our $VERSION = '1.992';
-    our $GDAL_VERSION = '1.11.0';
+    our $VERSION = '1.9921';
+    our $GDAL_VERSION = '1.11.1';
     use vars qw/
 	%TYPE_STRING2INT %TYPE_INT2STRING
 	%ACCESS_STRING2INT %ACCESS_INT2STRING
diff --git a/swig/perl/lib/Geo/OGR.pm b/swig/perl/lib/Geo/OGR.pm
index 62a453d..1f01802 100644
--- a/swig/perl/lib/Geo/OGR.pm
+++ b/swig/perl/lib/Geo/OGR.pm
@@ -1454,7 +1454,7 @@ package Geo::OGR;
 	    } elsif (@_ == 1) {
 		$param{Name} = shift;
 	    } else {
-		my %known = map {$_ => 1} qw/Name Type Justify Width Precision/;
+		my %known = map {$_ => 1} qw/Index Name Type Justify Width Precision/;
 		unless ($known{$_[0]}) {
 		    $param{Name} = shift;
 		    $param{Type} = shift;
diff --git a/swig/perl/ogr_wrap.cpp b/swig/perl/ogr_wrap.cpp
index d52ac1e..7365979 100644
--- a/swig/perl/ogr_wrap.cpp
+++ b/swig/perl/ogr_wrap.cpp
@@ -3424,7 +3424,7 @@ XS(_wrap_StyleTable_LoadStyleTable) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: StyleTable_LoadStyleTable(self,utf8_path);");
@@ -3487,7 +3487,7 @@ XS(_wrap_StyleTable_SaveStyleTable) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: StyleTable_SaveStyleTable(self,utf8_path);");
@@ -3842,7 +3842,7 @@ XS(_wrap_Driver_CreateDataSource) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 3)) {
       SWIG_croak("Usage: Driver_CreateDataSource(self,utf8_path,options);");
@@ -3948,7 +3948,7 @@ XS(_wrap_Driver_CopyDataSource) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg3 = (const char *)"";
+      arg3 = (char *)"";
     }
     if ((items < 2) || (items > 4)) {
       SWIG_croak("Usage: Driver_CopyDataSource(self,copy_ds,utf8_path,options);");
@@ -4060,7 +4060,7 @@ XS(_wrap_Driver_Open) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 3)) {
       SWIG_croak("Usage: Driver_Open(self,utf8_path,update);");
@@ -4132,7 +4132,7 @@ XS(_wrap_Driver_DeleteDataSource) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg2 = (const char *)"";
+      arg2 = (char *)"";
     }
     if ((items < 1) || (items > 2)) {
       SWIG_croak("Usage: Driver_DeleteDataSource(self,utf8_path);");
@@ -22339,7 +22339,7 @@ XS(_wrap_Open) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: Open(utf8_path,update);");
@@ -22404,7 +22404,7 @@ XS(_wrap_OpenShared) {
     
     {
       /* %typemap(default) const char * utf8_path */
-      arg1 = (const char *)"";
+      arg1 = (char *)"";
     }
     if ((items < 0) || (items > 2)) {
       SWIG_croak("Usage: OpenShared(utf8_path,update);");
diff --git a/swig/python/README.txt b/swig/python/README.txt
index 3da0fca..d13868e 100644
--- a/swig/python/README.txt
+++ b/swig/python/README.txt
@@ -16,7 +16,7 @@ reference documentation, but the `GDAL API Tutorial`_ includes Python examples.
 Dependencies
 ------------
  
- * libgdal (1.10.0 or greater) and header files (gdal-devel)
+ * libgdal (1.11.0 or greater) and header files (gdal-devel)
  * numpy (1.0.0 or greater) and header files (numpy-devel) (not explicitly 
    required, but many examples and utilities will not work without it)
 
@@ -208,7 +208,7 @@ the data are explicitly subsetted as part of the function call. For large
 data, this approach is expected to be prohibitively memory intensive.
 
 .. _GDAL API Tutorial: http://www.gdal.org/gdal_tutorial.html
-.. _GDAL Windows Binaries: http://vbkto.dyndns.org/sdk/
+.. _GDAL Windows Binaries: http://gisinternals.com/sdk/
 .. _Microsoft KnowledgeBase doc: http://support.microsoft.com/kb/310519
 .. _Python Cheeseshop: http://pypi.python.org/pypi/GDAL/
 .. _val_repl.py: http://trac.osgeo.org/gdal/browser/trunk/gdal/swig/python/samples/val_repl.py
diff --git a/swig/python/scripts/gdal2tiles.py b/swig/python/scripts/gdal2tiles.py
index 498d737..f49872e 100755
--- a/swig/python/scripts/gdal2tiles.py
+++ b/swig/python/scripts/gdal2tiles.py
@@ -1,7 +1,7 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 #******************************************************************************
-#  $Id: gdal2tiles.py 27044 2014-03-16 23:41:27Z rouault $
+#  $Id: gdal2tiles.py 27349 2014-05-16 18:58:51Z rouault $
 # 
 # Project:  Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
 # Support:  BRGM (http://www.brgm.fr)
@@ -58,7 +58,7 @@ except:
     # 'antialias' resampling is not available
     pass
 
-__version__ = "$Id: gdal2tiles.py 27044 2014-03-16 23:41:27Z rouault $"
+__version__ = "$Id: gdal2tiles.py 27349 2014-05-16 18:58:51Z rouault $"
 
 resampling_list = ('average','near','bilinear','cubic','cubicspline','lanczos','antialias')
 profile_list = ('mercator','geodetic','raster') #,'zoomify')
@@ -1523,8 +1523,8 @@ gdal2tiles temp.vrt""" % self.input )
       <Title>%(title)s</Title>
       <Abstract></Abstract>
       <SRS>%(srs)s</SRS>
-      <BoundingBox minx="%(south).14f" miny="%(west).14f" maxx="%(north).14f" maxy="%(east).14f"/>
-      <Origin x="%(south).14f" y="%(west).14f"/>
+      <BoundingBox minx="%(west).14f" miny="%(south).14f" maxx="%(east).14f" maxy="%(north).14f"/>
+      <Origin x="%(west).14f" y="%(south).14f"/>
       <TileFormat width="%(tilesize)d" height="%(tilesize)d" mime-type="image/%(tileformat)s" extension="%(tileformat)s"/>
       <TileSets profile="%(profile)s">
 """ % args
diff --git a/swig/python/scripts/pct2rgb.py b/swig/python/scripts/pct2rgb.py
index 76ed7fe..6395321 100755
--- a/swig/python/scripts/pct2rgb.py
+++ b/swig/python/scripts/pct2rgb.py
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 #******************************************************************************
-#  $Id: pct2rgb.py 27044 2014-03-16 23:41:27Z rouault $
+#  $Id: pct2rgb.py 27490 2014-07-02 17:43:54Z rouault $
 # 
 #  Name:     pct2rgb
 #  Project:  GDAL Python Interface
@@ -122,7 +122,7 @@ if dst_driver is None:
 
 ct = src_band.GetRasterColorTable()
 
-ct_size = max(256, ct.GetCount())
+ct_size = ct.GetCount()
 lookup = [Numeric.arrayrange(ct_size),
           Numeric.arrayrange(ct_size),
           Numeric.arrayrange(ct_size),
diff --git a/swig/python/setup.py b/swig/python/setup.py
index b1859aa..1b5660c 100644
--- a/swig/python/setup.py
+++ b/swig/python/setup.py
@@ -7,7 +7,7 @@
 # Howard Butler hobu.inc at gmail.com
 
 
-gdal_version = '1.11.0'
+gdal_version = '1.11.1'
 
 import sys
 import os

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



More information about the Pkg-grass-devel mailing list