[metview] 02/06: New upstream release 4.5.7

Alastair McKinstry mckinstry at moszumanska.debian.org
Wed Oct 21 19:38:08 UTC 2015


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

mckinstry pushed a commit to branch debian/master
in repository metview.

commit 3fbb6c5e38db4622e123c5b276b8d7bfa1139b2e
Author: Alastair McKinstry <mckinstry at debian.org>
Date:   Tue Oct 20 20:00:28 2015 +0100

    New upstream release 4.5.7
---
 CMakeLists.txt                                     | 180 ++++--
 VERSION.cmake                                      |   2 +-
 cmake/CheckFortranSourceCompiles.cmake             |   2 +-
 cmake/FindAEC.cmake                                |   2 -
 cmake/FindArmadillo.cmake                          |  33 +-
 cmake/FindEMOS.cmake                               |   2 -
 cmake/FindEcLib.cmake                              |  49 --
 cmake/FindEcregrid.cmake                           |  48 --
 cmake/FindLibIFort.cmake                           |  47 ++
 cmake/FindMKL.cmake                                |  77 +++
 cmake/FindNetCDF.cmake                             | 145 +++--
 cmake/FindNetCDF3.cmake                            |  65 +-
 cmake/FindOpenCL.cmake                             |  67 ++
 cmake/FindOpenJPEG.cmake                           |   3 +-
 cmake/FindPango.cmake                              |   2 -
 cmake/FindPangoCairo.cmake                         |  13 +-
 cmake/FindProj4.cmake                              |  10 +-
 cmake/FindSZip.cmake                               |   2 -
 cmake/FindScin.cmake                               |  48 --
 cmake/FindTrilinos.cmake                           |   3 -
 cmake/FindViennaCL.cmake                           |  38 ++
 cmake/Findgrib_api.cmake                           |   2 -
 cmake/Findodb_api.cmake                            |   2 -
 cmake/Findspot.cmake                               |   2 -
 cmake/VERSION.cmake                                |   4 +-
 cmake/contrib/FindEigen3.cmake                     |  10 +-
 cmake/contrib/FindFFTW.cmake                       |  52 +-
 cmake/contrib/FindNetCDF4.cmake                    |  14 +-
 cmake/ecbuild_add_cxx11_flags.cmake                |  20 +-
 cmake/ecbuild_add_executable.cmake                 | 433 ++++++++-----
 cmake/ecbuild_add_extra_search_paths.cmake         |  23 +-
 cmake/ecbuild_add_library.cmake                    | 688 ++++++++++++---------
 cmake/ecbuild_add_option.cmake                     | 184 ++++--
 cmake/ecbuild_add_persistent.cmake                 |  92 ++-
 cmake/ecbuild_add_resources.cmake                  |  95 ++-
 cmake/ecbuild_add_test.cmake                       | 610 ++++++++++--------
 cmake/ecbuild_append_to_rpath.cmake                |  35 +-
 cmake/ecbuild_bundle.cmake                         | 338 ++++------
 cmake/ecbuild_cache.cmake                          |  34 +-
 cmake/ecbuild_check_c_source.cmake                 |  73 ++-
 cmake/ecbuild_check_compiler.cmake                 |  28 +-
 cmake/ecbuild_check_cxx11.cmake                    |  76 ++-
 cmake/ecbuild_check_cxx_source.cmake               |  73 ++-
 cmake/ecbuild_check_fortran_source.cmake           |  68 +-
 cmake/ecbuild_check_functions.cmake                |  65 +-
 cmake/ecbuild_check_os.cmake                       |  54 +-
 cmake/ecbuild_config.h.in                          |  25 +
 cmake/ecbuild_debug_var.cmake                      |  12 +
 cmake/ecbuild_declare_project.cmake                | 216 ++++---
 cmake/ecbuild_define_build_types.cmake             |  43 +-
 cmake/ecbuild_define_options.cmake                 |   8 +-
 cmake/ecbuild_define_uninstall.cmake               |   7 +
 cmake/ecbuild_dont_pack.cmake                      |  82 +++
 cmake/ecbuild_download_resource.cmake              |  47 ++
 cmake/ecbuild_echo_targets.cmake                   |  67 +-
 cmake/ecbuild_enable_fortran.cmake                 |  80 ++-
 cmake/ecbuild_features.cmake                       | 121 ++++
 cmake/ecbuild_find_fortranlibs.cmake               | 210 ++++---
 cmake/ecbuild_find_lexyacc.cmake                   |  96 +--
 cmake/ecbuild_find_mpi.cmake                       | 118 +++-
 cmake/ecbuild_find_omp.cmake                       |  72 ++-
 cmake/ecbuild_find_package.cmake                   | 394 ++++++++----
 cmake/ecbuild_find_perl.cmake                      |  76 ++-
 cmake/ecbuild_find_python.cmake                    |  74 ++-
 cmake/ecbuild_generate_config_headers.cmake        |  62 +-
 cmake/ecbuild_generate_rpc.cmake                   |  31 +-
 cmake/ecbuild_generate_yy.cmake                    | 227 ++++---
 cmake/ecbuild_get_cxx11_flags.cmake                |  71 +++
 cmake/ecbuild_get_date.cmake                       |  28 +-
 cmake/ecbuild_get_test_data.cmake                  | 206 ++++--
 cmake/ecbuild_git.cmake                            | 307 +++++++++
 ...package.cmake => ecbuild_install_project.cmake} | 156 +++--
 cmake/ecbuild_list_extra_search_paths.cmake        |  53 +-
 cmake/ecbuild_list_macros.cmake                    |  33 +
 cmake/ecbuild_log.cmake                            | 129 ++++
 cmake/ecbuild_pkgconfig.cmake                      | 168 +++--
 cmake/ecbuild_policies.cmake                       |  63 ++
 cmake/ecbuild_print_summary.cmake                  | 177 +++---
 cmake/ecbuild_project_files.cmake                  |  60 +-
 cmake/ecbuild_requires_macro_version.cmake         |  12 +
 cmake/ecbuild_separate_sources.cmake               |  32 +-
 cmake/ecbuild_setup_test_framework.cmake           |  47 +-
 cmake/ecbuild_system.cmake                         | 387 ++++++------
 cmake/ecbuild_uninstall.cmake.in                   |  21 +
 cmake/ecbuild_use_package.cmake                    | 353 ++++++-----
 cmake/ecbuild_warn_unused_files.cmake              |  29 +-
 cmake/pkg-config.pc.in                             |   8 +-
 cmake/project-config.cmake.in                      |  11 +-
 cmake/pymain.c                                     |   5 +
 scripts/CMakeLists.txt                             |  83 ++-
 scripts/CONFIG.site.in                             |  38 --
 scripts/compile.in                                 |   4 +-
 scripts/generate_icon_fun_help.mv                  |   5 +-
 scripts/{metview_base => metview_base.in}          |  87 ++-
 share/metview/app-defaults/CMakeLists.txt          |  12 +-
 share/metview/etc/CMakeLists.txt                   |  42 +-
 share/metview/etc/EPSOutputDef                     |   8 +-
 share/metview/etc/MCOASTDef                        |  26 +
 share/metview/etc/MCOASTRules                      |   3 +
 share/metview/etc/MSYMBRules                       |   2 +-
 share/metview/etc/PDFOutputDef                     |   6 +-
 share/metview/etc/PNGOutputDef                     |   6 +-
 share/metview/etc/PSOutputDef                      |   8 +-
 share/metview/etc/ecmwf.def                        |  47 +-
 share/metview/etc/obsgroups.def                    |   1 +
 share/metview/etc/reportypes.def                   |  16 +
 share/metview/etc/rt_by_obsgroup.chk               |  15 +-
 share/metview/etc/uPlotTable                       |   2 +-
 share/metview/icons/CMakeLists.txt                 |  17 +-
 share/metview/icons_mv5/CMakeLists.txt             |   6 +-
 src/AppMod/CMakeLists.txt                          |  15 +-
 src/BufrExaminer/CMakeLists.txt                    |   7 +-
 src/DebugTools/CMakeLists.txt                      |  20 +-
 src/DebugTools/XServ.h                             |   6 +-
 src/Desktop/CMakeLists.txt                         |  17 +-
 src/Desktop/Editor.h                               |   2 +-
 src/Desktop/MvQDetailedFolderView.cc               |   4 +
 src/Desktop/MvQFileBrowser.cc                      |  35 +-
 src/Desktop/MvQFileBrowser.h                       |   3 +
 src/Desktop/MvQFolderModel.cc                      |  12 +-
 src/Desktop/MvQIconFolderView.cc                   |   9 +-
 src/Desktop/MvQIconHolder.cc                       |   2 +-
 src/Desktop/MvQIconMimeData.cc                     |   4 +-
 src/Desktop/MvQIconObjectModel.cc                  |   2 +-
 src/Desktop/MvQListFolderViewBase.cc               |   1 +
 src/Desktop/MvQNewIconWidget.cc                    |   1 +
 src/Desktop/MvQProductBrowser.cc                   |   2 +-
 src/Desktop/ViewEditor.cc                          |   7 +-
 src/FlextraExaminer/CMakeLists.txt                 |   7 +-
 src/GeopExaminer/CMakeLists.txt                    |   6 +-
 src/GeopExaminer/MvGeoPointsModel.cc               |   2 +-
 src/GribExaminer/CMakeLists.txt                    |   6 +-
 src/GribExaminer/MvQGribDumpModel.cc               |  12 +-
 src/Hovmoeller/HovToolkit.cc                       |  19 +-
 src/MacroEditor/CMakeLists.txt                     |  14 +-
 src/MacroEditor/CodeTemplateDialog.cc              |   6 +-
 src/MacroEditor/FunctionListDialog.cc              |   6 +-
 src/MacroEditor/GotoLineDialog.cc                  |   6 +-
 src/MacroEditor/MacroEdit.cc                       |   8 +-
 src/MacroEditor/VerbFunctionHelp.cc                |   6 +-
 src/MacroEditor/VerbFunctionHelpDialog.cc          |   6 +-
 src/MacroEditor/mvplaintextedit.h                  |   7 +-
 src/MagML/CMakeLists.txt                           |   3 +
 src/MarsCatalog/CMakeLists.txt                     |  10 +-
 src/MarsCatalog/ObjectSpec.MarsCatalog             |   2 +-
 src/MetviewUI/CMakeLists.txt                       |   2 +-
 src/MvApp/grib_to_geo.cc                           |   4 +-
 src/NcExaminer/CMakeLists.txt                      |   7 +-
 src/OdbExaminer/CMakeLists.txt                     |   7 +-
 src/OdbExaminer/MvQOdbStatModel.cc                 |   5 +-
 src/OgcClient/CMakeLists.txt                       |  15 +-
 src/OgcClient/MvQWmsClientEditor.cc                |   4 +-
 src/OgcClient/ObjectSpec.WcsClient                 |   2 +-
 src/OgcClient/ObjectSpec.WmsClient                 |   2 +-
 src/Reprojection/CMakeLists.txt                    |   3 +
 src/ScmEditor/CMakeLists.txt                       |  11 +-
 src/StdAppManager/NetcdfPlusRules                  |   4 -
 src/Thermo/BufrThermo.cc                           | 114 ++--
 src/Thermo/BufrThermo.h                            |   3 +
 src/Thermo/CMakeLists.txt                          |   9 +-
 src/Thermo/GribThermo.cc                           |  37 +-
 src/Thermo/MTHERMO.svg                             | 390 ++++++++++++
 src/Thermo/MTHERMOGRID.svg                         | 377 +++++++++++
 src/Thermo/MTHERMOGRIDDef                          | 322 ++++++++++
 src/Thermo/MTHERMOGRIDRules                        |  62 ++
 src/Thermo/MThermoDef                              | 114 ++++
 src/Thermo/MThermoRules                            |   4 +
 src/Thermo/ObjectSpec.Thermo                       |  28 +
 src/Thermo/Thermo.cc                               |  52 +-
 src/Thermo/Thermo.h                                |   7 +-
 src/WebAccess/CMakeLists.txt                       |   2 +-
 src/XSection/Average.cc                            |  17 +-
 src/XSection/Average.h                             |   2 +-
 src/XSection/CrossS.cc                             | 397 +++++++-----
 src/XSection/CrossS.h                              |  13 +-
 src/XSection/MXSectionCommonDef                    |  35 ++
 src/XSection/MXSectionCommonRules                  |  13 +
 src/XSection/MXSectionDef                          |  10 +
 src/XSection/MXSectionRules                        |  10 +
 src/XSection/MXSectionViewDef                      |   8 +-
 src/XSection/MvXsectFrame.cc                       | 436 ++++++++++---
 src/XSection/MvXsectFrame.h                        | 102 ++-
 src/XSection/Vprofile.cc                           |   6 +-
 src/XSection/Vprofile.h                            |   2 +-
 src/XSection/Xsect.cc                              | 339 +++++-----
 src/XSection/Xsect.h                               |  35 +-
 src/libMars/CMakeLists.txt                         |   9 +-
 src/libMarsClient/nfdbbase.c                       |  10 +-
 src/libMarsClient/pproc.c                          |  12 +-
 src/libMetview/MvFieldSet.cc                       |  18 +-
 src/libMetview/MvFieldSet.h                        |   3 -
 src/libMetview/MvGrid.cc                           |  57 +-
 src/libMvQtGui/CMakeLists.txt                      |   9 +-
 src/libMvQtGui/MvQAbout.cc                         |   6 +
 src/libMvQtGui/MvQApplication.h                    |   6 +-
 src/libMvQtGui/MvQDragDrop.cc                      |   1 +
 src/libMvQtGui/MvQFileDialog.cc                    |   5 +-
 src/libMvQtGui/MvQKeyFilterModel.cc                |   6 +-
 src/libMvQtGui/MvQKeyModel.cc                      |   2 +-
 src/libMvQtGui/MvQKeyProfileModel.cc               |   2 +-
 src/libMvQtGui/MvQKeyProfileTree.cc                |  10 +-
 src/libMvQtGui/MvQOdbModel.cc                      |   7 +-
 src/libMvQtGui/MvQProfileView.cc                   |   6 +-
 src/libMvQtGui/MvQScmModel.cc                      |  14 +-
 src/libMvQtGui/MvQStationsWidget.cc                |   2 +-
 src/libMvQtGui/MvQX11Application.h                 |   6 +-
 src/libMvQtUtil/CMakeLists.txt                     |   7 +-
 src/libMvQtUtil/MvQKeyManager.cc                   |   9 +-
 src/libMvQtUtil/MvQKeyManager.h                    |   6 +-
 src/libMvQtUtil/MvQNetworkAccessManager.cc         |   9 +-
 src/libMvQtUtil/MvQNetworkAccessManager.h          |   7 +-
 src/libMvQtUtil/MvQNetworkProxyFactory.cc          |   4 +-
 src/libMvQtUtil/MvQNetworkProxyFactory.h           |   6 +-
 src/libMvQtUtil/MvQVisDefManager.cc                |  10 +-
 src/libMvQtUtil/MvQXmlQuery.h                      |  12 +-
 src/uPlot/CMakeLists.txt                           |  35 +-
 src/uPlot/CartesianView.cc                         |  13 +-
 src/uPlot/CartesianView.h                          |  95 ++-
 src/uPlot/CommonXSectView.cc                       |  95 ++-
 src/uPlot/CommonXSectView.h                        |  15 +-
 src/uPlot/DataObject.cc                            |  75 ++-
 src/uPlot/ExportDialog.cc                          |   6 +
 src/uPlot/MagPlusService.h                         |   2 +
 src/uPlot/MagicsTranslator.cc                      |  34 +-
 src/uPlot/MvCallback.hpp                           |   2 +-
 src/uPlot/MvQDataWidget.cc                         |   2 +-
 src/uPlot/MvQLayerModel.cc                         |   4 +-
 src/uPlot/MvQZoomStackWidget.cc                    |   6 +-
 src/uPlot/MvQZoomStackWidget.h                     |   6 +-
 src/uPlot/ObjectList.cc                            |  12 +
 src/uPlot/ObjectList.h                             |   2 +
 src/uPlot/PlotModConst.h                           |  24 +-
 src/uPlot/PlotModView.cc                           |  41 +-
 src/uPlot/ThermoView.cc                            | 125 +++-
 src/uPlot/ThermoView.h                             |  13 +-
 src/uPlot/uPlotBase.cc                             |   4 +-
 test/macros/CMakeLists.txt                         |  16 +
 test/macros/post_install_tests.sh.in               |  30 +
 238 files changed, 9156 insertions(+), 3820 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index dfa1cd4..2ebebe5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -25,7 +25,14 @@ cmake_minimum_required( VERSION 2.8.4 FATAL_ERROR )
 project( metview C CXX Fortran)
 
 
-set(MV_BIN_DIR bin/metview_bin) # all executables and scripts apart from the startup script should go here
+# All executables and scripts apart from the startup script should go into MV_BIN_DIR.
+# Users can override by setting METVIEW_INSTALL_EXE_BIN_DIR.
+# It should be relative to the root of the install directory.
+if(DEFINED METVIEW_INSTALL_EXE_BIN_DIR)
+    set(MV_BIN_DIR ${METVIEW_INSTALL_EXE_BIN_DIR})
+else()
+    set(MV_BIN_DIR bin/metview_bin)
+endif()
 
 
 set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/../ecbuild/cmake")
@@ -33,10 +40,10 @@ set(CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE OFF)
 
 set(METVIEW_INSTALL_BIN_DIR "${MV_BIN_DIR}" CACHE PATH "Metview installation directory for executable files")
 
-include( ecbuild_system )
+include( ecbuild_system NO_POLICY_SCOPE )
 
 
-ecbuild_requires_macro_version( 1.2 )
+ecbuild_requires_macro_version( 1.9 )
 
 ecbuild_enable_fortran( REQUIRED )
 
@@ -53,6 +60,7 @@ option( ENABLE_ODB           "enable ODB"
 option( ENABLE_MARS_ODB      "enable ODB in MARS"                                 OFF )
 option( ENABLE_USAGE_LOG     "enable usage logging (only at ECMWF)"               OFF )
 option( ENABLE_QT_DEBUG      "enable Qt debugging messages"                       OFF )
+option( ENABLE_QT5           "enable Qt5"                                         OFF )
 option( ENABLE_INPE          "enable INPE modules"                                ON )
 option( ENABLE_WEATHER_ROOM  "enable Weather Room plot export (only at ECMWF)"    OFF )
 option( ENABLE_NETWORK_PROXY "enable network proxy settings for WMS"              OFF )
@@ -131,6 +139,7 @@ else()
     # otherwise look in some default locations
     set(MARS_SOURCE_PATHS ${CMAKE_SOURCE_DIR}/src/libMars         # embedded in source
                           ${CMAKE_SOURCE_DIR}/src/libMarsClient   # embedded in source
+                          ${CMAKE_SOURCE_DIR}/mars-client/src     # bundle
                           ${CMAKE_SOURCE_DIR}/../client/src       # in external dir
                           ${CMAKE_SOURCE_DIR}/../mars-client/src) # in external dir
 endif()
@@ -220,7 +229,6 @@ endif()
 # ecbuild_use_package( PROJECT eckit VERSION 0.3 REQUIRED )
 
 ecbuild_use_package( PROJECT grib_api VERSION 1.13.0 REQUIRED )
-list( APPEND METVIEW_TPLS grib_api )
 
 
 if(ENABLE_ODB)
@@ -231,7 +239,10 @@ if(ENABLE_ODB)
         list(FIND ODB_API_LIBRARIES eckit ODB_ECKIT_INDEX)
    
 
-        if (NOT ODB_ECKIT_INDEX EQUAL -1)  # is an eckit version
+        if ((NOT ODB_ECKIT_INDEX EQUAL -1) OR (DEFINED ODB_ECKIT))  # is an eckit version
+            if (DEFINED SEPARATE_ECKIT)
+                ecbuild_use_package( PROJECT eckit VERSION 0.6 REQUIRED )
+            endif()
             add_definitions(-DODB_ECKIT)
         endif()
 
@@ -247,7 +258,15 @@ if(ENABLE_ODB)
                                          ${ODB_API_INCLUDE_DIRS}/..
                                          ${ODB_API_INCLUDE_DIRS}/../eclib
                                          ${ODB_API_INCLUDE_DIRS}/../eclib/eclib
-                                         ${ODB_API_INCLUDE_DIRS}/odblib) 
+                                         ${ODB_API_INCLUDE_DIRS}/odblib
+                                         ${ECKIT_INCLUDE_DIRS}) 
+
+        # remove eckit_cmd because it's not needed for Metview, and causes problems when linked
+        # with Metview
+        list(REMOVE_ITEM ODB_API_LIBRARIES eckit_cmd)
+        message(STATUS "after removal of eckit_cmd:")
+        message(STATUS "ODB_API_LIBRARIES: ${ODB_API_LIBRARIES}")
+
     else()
         if(ENABLE_MARS_ODB)
             message(FATAL_ERROR "ENABLE_ODB was set, but ODB not found")
@@ -295,6 +314,8 @@ if(ENABLE_ODB)
 endif()
 
 
+ecbuild_use_package( PROJECT libemos VERSION 4.0.5 REQUIRED )
+
 
 # ------------------------------------------------------------------------
 # MACRO metview_get_magics_config
@@ -304,7 +325,7 @@ endif()
 
 macro(metview_get_magics_config MAGICS_INFO MAGICS_OUT)
 
-    set(command ${MAGICS_BIN_PATH}magics-config --${MAGICS_INFO})
+    set(command ${MAGICS_BIN_PATH}${MAGICS_CONFIG_CMD} --${MAGICS_INFO})
 
     execute_process(COMMAND ${command}
                     RESULT_VARIABLE cmdres
@@ -328,26 +349,51 @@ if(ENABLE_PLOTTING)
     ecbuild_use_package( PROJECT magics VERSION 2.24.3)
     if( MAGICS_FOUND )
 
+        set(MAGICS_CONFIG_CMD  "magics-config")
+
         if(DEFINED MAGICS_PATH) # user supplied MAGICS_PATH
             message (STATUS "MAGICS_PATH supplied: ${MAGICS_PATH}")
             set(MAGICS_BIN_PATH "${MAGICS_PATH}/bin/") # note the trailing slash
+            set(MAGICS_METGRAM_DIR "${MAGICS_BIN_PATH}")
         else()
-            # if MAGICS_PATH was not defined, then we probably picked up Magics from
-            # a system directory. We use MAGICS_CMAKE_DIR and work backwards from there
-            # to find the bin directory . This assumes a standard Magics installation
-            # where we have: <prefix>/bin  and  <prefix>/share/magics/cmake
-            # so the bin directory is ${MAGICS_CMAKE_DIR}/../../../bin
-
-            set(MAGICS_BIN_PATH "${MAGICS_CMAKE_DIR}/../../../bin/")
-            message (STATUS "MAGICS_PATH not supplied: bin dir should be at ${MAGICS_BIN_PATH}")
+
+            # building as part of a bundle which includes Magics?
+            if(DEFINED magics_BINARY_DIR)
+                set(MAGICS_BIN_PATH "${magics_BINARY_DIR}/")  # note the trailing slash
+                message(STATUS "Found Magics as part of the bundle: ${MAGICS_BIN_PATH}")
+
+                # magics-config will not have execute permission, so make a copy
+                file(COPY ${MAGICS_BIN_PATH}/magics-config 
+                     DESTINATION ${MAGICS_BIN_PATH}/bin
+                     FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ
+                     GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
+                set(MAGICS_BIN_PATH "${MAGICS_BIN_PATH}/bin/") # note the trailing slash
+                set(MAGICS_METGRAM_DIR "${MAGICS_subproj_dir_}/apps/metgram/") # where we find the metgram script
+
+                # if Magics is part of the bundle, then we need to manually add MAGICS_TPL_INCLUDE_DIRS
+                list(APPEND MAGICS_INCLUDE_DIRS ${MAGICS_TPL_INCLUDE_DIRS})
+
+            else()
+                # if MAGICS_PATH was not defined, then we probably picked up Magics from
+                # a system directory. We use MAGICS_CMAKE_DIR and work backwards from there
+                # to find the bin directory . This assumes a standard Magics installation
+                # where we have: <prefix>/bin  and  <prefix>/share/magics/cmake
+                # so the bin directory is ${MAGICS_CMAKE_DIR}/../../../bin
+
+                set(MAGICS_BIN_PATH "${MAGICS_CMAKE_DIR}/../../../bin/")
+                set(MAGICS_METGRAM_DIR "${MAGICS_BIN_PATH}")
+                message (STATUS "MAGICS_PATH not supplied: bin dir should be at ${MAGICS_BIN_PATH}")
+            endif()
         endif()
 
+
         metview_get_magics_config("libdir" magout)
         list(APPEND MAGICS_LIBRARIES "-L${magout}")
+        list(APPEND MAGICS_LIBRARIES "-L${CMAKE_BINARY_DIR}/lib") # for bundles
         set(MAGICS_LIB_DIR ${magout})
 
-        list(APPEND MAGICS_LIBRARIES "-lMagWrapper")
-        set(MAGICS_METEOGRAM_SCRIPT "${MAGICS_BIN_PATH}metgram")
+        list(APPEND MAGICS_LIBRARIES "MagWrapper")
+        set(MAGICS_METEOGRAM_SCRIPT "${MAGICS_METGRAM_DIR}metgram")
 
         metview_get_magics_config("with-metview" magout)
         if(NOT magout STREQUAL "yes")
@@ -378,7 +424,22 @@ if(ENABLE_PLOTTING)
             message(STATUS "NO BUFR plotting support (disabled in Magics)")  #xxx should be at end
         endif()
 
-        ###list( APPEND METVIEW_TPLS magics )
+        #list( APPEND METVIEW_TPLS magics )
+
+
+#message(STATUS "xMAGICS_INCLUDE_DIRS: ${MAGICS_INCLUDE_DIRS}")
+#message(STATUS "xMAGICS_EXTRA_INCLUDES: ${MAGICS_EXTRA_INCLUDES}")
+#message(STATUS "xMAGICS_TPL_INCLUDE_DIRS: ${MAGICS_TPL_INCLUDE_DIRS}")
+#message(STATUS "xMAGICS_LIBS: ${MAGICS_LIBS}")
+#message(STATUS "xMAGICS_LIBRARIES: ${MAGICS_LIBRARIES}")
+
+
+
+#get_cmake_property(_variableNames VARIABLES)
+#foreach (_variableName ${_variableNames})
+#    message(STATUS "${_variableName}=${${_variableName}}")
+#endforeach()
+
 
     else()
         message(FATAL_ERROR "Magics was not found, and it is required if ENABLE_PLOTTING=ON. Please supply MAGICS_PATH if necessary.")
@@ -392,11 +453,6 @@ message(STATUS "VERSION: ${METVIEW_VERSION_STR}")
 ###############################################################################
 # Find external dependencies
 
-find_package( EMOS  REQUIRED ) 
-#find_library(EMOS_LIBRARIES emosR64 PATHS ${EMOS_PATH})
-
-
-
 #set( CMAKE_THREAD_PREFER_PTHREAD 1 )
 #find_package( Threads ) 
 
@@ -516,6 +572,36 @@ endif()
 
 if( ENABLE_UI )
 
+ if( ENABLE_QT5 )
+
+      if( ENABLE_MOTIF )
+        message(FATAL_ERROR "Metview does not support the Motif user interface with Qt5. Please set ENABLE_MOTIF=OFF in the CMake arguments")
+      endif()
+
+      find_package(Qt5Widgets REQUIRED)
+      find_package(Qt5Gui REQUIRED)
+      find_package(Qt5Network REQUIRED)
+      find_package(Qt5Xml REQUIRED)
+      find_package(Qt5XmlPatterns REQUIRED)
+      find_package(Qt5PrintSupport REQUIRED)
+
+      #if( ENABLE_MOTIF )
+        #find_package(Qt5X11Extras REQUIRED)
+        # we would add this to include_directories()  : ${Qt5X11Extras_INCLUDE_DIRS}
+        # But... the X11 interface has changed in Qt5 and there's probably no demand
+        # to support both Motif and Qt anymore.
+      #endif()
+
+      if( Qt5Widgets_FOUND )
+          message(STATUS "Qt5 version ${Qt5Widgets_VERSION_STRING} was found")
+          include_directories(${Qt5Widgets_INCLUDE_DIRS} ${Qt5Gui_INCLUDE_DIRS} ${Qt5Xml_INCLUDE_DIRS} ${Qt5XmlPatterns_INCLUDE_DIRS} ${Qt5Network_INCLUDE_DIRS} ${Qt5PrintSupport_INCLUDE_DIRS})
+          set( METVIEW_QT 1)
+          set( METVIEW_QT5 true)
+          add_definitions( -DMETVIEW_QT5 )
+      else()
+          message(FATAL_ERROR "Qt5 was NOT found ...")
+      endif()
+  else( ENABLE_QT5 )
     find_package(Qt4 4.6.2 REQUIRED QtCore QtNetwork QtGui QtXml QtXmlPatterns) #  QtWebKit QtHelp
     if( QT_FOUND )
         include( ${QT_USE_FILE} )
@@ -523,6 +609,7 @@ if( ENABLE_UI )
     else()
         message(FATAL_ERROR "Qt not found - this is required for the user interface")
     endif()
+  endif( ENABLE_QT5 )
 
 
     if( ENABLE_MOTIF )
@@ -588,7 +675,7 @@ endif()
 ###############################################################################
 # contents
 
-######set( METVIEW_TPLS grib_api odb_api EXPAT NetCDF PangoCairo Proj4 EMOS)
+######set( METVIEW_TPLS grib_api odb_api EXPAT NetCDF PangoCairo Proj4 libemos)
 
 set( METVIEW_STANDARD_INCLUDE_DIRS 
         ${CMAKE_CURRENT_SOURCE_DIR}/src/libMetview
@@ -602,8 +689,8 @@ set( METVIEW_STANDARD_INCLUDE_DIRS
         ${Boost_INCLUDE_DIRS} )
 
 if (MOTIF_FOUND)
-    list (APPEND METVIEW_STANDARD_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvMotif)
-    set  (METVIEW_MOTIF_LIBS MvMotif)
+    set(METVIEW_MOTIF_LIBS MvMotif)
+    set(METVIEW_MOTIF_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvMotif)
 endif()
 
 
@@ -614,31 +701,41 @@ if( METVIEW_ODB )
     )
 endif()
 
-set(STANDARD_METVIEW_LIBS Metview FTimeUtil Util MvNetCDF MvMars ${EMOS_LIBRARIES}) ### ${METVIEW_3RDPARTY_LIBS}"
+set(STANDARD_METVIEW_LIBS Metview FTimeUtil Util MvNetCDF MvMars ${LIBEMOS_LIBRARIES}) ### ${METVIEW_3RDPARTY_LIBS}"
 set(METVIEW_MACRO_API_F90_LIB macro_api_f90)
 
+unset( LIBEMOS_DEFINITIONS ) # no need to use exported libemos definitions 
 
+# only want certain third-party libraries linked with all modules - the rest
+# are on a per-module basis
+set(METVIEW_TPLS grib_api NetCDF)
 foreach( _tpl ${METVIEW_TPLS} )
     string( TOUPPER ${_tpl} TPL )
     list( APPEND METVIEW_EXTRA_DEFINITIONS   ${${TPL}_DEFINITIONS}  )
     list( APPEND METVIEW_EXTRA_INCLUDE_DIRS  ${${TPL}_INCLUDE_DIRS} )
     list( APPEND METVIEW_EXTRA_LIBRARIES     ${${TPL}_LIBRARIES} )
-    message(STATUS "${TPL_LIBRARIES}")
+    message(STATUS "xTPL_LIBRARIES: ${TPL}_LIBRARIES")
 endforeach()
 
 
 ###list( APPEND METVIEW_EXTRA_DEFINITIONS   fortfloat=double fortint=int boolean=bool )
 
 if( ENABLE_UI )
+  if( METVIEW_QT5 )
+    list( APPEND METVIEW_QT_INCLUDE_DIRS ${Qt5Widgets_INCLUDE_DIR} ${Qt5Gui_INCLUDE_DIR} ${Qt5Xml_INCLUDE_DIR} ${Qt5XmlPatterns_INCLUDE_DIR} ${Qt5Network_INCLUDE_DIR} ${Qt5PrintSupport_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvQtUtil ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvQtGui )
+    list( APPEND METVIEW_QT_LIBRARIES  MvQtGui MvQtUtil ${Qt5Widgets_LIBRARIES} ${Qt5Gui_LIBRARIES} ${Qt5Xml_LIBRARIES} ${Qt5XmlPatterns_LIBRARIES} ${Qt5Network_LIBRARIES} ${Qt5PrintSupport_LIBRARIES})
+  else()
     list( APPEND METVIEW_QT_INCLUDE_DIRS  ${QT_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvQtUtil ${CMAKE_CURRENT_SOURCE_DIR}/src/libMvQtGui )
     list( APPEND METVIEW_QT_LIBRARIES     MvQtGui MvQtUtil ${QT_LIBRARIES} )
 endif()
+endif()
+
 
 message(STATUS "METVIEW_EXTRA_DEFINITIONS  => ${METVIEW_EXTRA_DEFINITIONS}")
 message(STATUS "METVIEW_EXTRA_INCLUDE_DIRS => ${METVIEW_EXTRA_INCLUDE_DIRS}")
 message(STATUS "METVIEW_EXTRA_LIBRARIES    => ${METVIEW_EXTRA_LIBRARIES}")
 message(STATUS "STANDARD_METVIEW_LIBS      => ${STANDARD_METVIEW_LIBS}")
-message(STATUS "EMOS_LIBRARIES             => ${EMOS_LIBRARIES}")
+message(STATUS "LIBEMOS_LIBRARIES          => ${LIBEMOS_LIBRARIES}")
 
 
 ###get_directory_property( MAGICS_DEFINITIONS COMPILE_DEFINITIONS )
@@ -673,13 +770,13 @@ endif()
 # -------------------------
 
 if     (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" )
-    cmake_add_cxx_flags("-fpermissive -Wno-write-strings -Wno-deprecated")
+    ecbuild_add_cxx_flags("-fpermissive -Wno-write-strings -Wno-deprecated")
 elseif (CMAKE_CXX_COMPILER_ID STREQUAL "clang" )
-    cmake_add_cxx_flags("-fpermissive -Wno-deprecated -undefined dynamic_lookup")
+    ecbuild_add_cxx_flags("-fpermissive -Wno-deprecated -undefined dynamic_lookup")
 endif()
 
 if     (CMAKE_C_COMPILER_ID STREQUAL "clang" )
-    cmake_add_c_flags("-undefined dynamic_lookup")     #  "-fno-common  -mmacosx-version-min=10.8")
+    ecbuild_add_c_flags("-undefined dynamic_lookup")     #  "-fno-common  -mmacosx-version-min=10.8")
 endif()
 
 
@@ -688,13 +785,15 @@ endif()
 # ensure double-precision REALs
 
 if(CMAKE_Fortran_COMPILER_ID STREQUAL "PGI")
-    cmake_add_fortran_flags("-r8")
+    ecbuild_add_fortran_flags("-r8")
+elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "Intel")
+    ecbuild_add_fortran_flags("-r8")
 elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
     # NOTE that if we add -fdefault-real-8 then we NEED -fdefault-double-8 to avoid quadmath
-    cmake_add_fortran_flags("-fdefault-real-8 -fdefault-double-8")
+    ecbuild_add_fortran_flags("-fdefault-real-8 -fdefault-double-8")
 endif()
 # for grib_api.mod
-cmake_add_fortran_flags("-I${GRIB_API_INCLUDE_DIR}")
+ecbuild_add_fortran_flags("-I${GRIB_API_INCLUDE_DIR}")
 
 
 # we have to create the share directories now, because otherwise module-specific
@@ -842,7 +941,7 @@ endif()
 
 
 # install the metview.desktop file
-install( FILES ${CMAKE_SOURCE_DIR}/metview.desktop
+install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/metview.desktop
          DESTINATION share/applications/
          PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ )
 
@@ -914,10 +1013,17 @@ ecbuild_dont_pack(FILES "share/metview/grib_seed" )
 
 #ecbuild_add_resources(TARGET package_source SOURCES_PACK ${CMAKE_CURRENT_SOURCE_DIR}/../ecbuild/cmake/ecbuild_find_python.cmake)
 
-
 ############################################################################################
 # finalize
 
+
+# print all variables
+#get_cmake_property(_variableNames VARIABLES)
+#foreach (_variableName ${_variableNames})
+#    message(STATUS "${_variableName}=${${_variableName}}")
+#endforeach()
+
+
 ecbuild_install_project( NAME Metview )
 
 ecbuild_print_summary()
diff --git a/VERSION.cmake b/VERSION.cmake
index c900703..5752bc4 100644
--- a/VERSION.cmake
+++ b/VERSION.cmake
@@ -1,5 +1,5 @@
 set(${PROJECT_NAME}_MAJOR_VERSION_STR    "4")
 set(${PROJECT_NAME}_MINOR_VERSION_STR    "5")
-set(${PROJECT_NAME}_REVISION_VERSION_STR "6")
+set(${PROJECT_NAME}_REVISION_VERSION_STR "7")
 
 set(${PROJECT_NAME}_VERSION_STR  "${${PROJECT_NAME}_MAJOR_VERSION_STR}.${${PROJECT_NAME}_MINOR_VERSION_STR}.${${PROJECT_NAME}_REVISION_VERSION_STR}")
diff --git a/cmake/CheckFortranSourceCompiles.cmake b/cmake/CheckFortranSourceCompiles.cmake
index ad4b91f..4303315 100644
--- a/cmake/CheckFortranSourceCompiles.cmake
+++ b/cmake/CheckFortranSourceCompiles.cmake
@@ -29,7 +29,7 @@
 
 macro(CHECK_FORTRAN_SOURCE_COMPILES SOURCE VAR)
 
-if("${VAR}" MATCHES "^${VAR}$")
+if( ${VAR} MATCHES "^${VAR}$" )
     set(_FAIL_REGEX)
     set(_key)
     foreach(arg ${ARGN})
diff --git a/cmake/FindAEC.cmake b/cmake/FindAEC.cmake
index 70a63b1..28d086d 100644
--- a/cmake/FindAEC.cmake
+++ b/cmake/FindAEC.cmake
@@ -14,8 +14,6 @@
 #  AEC_INCLUDE_DIRS - The AEC include directories
 #  AEC_LIBRARIES - The libraries needed to use AEC
 
-ecbuild_add_extra_search_paths( aec )
-
 if( DEFINED AEC_PATH )
     find_path( AEC_INCLUDE_DIR szlib.h    PATHS ${AEC_PATH}/include PATH_SUFFIXES aec NO_DEFAULT_PATH )
     find_library( AEC_LIBRARY  NAMES aec  PATHS ${AEC_PATH}/lib     PATH_SUFFIXES aec NO_DEFAULT_PATH )
diff --git a/cmake/FindArmadillo.cmake b/cmake/FindArmadillo.cmake
index ba14e2e..4183306 100644
--- a/cmake/FindArmadillo.cmake
+++ b/cmake/FindArmadillo.cmake
@@ -6,19 +6,28 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-ecbuild_add_extra_search_paths( armadillo )
-
-IF( NOT DEFINED ARMADILLO_PATH AND NOT "$ENV{ARMADILLO_PATH}" STREQUAL "" )
-  SET( ARMADILLO_PATH "$ENV{ARMADILLO_PATH}" )
-ENDIF()
-
-if( DEFINED ARMADILLO_PATH )
-        find_path(ARMADILLO_INCLUDE_DIR ARMADILLO.h PATHS ${ARMADILLO_PATH}/include PATH_SUFFIXES ARMADILLO  NO_DEFAULT_PATH)
-        find_library(ARMADILLO_LIBRARY  ARMADILLO   PATHS ${ARMADILLO_PATH}/lib     PATH_SUFFIXES ARMADILLO  NO_DEFAULT_PATH)
-endif()
-
+# - Try to find Armadillo
+# Once done this will define
+#
+#  ARMADILLO_FOUND         - system has Armadillo
+#  ARMADILLO_INCLUDE_DIRS  - the Armadillo include directory
+#  ARMADILLO_LIBRARIES     - the Armadillo library
+#
+# The following paths will be searched with priority if set in CMake or env
+#
+#  ARMADILLO_PATH          - prefix path of the Armadillo installation
+
+# Search with priority for ARMADILLO_PATH if given as CMake or env var
+find_path(ARMADILLO_INCLUDE_DIR armadillo
+          PATHS ${ARMADILLO_PATH} ENV ARMADILLO_PATH
+          PATH_SUFFIXES include NO_DEFAULT_PATH)
 find_path(ARMADILLO_INCLUDE_DIR  armadillo PATH_SUFFIXES include )
-find_library( ARMADILLO_LIBRARY  armadillo   PATH_SUFFIXES lib )
+
+# Search with priority for ARMADILLO_PATH if given as CMake or env var
+find_library(ARMADILLO_LIBRARY armadillo
+             PATHS ${ARMADILLO_PATH} ENV ARMADILLO_PATH
+             PATH_SUFFIXES lib64 lib NO_DEFAULT_PATH)
+find_library( ARMADILLO_LIBRARY  armadillo   PATH_SUFFIXES lib64 lib )
 
 set( ARMADILLO_LIBRARIES    ${ARMADILLO_LIBRARY} )
 set( ARMADILLO_INCLUDE_DIRS ${ARMADILLO_INCLUDE_DIR} )
diff --git a/cmake/FindEMOS.cmake b/cmake/FindEMOS.cmake
index 8472b0a..56ee334 100644
--- a/cmake/FindEMOS.cmake
+++ b/cmake/FindEMOS.cmake
@@ -12,8 +12,6 @@
 #  EMOS_INCLUDE_DIRS - The EMOS include directories
 #  EMOS_LIBRARIES - The libraries needed to use EMOS
 
-ecbuild_add_extra_search_paths( libemos )
-
 if( NOT DEFINED EMOS_PATH AND DEFINED $ENV{EMOS_PATH} )
 	set( EMOS_PATH $ENV{EMOS_PATH} )
 endif()
diff --git a/cmake/FindEcLib.cmake b/cmake/FindEcLib.cmake
deleted file mode 100644
index 5799c85..0000000
--- a/cmake/FindEcLib.cmake
+++ /dev/null
@@ -1,49 +0,0 @@
-# (C) Copyright 1996-2014 ECMWF.
-#
-# This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
-# In applying this licence, ECMWF does not waive the privileges and immunities
-# granted to it by virtue of its status as an intergovernmental organisation nor
-# does it submit to any jurisdiction.
-
-# - Try to find EcLib
-# Once done this will define
-#  ECLIB_FOUND - System has ECLIB
-#  ECLIB_INCLUDE_DIRS - The ECLIB include directories
-#  ECLIB_LIBRARIES - The libraries needed to use ECLIB
-
-# skip if ECLIB is already found or if has is built inside
-
-if( NOT ECLIB_FOUND )
-
-    # find external eclib
-
-    set( _ENV_ECLIB_PATH "$ENV{ECLIB_PATH}" )
-    if( NOT DEFINED ECLIB_PATH AND _ENV_ECLIB_PATH )
-        set( ECLIB_PATH ${_ENV_ECLIB_PATH} )
-    endif()
-
-    if( DEFINED ECLIB_PATH )
-        find_path(ECLIB_INCLUDE_DIR NAMES eclib_version.h PATHS ${ECLIB_PATH} ${ECLIB_PATH}/include PATH_SUFFIXES eclib  NO_DEFAULT_PATH)
-        find_library(ECLIB_LIBRARY  NAMES Ec              PATHS ${ECLIB_PATH} ${ECLIB_PATH}/lib     PATH_SUFFIXES eclib  NO_DEFAULT_PATH)
-    endif()
-    
-    find_path(ECLIB_INCLUDE_DIR NAMES eclib_version.h PATH_SUFFIXES eclib )
-    find_library( ECLIB_LIBRARY NAMES Ec              PATH_SUFFIXES eclib )
-
-    include(FindPackageHandleStandardArgs)
-    
-    # handle the QUIETLY and REQUIRED arguments and set ECLIB_FOUND to TRUE
-    # if all listed variables are TRUE
-    find_package_handle_standard_args(ECLIB  DEFAULT_MSG
-                                      ECLIB_LIBRARY ECLIB_INCLUDE_DIR )
-    
-    mark_as_advanced(ECLIB_INCLUDE_DIR ECLIB_LIBRARY )
-
-    set( ECLIB_LIBRARIES    ${ECLIB_LIBRARY} )
-    set( ECLIB_INCLUDE_DIRS ${ECLIB_INCLUDE_DIR} )
-
-    debug_var( ECLIB_LIBRARIES )
-    debug_var( ECLIB_INCLUDE_DIRS )
-
-endif()
diff --git a/cmake/FindEcregrid.cmake b/cmake/FindEcregrid.cmake
deleted file mode 100644
index 3ddf732..0000000
--- a/cmake/FindEcregrid.cmake
+++ /dev/null
@@ -1,48 +0,0 @@
-# (C) Copyright 1996-2014 ECMWF.
-#
-# This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
-# In applying this licence, ECMWF does not waive the privileges and immunities
-# granted to it by virtue of its status as an intergovernmental organisation nor
-# does it submit to any jurisdiction.
-
-# - Try to find ECREGRID
-# Once done this will define
-#  ECREGRID_FOUND - System has ECREGRID
-#  ECREGRID_INCLUDE_DIRS - The ECREGRID include directories
-#  ECREGRID_LIBRARIES - The libraries needed to use ECREGRID
-#  ECREGRID_DEFINITIONS - Compiler switches required for using ECREGRID
-
-option( WITH_ECREGRID "try to find scin installation" ON )
-
-# skip if ECREGRID is already found or if has is built inside
-
-if( NOT ECREGRID_FOUND AND WITH_ECREGRID )
-
-    if( NOT DEFINED ECREGRID_PATH AND NOT "$ENV{ECREGRID_PATH}" STREQUAL "" )
-        list( APPEND ECREGRID_PATH "$ENV{ECREGRID_PATH}" )
-    endif()
-
-    if( DEFINED ECREGRID_PATH )
-        find_path(ECREGRID_INCLUDE_DIR NAMES scin_api.h PATHS ${ECREGRID_PATH} ${ECREGRID_PATH}/include PATH_SUFFIXES scin_api  NO_DEFAULT_PATH )
-        find_library(ECREGRID_LIBRARY  NAMES scin       PATHS ${ECREGRID_PATH} ${ECREGRID_PATH}/lib     PATH_SUFFIXES scin      NO_DEFAULT_PATH )
-    endif()
-    
-    find_path(ECREGRID_INCLUDE_DIR NAMES scin_api.h PATH_SUFFIXES scin_api )
-    find_library( ECREGRID_LIBRARY NAMES scin       PATH_SUFFIXES scin     )
-    
-    include(FindPackageHandleStandardArgs)
-    
-    # handle the QUIETLY and REQUIRED arguments and set ECREGRID_FOUND to TRUE
-    # if all listed variables are TRUE
-    find_package_handle_standard_args(Scin  DEFAULT_MSG
-                                      ECREGRID_LIBRARY ECREGRID_INCLUDE_DIR)
-
-    if( ECREGRID_FOUND )
-        set( ECREGRID_LIBRARIES    ${ECREGRID_LIBRARY} )
-        set( ECREGRID_INCLUDE_DIRS ${ECREGRID_INCLUDE_DIR} )
-    endif()
-    
-    mark_as_advanced(ECREGRID_INCLUDE_DIR ECREGRID_LIBRARY )
-    
-endif()
diff --git a/cmake/FindLibIFort.cmake b/cmake/FindLibIFort.cmake
new file mode 100644
index 0000000..e1d82ee
--- /dev/null
+++ b/cmake/FindLibIFort.cmake
@@ -0,0 +1,47 @@
+# © Copyright 1996-2015 ECMWF.
+# 
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
+# In applying this licence, ECMWF does not waive the privileges and immunities 
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# date:   July 2015
+# author: Florian Rathgeber
+
+###############################################################################
+
+# - Try to find Intel Fortran (ifort) runtime libraries libifcore and libifport
+# Once done this will define
+#
+#  LIBIFORT_FOUND   - system has Intel Fortran (ifort) runtime libraries
+#  IFORT_LIBRARIES  - the Intel Fortran (ifort) runtime libraries
+#
+# The following paths will be searched with priority if set in CMake or env
+#
+#  INTEL_PATH       - prefix path of the Intel installation
+#
+# Otherwise the libraries are assumed to be on LIBRARY_PATH or LD_LIBRARY_PATH
+
+# FIXME: might need to add further libraries in future, see
+# http://nf.nci.org.au/facilities/software/Compilers/Intel8/doc/f_ug1/files_32.htm
+
+# Search with priority for INTEL_PATH if given as CMake or env var
+find_library( IFORT_LIB_CORE ifcore PATHS ${INTEL_PATH} ENV INTEL_PATH
+              PATH_SUFFIXES lib/intel64 compiler/lib/intel64 NO_DEFAULT_PATH )
+find_library( IFORT_LIB_PORT ifport PATHS ${INTEL_PATH} ENV INTEL_PATH
+              PATH_SUFFIXES lib/intel64 compiler/lib/intel64 NO_DEFAULT_PATH )
+
+# Otherwise, search LIBRARY_PATH and LD_LIBRARY_PATH
+find_library( IFORT_LIB_CORE ifcore PATHS ENV LIBRARY_PATH LD_LIBRARY_PATH )
+find_library( IFORT_LIB_PORT ifport PATHS ENV LIBRARY_PATH LD_LIBRARY_PATH )
+
+mark_as_advanced( IFORT_LIB_CORE IFORT_LIB_PORT )
+
+if( IFORT_LIB_CORE AND IFORT_LIB_PORT )
+  set( IFORT_LIBRARIES ${IFORT_LIB_CORE} ${IFORT_LIB_PORT} )
+endif()
+
+include(FindPackageHandleStandardArgs)
+
+find_package_handle_standard_args( LIBIFORT DEFAULT_MSG IFORT_LIBRARIES )
diff --git a/cmake/FindMKL.cmake b/cmake/FindMKL.cmake
new file mode 100644
index 0000000..fe182a4
--- /dev/null
+++ b/cmake/FindMKL.cmake
@@ -0,0 +1,77 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# - Try to find MKL
+# Once done this will define
+#
+#  MKL_FOUND         - system has Intel MKL
+#  MKL_INCLUDE_DIRS  - the MKL include directories
+#  MKL_LIBRARIES     - link these to use MKL
+#
+# The following paths will be searched with priority if set in CMake or env
+#
+#  MKL_PATH          - root directory of the MKL installation
+#  MKL_ROOT          - root directory of the MKL installation
+
+option( MKL_PARALLEL "if mkl shoudl be parallel" OFF )
+
+if( MKL_PARALLEL )
+
+  set( __mkl_lib_par  MKL_LIB_INTEL_THREAD )
+  set( __mkl_lib_name mkl_intel_thread )
+
+  find_package(Threads)
+
+else()
+
+  set( __mkl_lib_par MKL_LIB_SEQUENTIAL )
+  set( __mkl_lib_name mkl_sequential )
+
+endif()
+
+# Search with priority for MKL_ROOT and MKL_PATH if set in CMake or env
+find_path(MKL_INCLUDE_DIR mkl.h
+          PATHS ${MKL_PATH} ${MKL_ROOT} ENV MKL_PATH MKL_ROOT
+          PATH_SUFFIXES include NO_DEFAULT_PATH)
+find_path(MKL_INCLUDE_DIR mkl.h
+          PATH_SUFFIXES include)
+
+if( MKL_INCLUDE_DIR ) # use include dir to find libs
+
+  set( MKL_INCLUDE_DIRS ${MKL_INCLUDE_DIR} )
+
+  if( CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" )
+    get_filename_component( MKL_LIB_PATH ${MKL_INCLUDE_DIR}/../lib/intel64 ABSOLUTE )
+    set( __libsfx _lp64 )
+  else()
+    get_filename_component( MKL_LIB_PATH ${MKL_INCLUDE_DIR}/../lib/ia32 ABSOLUTE )
+    set( __libsfx "" )
+  endif()
+
+  message( STATUS "ICC_LIB_PATH ${ICC_LIB_PATH}" )
+
+  find_library( MKL_LIB_INTEL         NAMES mkl_intel${__libsfx} PATHS ${MKL_LIB_PATH} )
+  find_library( ${__mkl_lib_par}      NAMES ${__mkl_lib_name} PATHS ${MKL_LIB_PATH} )
+  find_library( MKL_LIB_CORE          NAMES mkl_core PATHS ${MKL_LIB_PATH} )
+
+  if( MKL_PARALLEL )
+    find_library( MKL_LIB_IOMP5  NAMES iomp5 PATHS ${MKL_LIB_PATH} )
+  endif()
+
+  if( MKL_LIB_INTEL AND ${__mkl_lib_par} AND MKL_LIB_CORE )
+    set( MKL_LIBRARIES ${MKL_LIB_INTEL} ${${__mkl_lib_par}} ${MKL_LIB_CORE} ${MKL_LIB_IOMP5} ${CMAKE_THREAD_LIBS_INIT} )
+  endif()
+
+endif()
+
+include(FindPackageHandleStandardArgs)
+
+find_package_handle_standard_args( MKL DEFAULT_MSG
+                                   MKL_LIBRARIES MKL_INCLUDE_DIRS )
+
+mark_as_advanced( MKL_INCLUDE_DIR MKL_LIB_LAPACK MKL_LIB_INTEL MKL_LIB_SEQUENTIAL MKL_LIB_CORE )
diff --git a/cmake/FindNetCDF.cmake b/cmake/FindNetCDF.cmake
index 99ead8d..b214d27 100644
--- a/cmake/FindNetCDF.cmake
+++ b/cmake/FindNetCDF.cmake
@@ -23,7 +23,7 @@
 
 # default is netcdf4
 if( NetCDF_FIND_VERSION STREQUAL "3" )
-    set( PREFER_NETCDF3 1 )
+  set( PREFER_NETCDF3 1 )
 endif()
 
 if( NOT PREFER_NETCDF3 )
@@ -40,87 +40,88 @@ set( NETCDF_FIND_COMPONENTS ${NetCDF_FIND_COMPONENTS} )
 list( APPEND NETCDF_FIND_COMPONENTS C )
 
 if( NETCDF_CXX )
-    list( APPEND NETCDF_FIND_COMPONENTS CXX )
+  ecbuild_debug( "FindNetCDF: also looking for C++ libraries" )
+  list( APPEND NETCDF_FIND_COMPONENTS CXX )
 endif()
 
 if( NETCDF_Fortran OR NETCDF_FORTRAN OR NETCDF_F90 )
-    list( APPEND NETCDF_FIND_COMPONENTS FORTRAN F90 )
+  ecbuild_debug( "FindNetCDF: also looking for Fortran libraries" )
+  list( APPEND NETCDF_FIND_COMPONENTS FORTRAN F90 )
 endif()
 
 list(FIND NETCDF_FIND_COMPONENTS "FORTRAN" _index)
 if(${_index} GREATER -1)
-    list( APPEND NETCDF_FIND_COMPONENTS F90 )
+  list( APPEND NETCDF_FIND_COMPONENTS F90 )
 endif()
 
 list (FIND NETCDF_FIND_COMPONENTS "F90" _index)
 if(${_index} GREATER -1)
-    list( APPEND NETCDF_FIND_COMPONENTS FORTRAN )
+  list( APPEND NETCDF_FIND_COMPONENTS FORTRAN )
 endif()
 
 list(FIND NETCDF_FIND_COMPONENTS "Fortran" _index)
 if(${_index} GREATER -1)
-    list( REMOVE_ITEM NETCDF_FIND_COMPONENTS Fortran )
-    list( APPEND NETCDF_FIND_COMPONENTS FORTRAN F90 )
+  list( REMOVE_ITEM NETCDF_FIND_COMPONENTS Fortran )
+  list( APPEND NETCDF_FIND_COMPONENTS FORTRAN F90 )
 endif()
 
 list( REMOVE_DUPLICATES NETCDF_FIND_COMPONENTS )
+ecbuild_debug( "FindNetCDF: looking for components ${NETCDF_FIND_COMPONENTS}" )
 
 ### NetCDF4
 
 if( PREFER_NETCDF4 )
 
-    ## hdf5
+  ecbuild_debug( "FindNetCDF: looking for NetCDF4" )
 
-    ecbuild_add_extra_search_paths( hdf5 )
+  ## hdf5
 
-    # Note: Only the HDF5 C-library is required for NetCDF 
-    #       ( even for Fortan and CXX bindings)
-    find_package( HDF5 COMPONENTS C QUIET )
+  # Note: Only the HDF5 C-library is required for NetCDF 
+  #       ( even for Fortan and CXX bindings)
+  find_package( HDF5 COMPONENTS C QUIET )
 
-    ## netcdf4
+  ## netcdf4
 
-    # CONFIGURE the NETCDF_FIND_COMPONENTS variable
+  # CONFIGURE the NETCDF_FIND_COMPONENTS variable
 
-    # Find NetCDF4
+  # Find NetCDF4
 
-    ecbuild_add_extra_search_paths( netcdf4 )
+  # message( "NETCDF CMAKE_PREFIX_PATH = [${CMAKE_PREFIX_PATH}]")
+  # debug_var( NETCDF_ROOT )
+  # debug_var( NETCDF_FIND_COMPONENTS )
+  # debug_var( NETCDF_FIND_QUIETLY )
+  # debug_var( NETCDF_FIND_REQUIRED )
+  find_package( NetCDF4 COMPONENTS ${NETCDF_FIND_COMPONENTS} )
+  # debug_var( NETCDF4_FOUND )
+  # debug_var( NETCDF_FOUND )
+  # debug_var( NETCDF_LIBRARIES )
+  # debug_var( NETCDF_INCLUDE_DIRS )
 
-    # message( "NETCDF CMAKE_PREFIX_PATH = [${CMAKE_PREFIX_PATH}]")
-    # debug_var( NETCDF_ROOT )
-    # debug_var( NETCDF_FIND_COMPONENTS )
-    # debug_var( NETCDF_FIND_QUIETLY )
-    # debug_var( NETCDF_FIND_REQUIRED )
-    find_package( NetCDF4 )
-    # debug_var( NETCDF4_FOUND )
-    # debug_var( NETCDF_FOUND )
-    # debug_var( NETCDF_LIBRARIES )
-    # debug_var( NETCDF_INCLUDE_DIRS )
+  list( APPEND NETCDF_Fortran_LIBRARIES ${NETCDF_FORTRAN_LIBRARIES} ${NETCDF_F90_LIBRARIES} )
+  if( NETCDF_Fortran_LIBRARIES )
+    list( REMOVE_DUPLICATES NETCDF_Fortran_LIBRARIES )
+  endif()
 
-    list( APPEND NETCDF_Fortran_LIBRARIES ${NETCDF_FORTRAN_LIBRARIES} ${NETCDF_F90_LIBRARIES} )
-    if( NETCDF_Fortran_LIBRARIES )
-      list( REMOVE_DUPLICATES NETCDF_Fortran_LIBRARIES )
-    endif()
+  # debug_var( NETCDF_Fortran_LIBRARIES )
+  # debug_var( NETCDF_C_LIBRARIES )
+  # debug_var( NETCDF_CXX_LIBRARIES )
 
-    # debug_var( NETCDF_Fortran_LIBRARIES )
-    # debug_var( NETCDF_C_LIBRARIES )
-    # debug_var( NETCDF_CXX_LIBRARIES )
 
+  set_package_properties( NetCDF4 PROPERTIES TYPE RECOMMENDED PURPOSE "support for NetCDF4 file format" )
 
-	set_package_properties( NetCDF4 PROPERTIES TYPE RECOMMENDED PURPOSE "support for NetCDF4 file format" )
+  if( NETCDF_FOUND AND HDF5_FOUND )
+    # list( APPEND NETCDF_DEFINITIONS  ${HDF5_DEFINITIONS} )
+    list( APPEND NETCDF_LIBRARIES    ${HDF5_HL_LIBRARIES} ${HDF5_LIBRARIES}  )
+    list( APPEND NETCDF_INCLUDE_DIRS ${HDF5_INCLUDE_DIRS} )
+  endif()
 
-    if( NETCDF_FOUND AND HDF5_FOUND )
-        # list( APPEND NETCDF_DEFINITIONS  ${HDF5_DEFINITIONS} )
-        list( APPEND NETCDF_LIBRARIES    ${HDF5_HL_LIBRARIES} ${HDF5_LIBRARIES}  )
-        list( APPEND NETCDF_INCLUDE_DIRS ${HDF5_INCLUDE_DIRS} )
-    endif()
-
-    #debug_var( NETCDF_FOUND )
-    #debug_var( NETCDF_LIBRARIES )
-    #debug_var( NETCDF_INCLUDE_DIRS )
-    #debug_var( HDF5_FOUND )
-    #debug_var( HDF5_INCLUDE_DIRS )
-    #debug_var( HDF5_HL_LIBRARIES )
-    #debug_var( HDF5_LIBRARIES )
+  #debug_var( NETCDF_FOUND )
+  #debug_var( NETCDF_LIBRARIES )
+  #debug_var( NETCDF_INCLUDE_DIRS )
+  #debug_var( HDF5_FOUND )
+  #debug_var( HDF5_INCLUDE_DIRS )
+  #debug_var( HDF5_HL_LIBRARIES )
+  #debug_var( HDF5_LIBRARIES )
 
 endif()
 
@@ -128,40 +129,36 @@ endif()
 
 if( PREFER_NETCDF3 )
 
-    # message( "LOOKING FOR NETCDF3" )
-
-    # debug_var( NetCDF_FIND_COMPONENTS )
-    # debug_var( NetCDF_FIND_QUIETLY )
-    # debug_var( NetCDF_FIND_REQUIRED )
-
-	list(FIND NetCDF_FIND_COMPONENTS "CXX" _index)
-	if(${_index} GREATER -1)
-        set( NETCDF_CXX 1 )
-    endif()
+  ecbuild_debug( "FindNetCDF: looking for NetCDF3" )
 
-	list(FIND NetCDF_FIND_COMPONENTS "Fortran" _index)
-	if(${_index} GREATER -1)
-        set( NETCDF_Fortran 1 )
-    endif()
+  # debug_var( NetCDF_FIND_COMPONENTS )
+  # debug_var( NetCDF_FIND_QUIETLY )
+  # debug_var( NetCDF_FIND_REQUIRED )
 
-	list(FIND NetCDF_FIND_COMPONENTS "FORTRAN" _index)
-	if(${_index} GREATER -1)
-        set( NETCDF_Fortran 1 )
-    endif()
+  list(FIND NetCDF_FIND_COMPONENTS "CXX" _index)
+  if(${_index} GREATER -1)
+    set( NETCDF_CXX 1 )
+  endif()
 
-	list(FIND NetCDF_FIND_COMPONENTS "F90" _index)
-	if(${_index} GREATER -1)
-        set( NETCDF_Fortran 1 )
-    endif()
+  list(FIND NetCDF_FIND_COMPONENTS "Fortran" _index)
+  if(${_index} GREATER -1)
+    set( NETCDF_Fortran 1 )
+  endif()
 
-    ecbuild_add_extra_search_paths( netcdf3 )
+  list(FIND NetCDF_FIND_COMPONENTS "FORTRAN" _index)
+  if(${_index} GREATER -1)
+    set( NETCDF_Fortran 1 )
+  endif()
 
-	ecbuild_add_extra_search_paths( netcdf ) # fallback to netcdf search paths
+  list(FIND NetCDF_FIND_COMPONENTS "F90" _index)
+  if(${_index} GREATER -1)
+    set( NETCDF_Fortran 1 )
+  endif()
 
-    message( "NETCDF CMAKE_PREFIX_PATH = ${CMAKE_PREFIX_PATH}" )
+  #message( "NETCDF CMAKE_PREFIX_PATH = ${CMAKE_PREFIX_PATH}" )
 
-    find_package( NetCDF3 )
+  find_package( NetCDF3 COMPONENTS ${NETCDF_FIND_COMPONENTS} )
 
-	set_package_properties( NetCDF3 PROPERTIES TYPE RECOMMENDED PURPOSE "support for NetCDF3 file format" )
+  set_package_properties( NetCDF3 PROPERTIES TYPE RECOMMENDED PURPOSE "support for NetCDF3 file format" )
 
 endif()
diff --git a/cmake/FindNetCDF3.cmake b/cmake/FindNetCDF3.cmake
index 079e55e..20a5396 100644
--- a/cmake/FindNetCDF3.cmake
+++ b/cmake/FindNetCDF3.cmake
@@ -9,10 +9,12 @@
 # Try to find NetCDF
 #
 # Input:
-#  * NETCDF_PATH - user defined path where to search for the library first
-#  * NETCDF_DIR  - user defined path where to search for the library first
-#  * NETCDF_CXX  - if to search also for netcdf_c++ wrapper library
-#  * NETCDF_Fortran  - if to search also for netcdff wrapper library
+#  * NETCDF_PATH     - user defined path where to search for the library first
+#                      (CMake or environment variable)
+#  * NETCDF_DIR      - user defined path where to search for the library first
+#                      (CMake or environment variable)
+#  * NETCDF_CXX      - search also for netcdf_c++ wrapper library
+#  * NETCDF_Fortran  - search also for netcdff wrapper library
 #
 # Output:
 #  NETCDF_FOUND - System has NetCDF
@@ -21,14 +23,6 @@
 
 ### TODO: generalize this into a macro for all ecbuild
 
-if( DEFINED $ENV{NETCDF_PATH} )
-    list( APPEND CMAKE_PREFIX_PATH  $ENV{NETCDF_PATH} )
-endif()
-
-if( DEFINED $ENV{NETCDF_DIR} )
-    list( APPEND CMAKE_PREFIX_PATH  $ENV{NETCDF_DIR} )
-endif()
-
 if( DEFINED NETCDF_PATH )
     list( APPEND _netcdf_incs ${NETCDF_PATH} ${NETCDF_PATH}/include )
     list( APPEND _netcdf_libs ${NETCDF_PATH} ${NETCDF_PATH}/lib )
@@ -39,33 +33,20 @@ if( DEFINED NETCDF_DIR )
     list( APPEND _netcdf_libs ${NETCDF_DIR} ${NETCDF_DIR}/lib )
 endif()
 
-foreach( _h /usr/local/apps/netcdf )
-
-	if( EXISTS ${_h} )
-	
-        list( APPEND _netcdf_incs  ${_h}/include ${_h}/current/include ${_h}/new/include ${_h}/stable/include )
-        list( APPEND _netcdf_libs  ${_h}/lib ${_h}/current/lib ${_h}/new/lib ${_h}/stable/lib )
-
-		file(GLOB _hd ${_h}/*)
-        foreach( d ${_hd} )
-            if( IS_DIRECTORY ${d} )
-                list( APPEND _netcdf_incs ${d}/include ${d}/LP64/include )
-                list( APPEND _netcdf_libs ${d}/lib ${d}/LP64/lib )
-            endif()
-        endforeach()
-    endif()
-
-endforeach() 
+# Honour environment variables NETCDF_DIR, NETCDF_PATH
+list( APPEND _netcdf_incs ENV NETCDF_DIR ENV NETCDF_PATH )
+list( APPEND _netcdf_libs ENV NETCDF_DIR ENV NETCDF_PATH )
 
 ###
 
-set( _ncdf_sfx netcdf LP64 )
+set( _inc_sfx netcdf include )
+set( _lib_sfx netcdf lib64 lib )
 
-find_path( NETCDF_INCLUDE_DIR  netcdf.h  PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} NO_DEFAULT_PATH )
-find_path( NETCDF_INCLUDE_DIR  netcdf.h  PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} )
+find_path( NETCDF_INCLUDE_DIR  netcdf.h  PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} NO_DEFAULT_PATH )
+find_path( NETCDF_INCLUDE_DIR  netcdf.h  PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} )
 
-find_library( NETCDF_LIBRARY  netcdf  PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx}  NO_DEFAULT_PATH )
-find_library( NETCDF_LIBRARY  netcdf  PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx}  )
+find_library( NETCDF_LIBRARY  netcdf  PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx}  NO_DEFAULT_PATH )
+find_library( NETCDF_LIBRARY  netcdf  PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx}  )
 
 set( NETCDF_LIBRARIES    ${NETCDF_LIBRARY} )
 set( NETCDF_INCLUDE_DIRS ${NETCDF_INCLUDE_DIR} )
@@ -76,13 +57,13 @@ list( APPEND NETCDF_REQUIRED_VARS NETCDF_LIBRARY NETCDF_INCLUDE_DIR )
 
 if( NETCDF_CXX )
 
-    find_path( NETCDF_CXX_INCLUDE_DIR netcdfcpp.h PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} NO_DEFAULT_PATH)
-    find_path( NETCDF_CXX_INCLUDE_DIR netcdfcpp.h PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} )
+    find_path( NETCDF_CXX_INCLUDE_DIR netcdfcpp.h PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} NO_DEFAULT_PATH)
+    find_path( NETCDF_CXX_INCLUDE_DIR netcdfcpp.h PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} )
 
     set( _ncdf_cxx netcdf_c++ netcdf_c++ netcdf_c++4 )
 
-    find_library( NETCDF_CXX_LIBRARY NAMES ${_ncdf_cxx} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx} NO_DEFAULT_PATH )
-    find_library( NETCDF_CXX_LIBRARY NAMES ${_ncdf_cxx} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx} )
+    find_library( NETCDF_CXX_LIBRARY NAMES ${_ncdf_cxx} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx} NO_DEFAULT_PATH )
+    find_library( NETCDF_CXX_LIBRARY NAMES ${_ncdf_cxx} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx} )
 
     list( APPEND NETCDF_INCLUDE_DIRS ${NETCDF_CXX_INCLUDE_DIR} )
     list( APPEND NETCDF_LIBRARIES    ${NETCDF_CXX_LIBRARY} )
@@ -95,13 +76,13 @@ endif()
 
 if( NETCDF_Fortran )
 
-    find_path( NETCDF_Fortran_INCLUDE_DIR netcdf.mod PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} NO_DEFAULT_PATH)
-    find_path( NETCDF_Fortran_INCLUDE_DIR netcdf.mod PATHS ${_netcdf_incs} PATH_SUFFIXES ${_ncdf_sfx} )
+    find_path( NETCDF_Fortran_INCLUDE_DIR netcdf.mod PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} NO_DEFAULT_PATH)
+    find_path( NETCDF_Fortran_INCLUDE_DIR netcdf.mod PATHS ${_netcdf_incs} PATH_SUFFIXES ${_inc_sfx} )
 
     set( _ncdf_fortran netcdff )
 
-    find_library( NETCDF_Fortran_LIBRARY NAMES ${_ncdf_fortran} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx} NO_DEFAULT_PATH )
-    find_library( NETCDF_Fortran_LIBRARY NAMES ${_ncdf_fortran} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_ncdf_sfx} )
+    find_library( NETCDF_Fortran_LIBRARY NAMES ${_ncdf_fortran} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx} NO_DEFAULT_PATH )
+    find_library( NETCDF_Fortran_LIBRARY NAMES ${_ncdf_fortran} PATHS ${_netcdf_libs} PATH_SUFFIXES ${_lib_sfx} )
 
     list( APPEND NETCDF_INCLUDE_DIRS ${NETCDF_Fortran_INCLUDE_DIR} )
     list( APPEND NETCDF_LIBRARIES    ${NETCDF_Fortran_LIBRARY} )
diff --git a/cmake/FindOpenCL.cmake b/cmake/FindOpenCL.cmake
new file mode 100644
index 0000000..e4e9556
--- /dev/null
+++ b/cmake/FindOpenCL.cmake
@@ -0,0 +1,67 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# - Try to find OpenCL
+# Once done this will define
+#
+#  OPENCL_FOUND           - system has OpenCL
+#  OPENCL_INCLUDE_DIRS    - the OpenCL include directory
+#  OPENCL_LIBRARIES       - link these to use OpenCL
+#
+# The following paths will be searched with priority if set in CMake or env
+#
+#  OPENCL_ROOT            - root folder of the OpenCL installation
+#  CUDA_TOOLKIT_ROOT_DIR  - root folder of the CUDA installation (ships OpenCL)
+#  CUDA_ROOT              - root folder of the CUDA installation (ships OpenCL)
+
+if(UNIX)
+
+  if(APPLE)
+
+    # Search with priority for OPENCL_ROOT if given as CMake or env var
+    find_path(OPENCL_INCLUDE_DIRS OpenCL/cl.h
+              PATHS ${OPENCL_ROOT} ENV OPENCL_ROOT
+              PATH_SUFFIXES include NO_DEFAULT_PATH)
+    find_path(OPENCL_INCLUDE_DIRS OpenCL/cl.h
+              PATH_SUFFIXES include )
+
+    # Search with priority for OPENCL_ROOT if given as CMake or env var
+    find_library(OPENCL_LIBRARIES OpenCL
+                 PATHS ${OPENCL_ROOT} ENV OPENCL_ROOT
+                 PATH_SUFFIXES lib NO_DEFAULT_PATH)
+    find_library(OPENCL_LIBRARIES OpenCL
+                 PATH_SUFFIXES lib )
+
+  else()
+
+    # Search with priority for OPENCL_ROOT if given as CMake or env var
+    find_path(OPENCL_INCLUDE_DIRS NAMES CL/cl.h CL/opencl.h
+              PATHS ${OPENCL_ROOT} ENV OPENCL_ROOT
+              PATH_SUFFIXES include NO_DEFAULT_PATH)
+    find_path(OPENCL_INCLUDE_DIRS NAMES CL/cl.h CL/opencl.h
+              PATHS ${CUDA_TOOLKIT_ROOT_DIR} ${CUDA_ROOT} /usr/local/cuda
+              PATH_SUFFIXES include )
+
+    # Search with priority for OPENCL_ROOT if given as CMake or env var
+    find_library(OPENCL_LIBRARIES OpenCL
+                 PATHS ${OPENCL_ROOT} ENV OPENCL_ROOT
+                 PATH_SUFFIXES lib64 lib NO_DEFAULT_PATH)
+    find_library(OPENCL_LIBRARIES OpenCL
+                 PATHS ${CUDA_TOOLKIT_ROOT_DIR} ${CUDA_ROOT} /usr/local/cuda
+                 PATH_SUFFIXES lib64 lib )
+
+  endif()
+
+endif()
+
+include(FindPackageHandleStandardArgs)
+
+find_package_handle_standard_args( OPENCL DEFAULT_MSG
+                                   OPENCL_LIBRARIES OPENCL_INCLUDE_DIRS )
+
+mark_as_advanced( OPENCL_INCLUDE_DIRS OPENCL_LIBRARIES )
diff --git a/cmake/FindOpenJPEG.cmake b/cmake/FindOpenJPEG.cmake
index 3e36954..d692f35 100644
--- a/cmake/FindOpenJPEG.cmake
+++ b/cmake/FindOpenJPEG.cmake
@@ -16,12 +16,11 @@
 #  OPENJPEG_LIBRARY, where to find the OpenJPEG library.
 #  OPENJPEG_INCLUDE_DIR, where to find the openjpeg.h header
 
-ecbuild_add_extra_search_paths( openjpg )
-
 IF( NOT DEFINED OPENJPEG_PATH AND NOT "$ENV{OPENJPEG_PATH}" STREQUAL "" )
   SET( OPENJPEG_PATH "$ENV{OPENJPEG_PATH}" )
 ENDIF()
 
+# TODO: This only works for OpenJPEG v1.x.y and not for v2 which has a different API, library name etc
 if( DEFINED OPENJPEG_PATH )
         find_path(OPENJPEG_INCLUDE_DIR openjpeg.h PATHS ${OPENJPEG_PATH}/include PATH_SUFFIXES openjpeg  NO_DEFAULT_PATH)
         find_library(OPENJPEG_LIBRARY  openjpeg   PATHS ${OPENJPEG_PATH}/lib     PATH_SUFFIXES openjpeg  NO_DEFAULT_PATH)
diff --git a/cmake/FindPango.cmake b/cmake/FindPango.cmake
index 81b55c0..0105d7f 100644
--- a/cmake/FindPango.cmake
+++ b/cmake/FindPango.cmake
@@ -13,8 +13,6 @@
 #   PANGO_LIBRARIES
 #   PANGO_INCLUDE_DIRS
 
-ecbuild_add_extra_search_paths( pango )
-
 find_package(PkgConfig)
 
 pkg_check_modules(PC_LIBPANGO QUIET pango)
diff --git a/cmake/FindPangoCairo.cmake b/cmake/FindPangoCairo.cmake
index 4fb1fd2..611e269 100644
--- a/cmake/FindPangoCairo.cmake
+++ b/cmake/FindPangoCairo.cmake
@@ -1,8 +1,8 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
-# In applying this licence, ECMWF does not waive the privileges and immunities 
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
@@ -21,15 +21,18 @@ pkg_check_modules(PC_LIBPANGOCAIRO QUIET pangocairo)
 #debug_var( PC_LIBPANGOCAIRO_FOUND )
 #debug_var( PC_LIBPANGOCAIRO_VERSION )
 #debug_var( PC_LIBPANGOCAIRO_LIBRARIES )
+#debug_var( PC_LIBPANGOCAIRO_LDFLAGS )
+#debug_var( PC_LIBPANGOCAIRO_LDFLAGS_OTHER )
 #debug_var( PC_LIBPANGOCAIRO_INCLUDE_DIRS )
 
-
 if(PC_LIBPANGOCAIRO_FOUND)
+
     include(FindPackageHandleStandardArgs)
     find_package_handle_standard_args( pangocairo DEFAULT_MSG PC_LIBPANGOCAIRO_LIBRARIES PC_LIBPANGOCAIRO_INCLUDE_DIRS )
     set( PANGOCAIRO_VERSION ${PC_LIBPANGOCAIRO_VERSION} )
-    set( PANGOCAIRO_LIBRARIES ${PC_LIBPANGOCAIRO_LIBRARIES} )
+    set( PANGOCAIRO_LIBRARIES "${PC_LIBPANGOCAIRO_LDFLAGS} ${PC_LIBPANGOCAIRO_LDFLAGS_OTHER}" )
     set( PANGOCAIRO_INCLUDE_DIRS ${PC_LIBPANGOCAIRO_INCLUDE_DIRS} )
+
 else()
 
     # this is to get magics compiling on mac with macbrew
diff --git a/cmake/FindProj4.cmake b/cmake/FindProj4.cmake
index 6181ed0..6774b6e 100644
--- a/cmake/FindProj4.cmake
+++ b/cmake/FindProj4.cmake
@@ -7,12 +7,14 @@
 #
 # Define PROJ4_MIN_VERSION for which version desired.
 
-if( NOT PROJ4_PATH AND NOT "$ENV{PROJ4_PATH}" STREQUAL "" )
-    set( PROJ4_PATH "$ENV{PROJ4_PATH}" )
+if( NOT PROJ4_PATH )
+    if ( NOT "$ENV{PROJ4_PATH}" STREQUAL "" )
+        set( PROJ4_PATH "$ENV{PROJ4_PATH}" )
+    elseif ( NOT "$ENV{PROJ4_DIR}" STREQUAL "" )
+        set( PROJ4_PATH "$ENV{PROJ4_DIR}" )
+    endif()
 endif()
 
-ecbuild_add_extra_search_paths( proj4 )
-
 if( NOT PROJ4_PATH )
 
     include(FindPkgConfig)
diff --git a/cmake/FindSZip.cmake b/cmake/FindSZip.cmake
index 533df50..d7d6026 100644
--- a/cmake/FindSZip.cmake
+++ b/cmake/FindSZip.cmake
@@ -12,8 +12,6 @@
 #  SZIP_INCLUDE_DIRS - The SZip include directories
 #  SZIP_LIBRARIES - The libraries needed to use SZip
 
-ecbuild_add_extra_search_paths( szip )
-
 if( DEFINED SZIP_PATH )
     find_path( SZIP_INCLUDE_DIR szlib.h       PATHS ${SZIP_PATH}/include PATH_SUFFIXES szip NO_DEFAULT_PATH )
     find_library( SZIP_LIBRARY  NAMES szip sz PATHS ${SZIP_PATH}/lib     PATH_SUFFIXES szip NO_DEFAULT_PATH )
diff --git a/cmake/FindScin.cmake b/cmake/FindScin.cmake
deleted file mode 100644
index 3ddf732..0000000
--- a/cmake/FindScin.cmake
+++ /dev/null
@@ -1,48 +0,0 @@
-# (C) Copyright 1996-2014 ECMWF.
-#
-# This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
-# In applying this licence, ECMWF does not waive the privileges and immunities
-# granted to it by virtue of its status as an intergovernmental organisation nor
-# does it submit to any jurisdiction.
-
-# - Try to find ECREGRID
-# Once done this will define
-#  ECREGRID_FOUND - System has ECREGRID
-#  ECREGRID_INCLUDE_DIRS - The ECREGRID include directories
-#  ECREGRID_LIBRARIES - The libraries needed to use ECREGRID
-#  ECREGRID_DEFINITIONS - Compiler switches required for using ECREGRID
-
-option( WITH_ECREGRID "try to find scin installation" ON )
-
-# skip if ECREGRID is already found or if has is built inside
-
-if( NOT ECREGRID_FOUND AND WITH_ECREGRID )
-
-    if( NOT DEFINED ECREGRID_PATH AND NOT "$ENV{ECREGRID_PATH}" STREQUAL "" )
-        list( APPEND ECREGRID_PATH "$ENV{ECREGRID_PATH}" )
-    endif()
-
-    if( DEFINED ECREGRID_PATH )
-        find_path(ECREGRID_INCLUDE_DIR NAMES scin_api.h PATHS ${ECREGRID_PATH} ${ECREGRID_PATH}/include PATH_SUFFIXES scin_api  NO_DEFAULT_PATH )
-        find_library(ECREGRID_LIBRARY  NAMES scin       PATHS ${ECREGRID_PATH} ${ECREGRID_PATH}/lib     PATH_SUFFIXES scin      NO_DEFAULT_PATH )
-    endif()
-    
-    find_path(ECREGRID_INCLUDE_DIR NAMES scin_api.h PATH_SUFFIXES scin_api )
-    find_library( ECREGRID_LIBRARY NAMES scin       PATH_SUFFIXES scin     )
-    
-    include(FindPackageHandleStandardArgs)
-    
-    # handle the QUIETLY and REQUIRED arguments and set ECREGRID_FOUND to TRUE
-    # if all listed variables are TRUE
-    find_package_handle_standard_args(Scin  DEFAULT_MSG
-                                      ECREGRID_LIBRARY ECREGRID_INCLUDE_DIR)
-
-    if( ECREGRID_FOUND )
-        set( ECREGRID_LIBRARIES    ${ECREGRID_LIBRARY} )
-        set( ECREGRID_INCLUDE_DIRS ${ECREGRID_INCLUDE_DIR} )
-    endif()
-    
-    mark_as_advanced(ECREGRID_INCLUDE_DIR ECREGRID_LIBRARY )
-    
-endif()
diff --git a/cmake/FindTrilinos.cmake b/cmake/FindTrilinos.cmake
index 717cca6..9cc6132 100644
--- a/cmake/FindTrilinos.cmake
+++ b/cmake/FindTrilinos.cmake
@@ -17,9 +17,6 @@
 
 # Try to find Trilinos using Trilinos recommendations
 
-
-ecbuild_add_extra_search_paths( trilinos )
-
 if( DEFINED $ENV{TRILINOS_PATH} )
     find_package(Trilinos PATHS $ENV{TRILINOS_PATH}/lib/cmake/Trilinos $ENV{TRILINOS_PATH}/include )
 endif()
diff --git a/cmake/FindViennaCL.cmake b/cmake/FindViennaCL.cmake
new file mode 100644
index 0000000..a1b1eb9
--- /dev/null
+++ b/cmake/FindViennaCL.cmake
@@ -0,0 +1,38 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# - Try to find ViennaCL
+# Once done this will define
+#
+#  VIENNACL_FOUND         - system has ViennaCL
+#  VIENNACL_INCLUDE_DIRS  - the ViennaCL include directories
+#
+# The following paths will be searched with priority if set in CMake or env
+#
+#  VIENNACL_PATH          - prefix path of the ViennaCL installation
+#
+# ViennaCL is header only, so there are no libraries to be found
+
+# Search with priority for VIENNACL_PATH if given as CMake or env var
+find_path(VIENNACL_INCLUDE_DIR viennacl/version.hpp
+          PATHS ${VIENNACL_PATH} ENV VIENNACL_PATH
+          PATH_SUFFIXES include NO_DEFAULT_PATH)
+
+find_path(VIENNACL_INCLUDE_DIR viennacl/version.hpp
+          PATH_SUFFIXES include )
+
+set( VIENNACL_INCLUDE_DIRS ${VIENNACL_INCLUDE_DIR} )
+
+include(FindPackageHandleStandardArgs)
+
+# handle the QUIETLY and REQUIRED arguments and set VIENNACL_FOUND to TRUE
+# if all listed variables are valid
+find_package_handle_standard_args(VIENNACL  DEFAULT_MSG
+                                  VIENNACL_INCLUDE_DIR)
+
+mark_as_advanced(VIENNACL_INCLUDE_DIRS)
diff --git a/cmake/Findgrib_api.cmake b/cmake/Findgrib_api.cmake
index 55a7b19..32a01e9 100644
--- a/cmake/Findgrib_api.cmake
+++ b/cmake/Findgrib_api.cmake
@@ -19,8 +19,6 @@ option( GRIB_API_JPG "use jpg with grib_api" ON )
 
 if( NOT grib_api_FOUND AND NOT NO_GRIB_API_BINARIES )
 
-    ecbuild_add_extra_search_paths( grib_api )
-
     if( GRIB_API_JPG ) # jpeg support
         
         find_package( JPEG     QUIET ) # grib_api might be a static .a library in which
diff --git a/cmake/Findodb_api.cmake b/cmake/Findodb_api.cmake
index c573d9b..5cd2a10 100644
--- a/cmake/Findodb_api.cmake
+++ b/cmake/Findodb_api.cmake
@@ -15,8 +15,6 @@
 
 if( NOT odb_api_FOUND )
 
-    ecbuild_add_extra_search_paths( odb_api )
-
     # find external odb_api
 
     if( NOT DEFINED ODB_API_PATH AND NOT "$ENV{ODB_API_PATH}" STREQUAL "" )
diff --git a/cmake/Findspot.cmake b/cmake/Findspot.cmake
index 6396ef0..1edb2cd 100644
--- a/cmake/Findspot.cmake
+++ b/cmake/Findspot.cmake
@@ -15,8 +15,6 @@
 
 if( NOT spot_FOUND )
 
-    ecbuild_add_extra_search_paths( spot )
-
     # find external odb_api
 
     if( NOT DEFINED SPOT_PATH AND NOT "$ENV{SPOT_PATH}" STREQUAL "" )
diff --git a/cmake/VERSION.cmake b/cmake/VERSION.cmake
index 40762d8..a07bd4a 100644
--- a/cmake/VERSION.cmake
+++ b/cmake/VERSION.cmake
@@ -1,7 +1,7 @@
 set( ECBUILD_MAJOR_VERSION "1" )
-set( ECBUILD_MINOR_VERSION "7" )
+set( ECBUILD_MINOR_VERSION "9" )
 set( ECBUILD_PATCH_VERSION "0" )
 
-set( ECBUILD_VERSION_STR  "1.7.0" )
+set( ECBUILD_VERSION_STR  "1.9.0" )
 
 set( ECBUILD_MACRO_VERSION "${ECBUILD_MAJOR_VERSION}.${ECBUILD_MINOR_VERSION}" )
diff --git a/cmake/contrib/FindEigen3.cmake b/cmake/contrib/FindEigen3.cmake
index 72d4a9d..9315294 100644
--- a/cmake/contrib/FindEigen3.cmake
+++ b/cmake/contrib/FindEigen3.cmake
@@ -15,8 +15,6 @@
 # Copyright (c) 2009 Benoit Jacob <jacob.benoit.1 at gmail.com>
 # Redistribution and use is allowed according to the terms of the 2-clause BSD license.
 
-ecbuild_add_extra_search_paths( eigen )
-
 if(NOT Eigen3_FIND_VERSION)
   if(NOT Eigen3_FIND_VERSION_MAJOR)
     set(Eigen3_FIND_VERSION_MAJOR 2)
@@ -76,7 +74,13 @@ else(EIGEN3_INCLUDE_DIR)
       ${EIGEN_PATH}/include
       ${EIGEN_DIR}/include
       ${EIGEN_ROOT}/include
-      PATH_SUFFIXES eigen3 eigen
+      ENV EIGEN3_PATH
+      ENV EIGEN3_DIR
+      ENV EIGEN3_ROOT
+      ENV EIGEN_PATH
+      ENV EIGEN_DIR
+      ENV EIGEN_ROOT
+      PATH_SUFFIXES eigen3 eigen include/eigen3 include/eigen
     )
 
   if(EIGEN3_INCLUDE_DIR)
diff --git a/cmake/contrib/FindFFTW.cmake b/cmake/contrib/FindFFTW.cmake
index 1ddaf4c..d76767b 100644
--- a/cmake/contrib/FindFFTW.cmake
+++ b/cmake/contrib/FindFFTW.cmake
@@ -12,27 +12,55 @@
 #   FFTW_USE_STATIC_LIBS    ... if true, only static libraries are found
 #   FFTW_ROOT               ... if set, the libraries are exclusively searched
 #                               under this path
+#   FFTW_DIR                ... equivalent to FFTW_ROOT
+#   FFTW_PATH               ... equivalent to FFTW_ROOT
 #   FFTW_LIBRARY            ... fftw library to use
 #   FFTW_INCLUDE_DIR        ... fftw include directory
 #
 
-#=======================#
-#
-#      From Eigen3
-#
-#========================
+#============================================#
+#                                            #
+#    From Eigen3, modified by W Deconinck    #
+#                                            #
+#============================================#
 
-#If environment variable FFTWDIR is specified, it has same effect as FFTW_ROOT
-if( NOT FFTW_ROOT AND ENV{FFTWDIR} )
+if( (NOT FFTW_ROOT) AND EXISTS $ENV{FFTW_ROOT} )
+  set( FFTW_ROOT ${FFTW_ROOT} )
+endif()
+if( NOT FFTW_ROOT AND $FFTW_DIR )
+  set( FFTW_ROOT ${FFTW_DIR} )
+endif()
+if( (NOT FFTW_ROOT) AND EXISTS $ENV{FFTW_DIR} )
+  set( FFTW_ROOT $ENV{FFTW_DIR} )
+endif()
+if( (NOT FFTW_ROOT) AND FFTWDIR )
+  set( FFTW_ROOT ${FFTWDIR} )
+endif()
+if( (NOT FFTW_ROOT) AND EXISTS $ENV{FFTWDIR} )
   set( FFTW_ROOT $ENV{FFTWDIR} )
 endif()
+if( (NOT FFTW_ROOT) AND FFTW_PATH )
+  set( FFTW_ROOT ${FFTW_PATH} )
+endif()
+if( (NOT FFTW_ROOT) AND EXISTS $ENV{FFTW_PATH})
+  set( FFTW_ROOT $ENV{FFTW_PATH} )
+endif()
+
+if( FFTW_ROOT ) # On cc[a|b|t] FFTW_DIR is set to the lib directory :(
+  get_filename_component(_dirname ${FFTW_ROOT} NAME)
+  if( _dirname MATCHES "lib" )
+    set( FFTW_ROOT "${FFTW_ROOT}/.." )
+  endif()
+endif()
 
-# Check if we can use PkgConfig
-find_package(PkgConfig)
+if( NOT FFTW_ROOT )
+  # Check if we can use PkgConfig
+  find_package(PkgConfig)
 
-#Determine from PKG
-if( PKG_CONFIG_FOUND AND NOT FFTW_ROOT )
-  pkg_check_modules( PKG_FFTW QUIET "fftw3" )
+  #Determine from PKG
+  if( PKG_CONFIG_FOUND AND NOT FFTW_ROOT )
+    pkg_check_modules( PKG_FFTW QUIET "fftw3" )
+  endif()
 endif()
 
 #Check whether to search static or dynamic libs
diff --git a/cmake/contrib/FindNetCDF4.cmake b/cmake/contrib/FindNetCDF4.cmake
index 33e7b36..adf232e 100644
--- a/cmake/contrib/FindNetCDF4.cmake
+++ b/cmake/contrib/FindNetCDF4.cmake
@@ -22,7 +22,7 @@
 # NETCDF_USE_STATIC_LIBRARIES variable is set before the call to find_package.
 #
 # To provide the module with a hint about where to find your NETCDF installation,
-# you can set the environment variable NETCDF_ROOT.  The Find module will then
+# set the environment variable NETCDF_ROOT or NETCDF_DIR. The Find module will then
 # look in this path when searching for NETCDF executables, paths, and libraries.
 #
 # In addition to finding the includes and libraries required to compile an NETCDF
@@ -90,7 +90,7 @@ endmacro()
 # try to find the NETCDF wrapper compilers
 find_program( NETCDF_CONFIG_EXECUTABLE
     NAMES nc-config
-    HINTS ENV NETCDF_ROOT
+    HINTS ENV NETCDF_ROOT ENV NETCDF_DIR ENV NETCDF4_DIR
     PATHS
     PATH_SUFFIXES bin Bin
     DOC "NETCDF CONFIG PROGRAM.  Used only to detect NETCDF compile flags." )
@@ -154,7 +154,7 @@ else()
     set( NETCDF_REQUIRED netcdf.h netcdfcpp.h netcdf.mod typesizes.mod netcdf netcdff netcdf_c++)
 
     foreach( LANGUAGE ${NETCDF_LANGUAGE_BINDINGS} )
-      # debug_var(LANGUAGE)
+        ecbuild_debug("FindNetCDF4: looking for ${LANGUAGE} language bindings")
         set( NETCDF_${LANGUAGE}_FOUND 1 ) # disable this in following if necessary
       
         # find the NETCDF includes
@@ -162,7 +162,7 @@ else()
           find_path( NETCDF_${INC}_INCLUDE_DIR ${INC}
               HINTS
                   ${NETCDF_${LANGUAGE}_INCLUDE_FLAGS}
-                      ENV NETCDF_ROOT
+                  ENV NETCDF_ROOT ENV NETCDF_DIR ENV NETCDF4_DIR
               PATHS
               PATH_SUFFIXES
                   include
@@ -203,13 +203,13 @@ else()
             find_library( NETCDF_${LIB}_LIBRARY_DEBUG
                 NAMES ${THIS_LIBRARY_SEARCH_DEBUG}
                 HINTS ${NETCDF_${LANGUAGE}_LIBRARY_DIRS}
-                ENV NETCDF_ROOT
+                ENV NETCDF_ROOT ENV NETCDF_DIR ENV NETCDF4_DIR
                 PATHS
                 PATH_SUFFIXES lib64 Lib64 lib Lib)
             find_library( NETCDF_${LIB}_LIBRARY_RELEASE
                 NAMES ${THIS_LIBRARY_SEARCH_RELEASE}
                 HINTS ${NETCDF_${LANGUAGE}_LIBRARY_DIRS}
-                ENV NETCDF_ROOT
+                ENV NETCDF_ROOT ENV NETCDF_DIR ENV NETCDF4_DIR
                 PATHS
                 PATH_SUFFIXES lib64 Lib64 lib Lib )
             select_library_configurations( NETCDF_${LIB} )
@@ -250,8 +250,8 @@ else()
         # Append the libraries for this language binding to the list of all
         # required libraries.
         
-        # debug_var( NETCDF_${LANGUAGE}_FOUND )
         if( NETCDF_${LANGUAGE}_FOUND )
+            ecbuild_debug( "FindNetCDF4: ${LANGUAGE} language bindings found" )
             if( CMAKE_CONFIGURATION_TYPES OR CMAKE_BUILD_TYPE )
                 list( APPEND NETCDF_${LANGUAGE}_LIBRARIES 
                     debug ${NETCDF_${LANGUAGE}_LIBRARIES_DEBUG}
diff --git a/cmake/ecbuild_add_cxx11_flags.cmake b/cmake/ecbuild_add_cxx11_flags.cmake
index 414f39f..7687bd9 100644
--- a/cmake/ecbuild_add_cxx11_flags.cmake
+++ b/cmake/ecbuild_add_cxx11_flags.cmake
@@ -6,17 +6,27 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to add cxx11 flags to compilation
-# uses macros from the project github.com/UCL/GreatCMakeCookOff
+##############################################################################
+#.rst:
+#
+# ecbuild_add_cxx11_flags
+# =======================
+#
+# Add cxx11 flags to CXX compilation flags. ::
+#
+#   ecbuild_add_cxx11_flags()
+#
+# This macro uses macros from http://github.com/UCL/GreatCMakeCookOff.
+#
+##############################################################################
 
 macro( ecbuild_add_cxx11_flags )
 
 	# if( CMAKE_COMPILER_IS_GNUCXX )
 	# 	if( CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7 )
-	# 		cmake_add_cxx_flags("-std=c++0x")
+	# 		ecbuild_add_cxx_flags("-std=c++0x")
 	# 	else()
-	# 		cmake_add_cxx_flags("-std=c++11")
+	# 		ecbuild_add_cxx_flags("-std=c++11")
 	# 	endif()
 	# endif()
 
diff --git a/cmake/ecbuild_add_executable.cmake b/cmake/ecbuild_add_executable.cmake
index 389505a..d1355c3 100644
--- a/cmake/ecbuild_add_executable.cmake
+++ b/cmake/ecbuild_add_executable.cmake
@@ -1,197 +1,296 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
-# In applying this licence, ECMWF does not waive the privileges and immunities 
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a test
+#.rst:
+#
+# ecbuild_add_executable
+# ======================
+#
+# Add an executable with a given list of source files. ::
+#
+#   ecbuild_add_executable( TARGET <name>
+#                           SOURCES <source1> [<source2> ...]
+#                           [ TEMPLATES <template1> [<template2> ...] ]
+#                           [ LIBS <library1> [<library2> ...] ]
+#                           [ INCLUDES <path1> [<path2> ...] ]
+#                           [ DEFINITIONS <definition1> [<definition2> ...] ]
+#                           [ PERSISTENT <file1> [<file2> ...] ]
+#                           [ GENERATED <file1> [<file2> ...] ]
+#                           [ DEPENDS <target1> [<target2> ...] ]
+#                           [ CONDITION <condition1> [<condition2> ...] ]
+#                           [ NOINSTALL ]
+#                           [ VERSION <version> | AUTO_VERSION ]
+#                           [ CFLAGS <flag1> [<flag2> ...] ]
+#                           [ CXXFLAGS <flag1> [<flag2> ...] ]
+#                           [ FFLAGS <flag1> [<flag2> ...] ]
+#                           [ LINKER_LANGUAGE <lang> ]
+#                           [ OUTPUT_NAME <name> ] )
+#
+# Options
+# -------
+#
+# TARGET : required
+#   target name
+#
+# SOURCES : required
+#   list of source files
+#
+# TEMPLATES : optional
+#   list of files specified as SOURCES which are not to be compiled separately
+#   (these are commonly template implementation files included in a header)
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# PERSISTENT : optional
+#   list of persistent layer object files
+#
+# GENERATED : optional
+#   list of files to mark as generated (sets GENERATED source file property)
+#
+# DEPENDS : optional
+#   list of targets to be built before this target
+#
+# CONDITION : optional
+#   list of conditions, all of which must evaluate to true for this target to be built
+#
+# NOINSTALL : optional
+#   do not install the executable
+# 
+# VERSION : optional, AUTO_VERSION or LIBS_VERSION is used if not specified
+#   version to use as executable version
+#
+# AUTO_VERSION : optional, ignored if VERSION is specified
+#   automatically version the executable with the package version
+#
+# CFLAGS : optional
+#   list of C compiler flags to use for all C source files
+#
+# CXXFLAGS : optional
+#   list of C++ compiler flags to use for all C++ source files
+#
+# FFLAGS : optional
+#   list of Fortran compiler flags to use for all Fortran source files
+#
+#
+# LINKER_LANGUAGE : optional
+#   sets the LINKER_LANGUAGE property on the target
+#
+# OUTPUT_NAME : optional
+#   sets the OUTPUT_NAME property on the target
+#
 ##############################################################################
 
 macro( ecbuild_add_executable )
 
-	set( options NOINSTALL AUTO_VERSION )
-	set( single_value_args TARGET COMPONENT LINKER_LANGUAGE VERSION OUTPUT_NAME )
-    set( multi_value_args  SOURCES TEMPLATES LIBS INCLUDES DEPENDS PERSISTENT DEFINITIONS CFLAGS CXXFLAGS FFLAGS GENERATED CONDITION )
+  set( options NOINSTALL AUTO_VERSION )
+  set( single_value_args TARGET COMPONENT LINKER_LANGUAGE VERSION OUTPUT_NAME )
+  set( multi_value_args  SOURCES TEMPLATES LIBS INCLUDES DEPENDS PERSISTENT DEFINITIONS CFLAGS CXXFLAGS FFLAGS GENERATED CONDITION )
+
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_add_executable(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
+
+  if( NOT _PAR_TARGET  )
+    message(FATAL_ERROR "The call to ecbuild_add_executable() doesn't specify the TARGET.")
+  endif()
+
+  if( NOT _PAR_SOURCES )
+    message(FATAL_ERROR "The call to ecbuild_add_executable() doesn't specify the SOURCES.")
+  endif()
+
+  ### conditional build
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  if( DEFINED _PAR_CONDITION )
+    set(_target_condition_file "${CMAKE_CURRENT_BINARY_DIR}/set_${_PAR_TARGET}_condition.cmake")
+    file( WRITE  ${_target_condition_file} "  if( ")
+    foreach( term ${_PAR_CONDITION} )
+      file( APPEND ${_target_condition_file} " ${term}")
+    endforeach()
+    file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
+    include( ${_target_condition_file} )
+  else()
+    set( _${_PAR_TARGET}_condition TRUE )
+  endif()
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_add_executable(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  if( _${_PAR_TARGET}_condition )
+
+    # add include dirs if defined
+    if( DEFINED _PAR_INCLUDES )
+      list(REMOVE_DUPLICATES _PAR_INCLUDES )
+      foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
+        if( path )
+          ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): add ${path} to include_directories")
+          include_directories( ${path} )
+        else()
+          ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): ${path} not found - not adding to include_directories")
+        endif()
+      endforeach()
     endif()
 
-    if( NOT _PAR_TARGET  )
-      message(FATAL_ERROR "The call to ecbuild_add_executable() doesn't specify the TARGET.")
+    # add persistent layer files
+    if( DEFINED _PAR_PERSISTENT )
+      if( DEFINED PERSISTENT_NAMESPACE )
+        ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
+      else()
+        ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
+      endif()
     endif()
 
-    if( NOT _PAR_SOURCES )
-      message(FATAL_ERROR "The call to ecbuild_add_executable() doesn't specify the SOURCES.")
+    # remove templates from compilation sources
+    if( DEFINED _PAR_TEMPLATES )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): removing ${_PAR_TEMPLATES} from sources")
+      list( REMOVE_ITEM _PAR_SOURCES ${_PAR_TEMPLATES} )
+      add_custom_target( ${_PAR_TARGET}_templates SOURCES ${_PAR_TEMPLATES} )
     endif()
 
-    ### conditional build
+    # add the executable target
+    add_executable( ${_PAR_TARGET} ${_PAR_SOURCES} )
 
-    if( DEFINED _PAR_CONDITION )
-        set(_target_condition_file "${CMAKE_CURRENT_BINARY_DIR}/set_${_PAR_TARGET}_condition.cmake")
-        file( WRITE  ${_target_condition_file} "  if( ")
-        foreach( term ${_PAR_CONDITION} )
-            file( APPEND ${_target_condition_file} " ${term}")
-        endforeach()
-        file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
-        include( ${_target_condition_file} )
-    else()
-        set( _${_PAR_TARGET}_condition TRUE )
+    # set OUTPUT_NAME
+
+    if( DEFINED _PAR_OUTPUT_NAME )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): set OUTPUT_NAME to ${_PAR_OUTPUT_NAME}")
+      set_target_properties( ${_PAR_TARGET} PROPERTIES OUTPUT_NAME ${_PAR_OUTPUT_NAME} )
     endif()
 
-    if( _${_PAR_TARGET}_condition )
-
-        # add include dirs if defined
-        if( DEFINED _PAR_INCLUDES )
-          list(REMOVE_DUPLICATES _PAR_INCLUDES )
-          foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
-            if( path )
-              include_directories( ${path} )
-    #        else()
-    #          message( WARNING "Path ${path} was skipped" )
-            endif()
-          endforeach()
-        endif()
-    
-        # add persistent layer files
-        if( DEFINED _PAR_PERSISTENT )
-			if( DEFINED PERSISTENT_NAMESPACE )
-	            ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
-			else()
-	            ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
-			endif()
-     endif()
-    
-        # add templates to project files and remove from compilation sources
-        if( DEFINED _PAR_TEMPLATES )
-            list( REMOVE_ITEM _PAR_SOURCES ${_PAR_TEMPLATES} )
-            ecbuild_declare_project_files( ${_PAR_TEMPLATES} )
-            add_custom_target( ${_PAR_TARGET}_templates SOURCES ${_PAR_TEMPLATES} )
-        endif()
-    
-        # add the executable target
-        add_executable( ${_PAR_TARGET} ${_PAR_SOURCES} )
-    
-		# set OUTPUT_NAME
-
-		if( DEFINED _PAR_OUTPUT_NAME )
-			set_target_properties( ${_PAR_TARGET} PROPERTIES OUTPUT_NAME ${_PAR_OUTPUT_NAME} )
-		endif()
-
-		# add extra dependencies
-        if( DEFINED _PAR_DEPENDS)
-          add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
-        endif()
-    
-        # add the link libraries
-        if( DEFINED _PAR_LIBS )
-          list(REMOVE_DUPLICATES _PAR_LIBS )
-          list(REMOVE_ITEM _PAR_LIBS debug)
-          list(REMOVE_ITEM _PAR_LIBS optimized)
-          foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
-            if( lib )
-              target_link_libraries( ${_PAR_TARGET} ${lib} )
-            else()
-#              message( WARNING "Lib ${lib} was skipped" )
-            endif()
-          endforeach()
-        endif()
-    
-        # add local flags
-        if( DEFINED _PAR_CFLAGS )
-            set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
-        endif()
-        if( DEFINED _PAR_CXXFLAGS )
-            set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
-        endif()
-        if( DEFINED _PAR_FFLAGS )
-            set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
-        endif()
-        if( DEFINED _PAR_GENERATED )
-            set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
-        endif()
+    # add extra dependencies
+    if( DEFINED _PAR_DEPENDS)
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): add dependency on ${_PAR_DEPENDS}")
+      add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
+    endif()
 
-		# define VERSION if requested
-		if( DEFINED _PAR_VERSION )
-			set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${_PAR_VERSION}" )
-		else()
-			if( _PAR_AUTO_VERSION )
-				set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}" )
-			endif()
-		endif()
-    
-        # filter sources        
-
-        ecbuild_separate_sources( TARGET ${_PAR_TARGET} SOURCES ${_PAR_SOURCES} )
-
-#    debug_var( ${_PAR_TARGET}_h_srcs )
-#    debug_var( ${_PAR_TARGET}_c_srcs )
-#    debug_var( ${_PAR_TARGET}_cxx_srcs )
-#    debug_var( ${_PAR_TARGET}_f_srcs )
-
-        # installation
-
-        if( NOT _PAR_NOINSTALL )
-
-            # add installation paths and associate with defined component
-#            if( DEFINED _PAR_COMPONENT )
-#                set( COMPONENT_DIRECTIVE "${_PAR_COMPONENT}" )
-#            else()
-#                set( COMPONENT_DIRECTIVE "${PROJECT_NAME}" )
-#            endif()
-        
-            install( TARGETS ${_PAR_TARGET}
-              EXPORT  ${CMAKE_PROJECT_NAME}-targets
-              RUNTIME DESTINATION ${INSTALL_BIN_DIR}
-              LIBRARY DESTINATION ${INSTALL_LIB_DIR}
-              ARCHIVE DESTINATION ${INSTALL_LIB_DIR} )
-#              COMPONENT ${COMPONENT_DIRECTIVE} )
-
-            # set build location
-
-            set_property( TARGET ${_PAR_TARGET} PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
-
-            # export location of target to other projects -- must be exactly after setting the build location (see previous command)
-
-            export( TARGETS ${_PAR_TARGET} APPEND FILE "${TOP_PROJECT_TARGETS_FILE}" )
-
-		else()
-				# NOINSTALL targets are always built the build_rpath, not the install_rpath
-				set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
-				set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
-		endif()
-    
-        # add definitions to compilation
-        if( DEFINED _PAR_DEFINITIONS )
-            get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
-            list( APPEND _target_defs ${_PAR_DEFINITIONS} )
-            set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
-        endif()
-        
-        # set linker language
-        if( DEFINED _PAR_LINKER_LANGUAGE )
-            set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
+    # add the link libraries
+    if( DEFINED _PAR_LIBS )
+      list(REMOVE_DUPLICATES _PAR_LIBS )
+      list(REMOVE_ITEM _PAR_LIBS debug)
+      list(REMOVE_ITEM _PAR_LIBS optimized)
+      foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
+        if( lib )
+          ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): linking with ${lib}")
+          target_link_libraries( ${_PAR_TARGET} ${lib} )
+        else()
+          ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): ${lib} not found - not linking")
         endif()
+      endforeach()
+    endif()
 
-        # make sure target is removed before - some problems with AIX
-        add_custom_command( TARGET ${_PAR_TARGET} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E remove $<TARGET_FILE:${_PAR_TARGET}> )
-    
-        # for the links target
-        if( NOT _PAR_NOINSTALL )
-            ecbuild_link_exe( ${_PAR_TARGET} $<TARGET_FILE_NAME:${_PAR_TARGET}> $<TARGET_FILE:${_PAR_TARGET}>  )
-        endif()
+    # filter sources
+    ecbuild_separate_sources( TARGET ${_PAR_TARGET} SOURCES ${_PAR_SOURCES} )
 
-        # append to the list of this project targets
-        set( ${PROJECT_NAME}_ALL_EXES ${${PROJECT_NAME}_ALL_EXES} ${_PAR_TARGET} CACHE INTERNAL "" )    
+    # add local flags
+    if( DEFINED _PAR_CFLAGS )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): use C flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
+    endif()
+    if( DEFINED _PAR_CXXFLAGS )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): use C++ flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
+    endif()
+    if( DEFINED _PAR_FFLAGS )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): use Fortran flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
+    endif()
+    if( DEFINED _PAR_GENERATED )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): mark as generated ${_PAR_GENERATED}")
+      set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
+    endif()
+
+    # define VERSION if requested
+    if( DEFINED _PAR_VERSION )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): set version to ${_PAR_VERSION}")
+      set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${_PAR_VERSION}" )
+    else()
+      if( _PAR_AUTO_VERSION )
+        ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): set version to ${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}")
+        set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}" )
+      endif()
+    endif()
+
+    #    debug_var( ${_PAR_TARGET}_h_srcs )
+    #    debug_var( ${_PAR_TARGET}_c_srcs )
+    #    debug_var( ${_PAR_TARGET}_cxx_srcs )
+    #    debug_var( ${_PAR_TARGET}_f_srcs )
+
+    # installation
+
+    if( NOT _PAR_NOINSTALL )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): installing to ${INSTALL_BIN_DIR}")
+
+      # add installation paths and associate with defined component
+      #            if( DEFINED _PAR_COMPONENT )
+      #                set( COMPONENT_DIRECTIVE "${_PAR_COMPONENT}" )
+      #            else()
+      #                set( COMPONENT_DIRECTIVE "${PROJECT_NAME}" )
+      #            endif()
+
+      install( TARGETS ${_PAR_TARGET}
+               EXPORT  ${CMAKE_PROJECT_NAME}-targets
+               RUNTIME DESTINATION ${INSTALL_BIN_DIR}
+               LIBRARY DESTINATION ${INSTALL_LIB_DIR}
+               ARCHIVE DESTINATION ${INSTALL_LIB_DIR} )
+      #        COMPONENT ${COMPONENT_DIRECTIVE} )
+
+      # set build location
+
+      set_property( TARGET ${_PAR_TARGET} PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
 
+      # export location of target to other projects -- must be exactly after setting the build location (see previous command)
+
+      export( TARGETS ${_PAR_TARGET} APPEND FILE "${TOP_PROJECT_TARGETS_FILE}" )
+
+    else()
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): not installing")
+      # NOINSTALL targets are always built the build_rpath, not the install_rpath
+      set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
+      set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
+    endif()
+
+    # add definitions to compilation
+    if( DEFINED _PAR_DEFINITIONS )
+      get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
+      list( APPEND _target_defs ${_PAR_DEFINITIONS} )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): using definitions ${_target_defs}")
+      set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
+    endif()
+
+    # set linker language
+    if( DEFINED _PAR_LINKER_LANGUAGE )
+      ecbuild_debug("ecbuild_add_executable(${_PAR_TARGET}): using linker language ${_PAR_LINKER_LANGUAGE}")
+      set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
+    endif()
+
+    # make sure target is removed before - some problems with AIX
+    add_custom_command( TARGET ${_PAR_TARGET} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E remove $<TARGET_FILE:${_PAR_TARGET}> )
+
+    # for the links target
+    if( NOT _PAR_NOINSTALL )
+      ecbuild_link_exe( ${_PAR_TARGET} $<TARGET_FILE_NAME:${_PAR_TARGET}> $<TARGET_FILE:${_PAR_TARGET}>  )
     endif()
 
-    # mark project files
-    ecbuild_declare_project_files( ${_PAR_SOURCES} )
+    # append to the list of this project targets
+    set( ${PROJECT_NAME}_ALL_EXES ${${PROJECT_NAME}_ALL_EXES} ${_PAR_TARGET} CACHE INTERNAL "" )
+
+  endif()
+
+  # mark source files as used
+  ecbuild_declare_project_files( ${_PAR_SOURCES} )
+  if( DEFINED _PAR_TEMPLATES )
+    ecbuild_declare_project_files( ${_PAR_TEMPLATES} )
+  endif()
 
 endmacro( ecbuild_add_executable  )
diff --git a/cmake/ecbuild_add_extra_search_paths.cmake b/cmake/ecbuild_add_extra_search_paths.cmake
index 8e28091..c8a7a77 100644
--- a/cmake/ecbuild_add_extra_search_paths.cmake
+++ b/cmake/ecbuild_add_extra_search_paths.cmake
@@ -6,7 +6,7 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
+###############################################################################
 #
 # macro for adding search paths to CMAKE_PREFIX_PATH
 # for example the ECMWF /usr/local/apps paths
@@ -15,20 +15,19 @@
 
 function( ecbuild_add_extra_search_paths pkg )
 
-# debug_var( pkg )
+  message( DEPRECATION " ecbuild_add_extra_search_paths modifies CMAKE_PREFIX_PATH,"
+           " which can affect future package discovery if not undone by the caller."
+           " The current CMAKE_PREFIX_PATH is being backed up as _CMAKE_PREFIX_PATH"
+           " so it can later be restored." )
 
-	ecbuild_list_extra_search_paths( ${pkg} CMAKE_PREFIX_PATH )
+  # Back up current CMAKE_PREFIX_PATH so the caller can reset it
+  set( _CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} PARENT_SCOPE )
 
-	set( CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} PARENT_SCOPE )
+  string( TOUPPER ${pkg} _PKG )
 
-	# fixes BOOST_ROOT taking precedence on the search for location
-	if( ${pkg} STREQUAL "boost" )
-		if( BOOST_ROOT OR BOOSTROOT OR DEFINED ENV{BOOST_ROOT} OR DEFINED ENV{BOOSTROOT} )
-			set( CMAKE_PREFIX_PATH ${BOOST_ROOT} ${BOOSTROOT} $ENV{BOOST_ROOT} $ENV{BOOSTROOT} ${CMAKE_PREFIX_PATH} )
-		endif()
-	endif()
+  ecbuild_list_extra_search_paths( ${pkg} CMAKE_PREFIX_PATH )
 
-# debug_var( CMAKE_PREFIX_PATH )
+  set( CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} PARENT_SCOPE )
+  # debug_var( CMAKE_PREFIX_PATH )
 
 endfunction()
-
diff --git a/cmake/ecbuild_add_library.cmake b/cmake/ecbuild_add_library.cmake
index 534807f..8ca43e0 100644
--- a/cmake/ecbuild_add_library.cmake
+++ b/cmake/ecbuild_add_library.cmake
@@ -7,266 +7,394 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# auxiliary macro for adding a library
+#.rst:
+#
+# ecbuild_add_library
+# ===================
+#
+# Add a library with a given list of source files. ::
+#
+#   ecbuild_add_library( TARGET <name>
+#                        SOURCES <source1> [<source2> ...]
+#                        [ TYPE SHARED|STATIC|MODULE ]
+#                        [ TEMPLATES <template1> [<template2> ...] ]
+#                        [ LIBS <library1> [<library2> ...] ]
+#                        [ INCLUDES <path1> [<path2> ...] ]
+#                        [ DEFINITIONS <definition1> [<definition2> ...] ]
+#                        [ PERSISTENT <file1> [<file2> ...] ]
+#                        [ GENERATED <file1> [<file2> ...] ]
+#                        [ DEPENDS <target1> [<target2> ...] ]
+#                        [ CONDITION <condition1> [<condition2> ...] ]
+#                        [ NOINSTALL ]
+#                        [ HEADER_DESTINATION <path> ]
+#                        [ INSTALL_HEADERS LISTED|ALL ]
+#                        [ INSTALL_HEADERS_LIST <header1> [<header2> ...] ]
+#                        [ INSTALL_HEADERS_REGEX <pattern> ]
+#                        [ VERSION <version> | AUTO_VERSION ]
+#                        [ CFLAGS <flag1> [<flag2> ...] ]
+#                        [ CXXFLAGS <flag1> [<flag2> ...] ]
+#                        [ FFLAGS <flag1> [<flag2> ...] ]
+#                        [ LINKER_LANGUAGE <lang> ]
+#                        [ OUTPUT_NAME <name> ] )
+#
+# Options
+# -------
+#
+# TARGET : required
+#   target name
+#
+# SOURCES : required
+#   list of source files
+#
+# TYPE : optional
+#   library type, one of:
+#
+#   :SHARED: libraries are linked dynamically and loaded at runtime
+#   :STATIC: archives of object files for use when linking other targets.
+#   :MODULE: plugins that are not linked into other targets but may be loaded
+#            dynamically at runtime using dlopen-like functionality
+#
+# TEMPLATES : optional
+#   list of files specified as SOURCES which are not to be compiled separately
+#   (these are commonly template implementation files included in a header)
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# PERSISTENT : optional
+#   list of persistent layer object files
+#
+# GENERATED : optional
+#   list of files to mark as generated (sets GENERATED source file property)
+#
+# DEPENDS : optional
+#   list of targets to be built before this target
+#
+# CONDITION : optional
+#   list of conditions, all of which must evaluate to true for this target to be built
+#
+# NOINSTALL : optional
+#   do not install the library
+# 
+# HEADER_DESTINATION
+#   directory to install headers (if not specified, INSTALL_INCLUDE_DIR is used)
+#
+# INSTALL_HEADERS : optional
+#   specify which header files to install:
+#
+#   :LISTED: install header files listed as SOURCES
+#   :ALL:    install all header files ending in .h, .hh, .hpp, .H
+#
+# INSTALL_HEADERS_LIST : optional
+#   list of extra headers to install
+#
+# INSTALL_HEADERS_REGEX : optional
+#   regular expression to match extra headers to install
+#
+# VERSION : optional, AUTO_VERSION or LIBS_VERSION is used if not specified
+#   version to use as library version
+#
+# AUTO_VERSION : optional, ignored if VERSION is specified
+#   automatically version the library with the package version
+#
+# CFLAGS : optional
+#   list of C compiler flags to use for all C source files
+#
+# CXXFLAGS : optional
+#   list of C++ compiler flags to use for all C++ source files
+#
+# FFLAGS : optional
+#   list of Fortran compiler flags to use for all Fortran source files
+#
+# LINKER_LANGUAGE : optional
+#   sets the LINKER_LANGUAGE property on the target
+#
+# OUTPUT_NAME : optional
+#   sets the OUTPUT_NAME property on the target
+#
 ##############################################################################
 
 function( ecbuild_add_library_impl )
 
-	set( options NOINSTALL AUTO_VERSION )
-	set( single_value_args TARGET TYPE COMPONENT INSTALL_HEADERS LINKER_LANGUAGE HEADER_DESTINATION VERSION OUTPUT_NAME )
-	set( multi_value_args  SOURCES TEMPLATES LIBS INCLUDES DEPENDS PERSISTENT DEFINITIONS CFLAGS CXXFLAGS FFLAGS GENERATED CONDITION )
-
-	cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
-
-	if(_PAR_UNPARSED_ARGUMENTS)
-	  message(FATAL_ERROR "Unknown keywords given to ecbuild_add_library(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-	endif()
-
-	if( NOT _PAR_TARGET  )
-	  message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the TARGET.")
-	endif()
-
-	if( NOT _PAR_SOURCES )
-	  message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the SOURCES.")
-	endif()
-
-	### conditional build
-
-	if( DEFINED _PAR_CONDITION )
-		set(_target_condition_file "${CMAKE_CURRENT_BINARY_DIR}/set_${_PAR_TARGET}_condition.cmake")
-		file( WRITE  ${_target_condition_file} "  if( ")
-		foreach( term ${_PAR_CONDITION} )
-			file( APPEND ${_target_condition_file} " ${term}")
-		endforeach()
-		file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
-		include( ${_target_condition_file} )
-	else()
-		set( _${_PAR_TARGET}_condition TRUE )
-	endif()
-
-	if( _${_PAR_TARGET}_condition )
-
-		# defines the type of library
-		if( DEFINED _PAR_TYPE )
-			# checks that is either SHARED or STATIC or MODULE
-			if( NOT _PAR_TYPE MATCHES "STATIC" AND
-				NOT _PAR_TYPE MATCHES "SHARED" AND
-				NOT _PAR_TYPE MATCHES "MODULE" )
-				message( FATAL_ERROR "library type must be one of [ STATIC | SHARED | MODULE ]" )
-			endif()
-		endif()
-
-
-		# add persistent layer files
-		if( DEFINED _PAR_PERSISTENT )
-			if( DEFINED PERSISTENT_NAMESPACE )
-				ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
-			else()
-				ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
-			endif()
-		endif()
-
-		# add templates to project files and remove from compilation sources
-		if( DEFINED _PAR_TEMPLATES )
-			list( REMOVE_ITEM _PAR_SOURCES ${_PAR_TEMPLATES} )
-			ecbuild_declare_project_files( ${_PAR_TEMPLATES} )
-			add_custom_target( ${_PAR_TARGET}_templates SOURCES ${_PAR_TEMPLATES} )
-		endif()
-
-		add_library( ${_PAR_TARGET} ${_PAR_TYPE} ${_PAR_SOURCES} )
-
-		# set OUTPUT_NAME
-
-		if( DEFINED _PAR_OUTPUT_NAME )
-			set_target_properties( ${_PAR_TARGET} PROPERTIES OUTPUT_NAME ${_PAR_OUTPUT_NAME} )
-		endif()
-
-		# add extra dependencies
-		if( DEFINED _PAR_DEPENDS)
-		  add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
-		endif()
-
-		# add the link libraries
-		if( DEFINED _PAR_LIBS )
-		  list(REMOVE_DUPLICATES _PAR_LIBS )
-		  list(REMOVE_ITEM _PAR_LIBS debug)
-		  list(REMOVE_ITEM _PAR_LIBS optimized)
-		  foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
-			if( lib )
-			  target_link_libraries( ${_PAR_TARGET} ${lib} )
-			else()
-#              message( WARNING "Lib ${lib} was skipped" )
-			endif()
-		  endforeach()
-		endif()
-
-		# add include dirs if defined
-		if( DEFINED _PAR_INCLUDES )
-		  list( REMOVE_DUPLICATES _PAR_INCLUDES )
-		  foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
-			if( path )
-				if( "${CMAKE_VERSION}" VERSION_LESS "2.8.11" )
-					include_directories( ${path} )
-				else()
-			  		target_include_directories( ${_PAR_TARGET} PUBLIC ${path} )
-				endif()
-	#        else()
-	#          message( WARNING "Path ${path} was skipped" )
-			endif()
-		  endforeach()
-		endif()
-
-		# FIX: Cray compiler PIC option is not detected by CMake
-
-		get_property( _target_pic TARGET ${_PAR_TARGET} PROPERTY POSITION_INDEPENDENT_CODE )
-		if( _target_pic )
-			if( "${CMAKE_C_COMPILER_ID}" STREQUAL "Cray" )
-				set( _PAR_CFLAGS "-fPIC -h PIC ${_PAR_CFLAGS}" )
-			endif()
-			if( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Cray" )
-				set( _PAR_CXXFLAGS "-fPIC -h PIC ${_PAR_CXXFLAGS}" )
-			endif()
-			if( "${CMAKE_Fortran_COMPILER_ID}" STREQUAL "Cray" )
-				set( _PAR_FFLAGS "-fPIC -h PIC ${_PAR_FFLAGS}" )
-			endif()
-		endif()
-
-		# define VERSION if requested
-		if( DEFINED _PAR_VERSION )
-			set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${_PAR_VERSION}" )
-		else()
-			if( _PAR_AUTO_VERSION OR LIBS_VERSION MATCHES "[Aa][Uu][Tt][Oo]")
-				set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}" )
-			endif()
-			if( LIBS_VERSION AND NOT LIBS_VERSION MATCHES "[Aa][Uu][Tt][Oo]" )
-				set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${LIBS_VERSION}" )
-			endif()
-		endif()
-
-		# filter sources
-
-		ecbuild_separate_sources( TARGET ${_PAR_TARGET} SOURCES ${_PAR_SOURCES} )
-
-#		debug_var( ${_PAR_TARGET}_h_srcs )
-#		debug_var( ${_PAR_TARGET}_c_srcs )
-#		debug_var( ${_PAR_TARGET}_cxx_srcs )
-#		debug_var( ${_PAR_TARGET}_f_srcs )
-
-		# add local flags
-
-		if( DEFINED _PAR_CFLAGS )
-			set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
-		endif()
-		if( DEFINED _PAR_CXXFLAGS )
-			set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
-		endif()
-		if( DEFINED _PAR_FFLAGS )
-			set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
-		endif()
-		if( DEFINED _PAR_GENERATED )
-			set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
-		endif()
-
-		# set linker language
-		if( DEFINED _PAR_LINKER_LANGUAGE )
-			set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
-		endif()
-
-		# installation
-
-		if( NOT _PAR_NOINSTALL )
-
-			# and associate with defined component
-#            if( DEFINED _PAR_COMPONENT )
-#                set( COMPONENT_DIRECTIVE "${_PAR_COMPONENT}" )
-#            else()
-#                set( COMPONENT_DIRECTIVE "${PROJECT_NAME}" )
-#            endif()
-
-			install( TARGETS ${_PAR_TARGET}
-			  EXPORT  ${CMAKE_PROJECT_NAME}-targets
-			  RUNTIME DESTINATION ${INSTALL_BIN_DIR}
-			  LIBRARY DESTINATION ${INSTALL_LIB_DIR}
-			  ARCHIVE DESTINATION ${INSTALL_LIB_DIR} )
-#              COMPONENT ${COMPONENT_DIRECTIVE} )
-
-			# install headers
-			if( _PAR_HEADER_DESTINATION )
-				set( _h_destination "${_PAR_HEADER_DESTINATION}" )
-			else()
-				set( _h_destination "${INSTALL_INCLUDE_DIR}" )
-			endif()
-
-			if( _PAR_INSTALL_HEADERS )
-				if( _PAR_INSTALL_HEADERS MATCHES "LISTED" )
-					foreach( file ${${_PAR_TARGET}_h_srcs} )
-						get_filename_component( _file_dir ${file} PATH )
-						install( FILES ${file} DESTINATION "${_h_destination}/${_file_dir}" )
-					endforeach()
-					if( DEFINED _PAR_TEMPLATES )
-						foreach( file ${_PAR_TEMPLATES} )
-							get_filename_component( _file_dir ${file} PATH )
-							install( FILES ${file} DESTINATION "${_h_destination}/${_file_dir}" )
-						endforeach()
-					endif()
-					if( DEFINED _PAR_PERSISTENT )
-						foreach( file ${_PAR_PERSISTENT} )
-							  get_filename_component( _file_dir ${file} PATH )
-							  get_filename_component( _file_we  ${file} NAME_WE )
-							  set( pfile "${CMAKE_CURRENT_BINARY_DIR}/${_file_dir}/${_file_we}.b" )
-							  install( FILES ${pfile} DESTINATION "${_h_destination}/${_file_dir}" )
-						endforeach()
-					endif()
-				endif()
-				if( _PAR_INSTALL_HEADERS MATCHES "ALL" ) # "(\\.h|\\.b|\\.hxx|\\.hh|\\.hpp|\\.H)" ????
-					install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.h" )
-					install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.hh" )
-					install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.hpp" )
-					install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.H" )
-				endif()
-			endif()
-
-			if( DEFINED _PAR_INSTALL_HEADERS_LIST )
-				install( FILES ${_PAR_INSTALL_HEADERS_LIST} DESTINATION ${_h_destination} )
-			endif()
-
-			if( DEFINED _PAR_INSTALL_HEADERS_REGEX )
-				install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "${_PAR_INSTALL_HEADERS_REGEX}")
-			endif()
-
-			# set build location
-
-			set_property( TARGET ${_PAR_TARGET} PROPERTY LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
-			set_property( TARGET ${_PAR_TARGET} PROPERTY ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
-
-			# export location of target to other projects -- must be exactly after setting the build location (see previous 2 commands)
-
-			export( TARGETS ${_PAR_TARGET} APPEND FILE "${TOP_PROJECT_TARGETS_FILE}" )
-
-		endif()
-
-		# add definitions to compilation
-		if( DEFINED _PAR_DEFINITIONS )
-			get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
-			list( APPEND _target_defs ${_PAR_DEFINITIONS} )
-			set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
-		endif()
-
-		# make sure target is removed before - some problems with AIX
-		add_custom_command( TARGET ${_PAR_TARGET} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E remove $<TARGET_FILE:${_PAR_TARGET}> )
-
-		# for the links target
-		if( NOT _PAR_NOINSTALL )
-			ecbuild_link_lib( ${_PAR_TARGET} $<TARGET_FILE_NAME:${_PAR_TARGET}> $<TARGET_FILE:${_PAR_TARGET}>  )
-		endif()
-
-		# append to the list of this project targets
-		set( ${PROJECT_NAME}_ALL_LIBS ${${PROJECT_NAME}_ALL_LIBS} ${_PAR_TARGET} CACHE INTERNAL "" )
-
-	endif()
-
-	# mark project files
-	ecbuild_declare_project_files( ${_PAR_SOURCES} )
+  set( options NOINSTALL AUTO_VERSION )
+  set( single_value_args TARGET TYPE COMPONENT INSTALL_HEADERS INSTALL_HEADERS_REGEX LINKER_LANGUAGE HEADER_DESTINATION VERSION OUTPUT_NAME )
+  set( multi_value_args  SOURCES TEMPLATES LIBS INCLUDES DEPENDS PERSISTENT DEFINITIONS INSTALL_HEADERS_LIST CFLAGS CXXFLAGS FFLAGS GENERATED CONDITION )
+
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_add_library(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
+
+  if( NOT _PAR_TARGET  )
+    message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the TARGET.")
+  endif()
+
+  if( NOT _PAR_SOURCES )
+    message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the SOURCES.")
+  endif()
+
+  ### conditional build
+
+  if( DEFINED _PAR_CONDITION )
+    set(_target_condition_file "${CMAKE_CURRENT_BINARY_DIR}/set_${_PAR_TARGET}_condition.cmake")
+    file( WRITE  ${_target_condition_file} "  if( ")
+    foreach( term ${_PAR_CONDITION} )
+      file( APPEND ${_target_condition_file} " ${term}")
+    endforeach()
+    file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
+    include( ${_target_condition_file} )
+  else()
+    set( _${_PAR_TARGET}_condition TRUE )
+  endif()
+
+  if( _${_PAR_TARGET}_condition )
+
+    # defines the type of library
+    if( DEFINED _PAR_TYPE )
+      # checks that is either SHARED or STATIC or MODULE
+      if( NOT _PAR_TYPE MATCHES "STATIC" AND
+          NOT _PAR_TYPE MATCHES "SHARED" AND
+          NOT _PAR_TYPE MATCHES "MODULE" )
+        message( FATAL_ERROR "library type must be one of [ STATIC | SHARED | MODULE ]" )
+      endif()
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): library type is ${_PAR_TYPE}")
+    endif()
+
+
+    # add persistent layer files
+    if( DEFINED _PAR_PERSISTENT )
+      if( DEFINED PERSISTENT_NAMESPACE )
+        ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
+      else()
+        ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
+      endif()
+    endif()
+
+    # remove templates from compilation sources
+    if( DEFINED _PAR_TEMPLATES )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): removing ${_PAR_TEMPLATES} from sources")
+      list( REMOVE_ITEM _PAR_SOURCES ${_PAR_TEMPLATES} )
+      add_custom_target( ${_PAR_TARGET}_templates SOURCES ${_PAR_TEMPLATES} )
+    endif()
+
+    add_library( ${_PAR_TARGET} ${_PAR_TYPE} ${_PAR_SOURCES} )
+
+    # set OUTPUT_NAME
+
+    if( DEFINED _PAR_OUTPUT_NAME )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): set OUTPUT_NAME to ${_PAR_OUTPUT_NAME}")
+      set_target_properties( ${_PAR_TARGET} PROPERTIES OUTPUT_NAME ${_PAR_OUTPUT_NAME} )
+    endif()
+
+    # add extra dependencies
+    if( DEFINED _PAR_DEPENDS)
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): add dependency on ${_PAR_DEPENDS}")
+      add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
+    endif()
+
+    # add the link libraries
+    if( DEFINED _PAR_LIBS )
+      list(REMOVE_DUPLICATES _PAR_LIBS )
+      list(REMOVE_ITEM _PAR_LIBS debug)
+      list(REMOVE_ITEM _PAR_LIBS optimized)
+      foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
+        if( lib )
+          ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): linking with ${lib}")
+          target_link_libraries( ${_PAR_TARGET} ${lib} )
+        else()
+          ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): ${lib} not found - not linking")
+        endif()
+      endforeach()
+    endif()
+
+    # add include dirs if defined
+    if( DEFINED _PAR_INCLUDES )
+      list( REMOVE_DUPLICATES _PAR_INCLUDES )
+      foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
+        if( path )
+          ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): add ${path} to include_directories")
+          if( "${CMAKE_VERSION}" VERSION_LESS "2.8.11" OR ECBUILD_USE_INCLUDE_DIRECTORIES )
+            include_directories( ${path} )
+          else()
+            target_include_directories( ${_PAR_TARGET} PUBLIC ${path} )
+          endif()
+        else()
+          ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): ${path} not found - not adding to include_directories")
+        endif()
+      endforeach()
+    endif()
+
+    # FIX: Cray compiler PIC option is not detected by CMake
+
+    get_property( _target_pic TARGET ${_PAR_TARGET} PROPERTY POSITION_INDEPENDENT_CODE )
+    if( _target_pic )
+      if( "${CMAKE_C_COMPILER_ID}" STREQUAL "Cray" )
+        set( _PAR_CFLAGS "-fPIC -h PIC ${_PAR_CFLAGS}" )
+      endif()
+      if( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Cray" )
+        set( _PAR_CXXFLAGS "-fPIC -h PIC ${_PAR_CXXFLAGS}" )
+      endif()
+      if( "${CMAKE_Fortran_COMPILER_ID}" STREQUAL "Cray" )
+        set( _PAR_FFLAGS "-fPIC -h PIC ${_PAR_FFLAGS}" )
+      endif()
+    endif()
+
+    # define VERSION if requested
+    if( DEFINED _PAR_VERSION )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): set version to ${_PAR_VERSION}")
+      set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${_PAR_VERSION}" )
+    else()
+      if( _PAR_AUTO_VERSION OR LIBS_VERSION MATCHES "[Aa][Uu][Tt][Oo]")
+        ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): set version to ${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION} (auto)")
+        set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}" )
+      endif()
+      if( LIBS_VERSION AND NOT LIBS_VERSION MATCHES "[Aa][Uu][Tt][Oo]" )
+        ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): set version to ${LIBS_VERSION}")
+        set_target_properties( ${_PAR_TARGET} PROPERTIES VERSION "${LIBS_VERSION}" )
+      endif()
+    endif()
+
+    # filter sources
+
+    ecbuild_separate_sources( TARGET ${_PAR_TARGET} SOURCES ${_PAR_SOURCES} )
+
+    #   debug_var( ${_PAR_TARGET}_h_srcs )
+    #   debug_var( ${_PAR_TARGET}_c_srcs )
+    #   debug_var( ${_PAR_TARGET}_cxx_srcs )
+    #   debug_var( ${_PAR_TARGET}_f_srcs )
+
+    # add local flags
+
+    if( DEFINED _PAR_CFLAGS )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): use C flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
+    endif()
+    if( DEFINED _PAR_CXXFLAGS )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): use C++ flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
+    endif()
+    if( DEFINED _PAR_FFLAGS )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): use Fortran flags ${_PAR_CFLAGS}")
+      set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
+    endif()
+    if( DEFINED _PAR_GENERATED )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): mark as generated ${_PAR_GENERATED}")
+      set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
+    endif()
+
+    # set linker language
+    if( DEFINED _PAR_LINKER_LANGUAGE )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): using linker language ${_PAR_LINKER_LANGUAGE}")
+      set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
+    endif()
+
+    # installation
+
+    if( NOT _PAR_NOINSTALL )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): installing to ${INSTALL_LIB_DIR}")
+
+      # and associate with defined component
+      #            if( DEFINED _PAR_COMPONENT )
+      #                set( COMPONENT_DIRECTIVE "${_PAR_COMPONENT}" )
+      #            else()
+      #                set( COMPONENT_DIRECTIVE "${PROJECT_NAME}" )
+      #            endif()
+
+      install( TARGETS ${_PAR_TARGET}
+        EXPORT  ${CMAKE_PROJECT_NAME}-targets
+        RUNTIME DESTINATION ${INSTALL_BIN_DIR}
+        LIBRARY DESTINATION ${INSTALL_LIB_DIR}
+        ARCHIVE DESTINATION ${INSTALL_LIB_DIR} )
+      #              COMPONENT ${COMPONENT_DIRECTIVE} )
+
+      # install headers
+      if( _PAR_HEADER_DESTINATION )
+        set( _h_destination "${_PAR_HEADER_DESTINATION}" )
+      else()
+        set( _h_destination "${INSTALL_INCLUDE_DIR}" )
+      endif()
+
+      if( _PAR_INSTALL_HEADERS )
+        if( _PAR_INSTALL_HEADERS MATCHES "LISTED" )
+          foreach( file ${${_PAR_TARGET}_h_srcs} )
+            get_filename_component( _file_dir ${file} PATH )
+            install( FILES ${file} DESTINATION "${_h_destination}/${_file_dir}" )
+          endforeach()
+          if( DEFINED _PAR_TEMPLATES )
+            foreach( file ${_PAR_TEMPLATES} )
+              get_filename_component( _file_dir ${file} PATH )
+              install( FILES ${file} DESTINATION "${_h_destination}/${_file_dir}" )
+            endforeach()
+          endif()
+          if( DEFINED _PAR_PERSISTENT )
+            foreach( file ${_PAR_PERSISTENT} )
+              get_filename_component( _file_dir ${file} PATH )
+              get_filename_component( _file_we  ${file} NAME_WE )
+              set( pfile "${CMAKE_CURRENT_BINARY_DIR}/${_file_dir}/${_file_we}.b" )
+              install( FILES ${pfile} DESTINATION "${_h_destination}/${_file_dir}" )
+            endforeach()
+          endif()
+        endif()
+        if( _PAR_INSTALL_HEADERS MATCHES "ALL" ) # "(\\.h|\\.b|\\.hxx|\\.hh|\\.hpp|\\.H)" ????
+          install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.h" )
+          install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.hh" )
+          install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.hpp" )
+          install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "*.H" )
+        endif()
+      endif()
+
+      if( DEFINED _PAR_INSTALL_HEADERS_LIST )
+        install( FILES ${_PAR_INSTALL_HEADERS_LIST} DESTINATION ${_h_destination} )
+      endif()
+
+      if( DEFINED _PAR_INSTALL_HEADERS_REGEX )
+        install( DIRECTORY ./  DESTINATION ${_h_destination} FILES_MATCHING PATTERN "${_PAR_INSTALL_HEADERS_REGEX}")
+      endif()
+
+      # set build location
+
+      set_property( TARGET ${_PAR_TARGET} PROPERTY LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
+      set_property( TARGET ${_PAR_TARGET} PROPERTY ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
+
+      # export location of target to other projects -- must be exactly after setting the build location (see previous 2 commands)
+
+      export( TARGETS ${_PAR_TARGET} APPEND FILE "${TOP_PROJECT_TARGETS_FILE}" )
+
+    endif()
+
+    # add definitions to compilation
+    if( DEFINED _PAR_DEFINITIONS )
+      get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
+      list( APPEND _target_defs ${_PAR_DEFINITIONS} )
+      ecbuild_debug("ecbuild_add_library(${_PAR_TARGET}): using definitions ${_target_defs}")
+      set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
+    endif()
+
+    # make sure target is removed before - some problems with AIX
+    add_custom_command( TARGET ${_PAR_TARGET} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E remove $<TARGET_FILE:${_PAR_TARGET}> )
+
+    # for the links target
+    if( NOT _PAR_NOINSTALL )
+      ecbuild_link_lib( ${_PAR_TARGET} $<TARGET_FILE_NAME:${_PAR_TARGET}> $<TARGET_FILE:${_PAR_TARGET}>  )
+    endif()
+
+    # append to the list of this project targets
+    set( ${PROJECT_NAME}_ALL_LIBS ${${PROJECT_NAME}_ALL_LIBS} ${_PAR_TARGET} CACHE INTERNAL "" )
+
+  endif()
+
+  # mark source files as used
+  ecbuild_declare_project_files( ${_PAR_SOURCES} )
+  if( DEFINED _PAR_TEMPLATES )
+    ecbuild_declare_project_files( ${_PAR_TEMPLATES} )
+  endif()
 
 endfunction( ecbuild_add_library_impl  )
 
@@ -276,46 +404,46 @@ endfunction( ecbuild_add_library_impl  )
 
 macro( ecbuild_add_library )
 
-	set( options  )
-	set( single_value_args TARGET TYPE )
-	set( multi_value_args )
+  set( options  )
+  set( single_value_args TARGET TYPE )
+  set( multi_value_args )
 
-	cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-	if( DEFINED _p_TYPE ) # don't do anything if TYPE was specified
+  if( DEFINED _p_TYPE ) # don't do anything if TYPE was specified
 
-			if( _p_TYPE MATCHES "[Bb][Oo][Tt][Hh]" ) # build both types
+    if( _p_TYPE MATCHES "[Bb][Oo][Tt][Hh]" ) # build both types
 
-				ecbuild_add_library_impl( TARGET ${_p_TARGET}        TYPE SHARED ${_p_UNPARSED_ARGUMENTS} )
-				ecbuild_add_library_impl( TARGET ${_p_TARGET}-static TYPE STATIC ${_p_UNPARSED_ARGUMENTS} OUTPUT_NAME ${_p_TARGET} DEPENDS ${_p_TARGET} )
+      ecbuild_add_library_impl( TARGET ${_p_TARGET}        TYPE SHARED ${_p_UNPARSED_ARGUMENTS} )
+      ecbuild_add_library_impl( TARGET ${_p_TARGET}-static TYPE STATIC ${_p_UNPARSED_ARGUMENTS} OUTPUT_NAME ${_p_TARGET} DEPENDS ${_p_TARGET} )
 
-			else()
+    else()
 
-				ecbuild_add_library_impl( ${ARGV} )
+      ecbuild_add_library_impl( ${ARGV} )
 
-			endif()
+    endif()
 
-	else()
+  else()
 
-		if( NOT DEFINED _p_TARGET )
-			message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the TARGET.")
-		else()
+    if( NOT DEFINED _p_TARGET )
+      message(FATAL_ERROR "The call to ecbuild_add_library() doesn't specify the TARGET.")
+    else()
 
-			if( BUILD_SHARED_LIBS MATCHES "[Bb][Oo][Tt][Hh]" ) # build both types
+      if( BUILD_SHARED_LIBS MATCHES "[Bb][Oo][Tt][Hh]" ) # build both types
 
-				ecbuild_add_library_impl( TARGET ${_p_TARGET}        TYPE SHARED ${_p_UNPARSED_ARGUMENTS} )
-				ecbuild_add_library_impl( TARGET ${_p_TARGET}-static TYPE STATIC ${_p_UNPARSED_ARGUMENTS} DEPENDS ${_p_TARGET} )
+        ecbuild_add_library_impl( TARGET ${_p_TARGET}        TYPE SHARED ${_p_UNPARSED_ARGUMENTS} )
+        ecbuild_add_library_impl( TARGET ${_p_TARGET}-static TYPE STATIC ${_p_UNPARSED_ARGUMENTS} DEPENDS ${_p_TARGET} )
 
-				set_target_properties( ${_p_TARGET}-static PROPERTIES OUTPUT_NAME ${_p_TARGET} )
+        set_target_properties( ${_p_TARGET}-static PROPERTIES OUTPUT_NAME ${_p_TARGET} )
 
-			else()
+      else()
 
-				ecbuild_add_library_impl( ${ARGV} )
+        ecbuild_add_library_impl( ${ARGV} )
 
-			endif()
+      endif()
 
-		endif()
+    endif()
 
-	endif()
+  endif()
 
 endmacro( ecbuild_add_library )
diff --git a/cmake/ecbuild_add_option.cmake b/cmake/ecbuild_add_option.cmake
index 8f42550..3561055 100644
--- a/cmake/ecbuild_add_option.cmake
+++ b/cmake/ecbuild_add_option.cmake
@@ -7,36 +7,91 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a test
+#.rst:
+#
+# ecbuild_add_option
+# ==================
+#
+# Add a CMake configuration option, which may depend on a list of packages. ::
+#
+#   ecbuild_add_option( FEATURE <name>
+#                       [ DEFAULT ON|OFF ]
+#                       [ DESCRIPTION <description> ]
+#                       [ REQUIRED_PACKAGES <package1> [<package2> ...] ]
+#                       [ CONDITION <condition1> [<condition2> ...] ]
+#                       [ ADVANCED ] )
+#
+# Options
+# -------
+#
+# FEATURE : required
+#   name of the feature / option
+#
+# DEFAULT : optional, defaults to ON
+#   if set to ON, the feature is enabled even if not explicitly requested
+#
+# DESCRIPTION : optional
+#   string describing the feature (shown in summary and stored in the cache)
+#
+# REQUIRED_PACKAGES : optional
+#   list of packages required to be found for this feature to be enabled
+#
+#   The package specification can be either ::
+#
+#     <package> [ <version> ... ]
+
+#   to search for a given package with option minimum required version or ::
+#
+#     PROJECT <name> [ VERSION <version> ... ]
+#
+#   to search for an ecBuild project with optional minimum required version.
+#
+# CONDITION : optional
+#   list of conditions, all of which must evaluate to true for this option to
+#   be enabled
+#
+# ADVANCED : optional
+#   mark the feature as advanced
+#
+# Usage
+# -----
+#
+# Features with ``DEFAULT OFF`` need to be explcitly enabled by the user with
+# ``-DENABLE_<FEATURE>=ON``. If a feature is enabled, all ``REQUIRED_PACKAGES``
+# are found and every ``CONDITION`` is met, ecBuild sets the variable
+# ``HAVE_<FEATURE>`` to ``ON``. This is the variable to use to check for the
+# availability of the feature.
+#
 ##############################################################################
 
 macro( ecbuild_add_option )
 
-	set( options ADVANCED )
+  set( options ADVANCED )
   set( single_value_args FEATURE DEFAULT DESCRIPTION )
   set( multi_value_args  REQUIRED_PACKAGES CONDITION )
 
-	cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
   if( _p_UNPARSED_ARGUMENTS )
-	  message(FATAL_ERROR "Unknown keywords given to ecbuild_add_option(): \"${_p_UNPARSED_ARGUMENTS}\"")
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_add_option(): \"${_p_UNPARSED_ARGUMENTS}\"")
   endif()
 
-	# check FEATURE parameter
+  # check FEATURE parameter
 
   if( NOT _p_FEATURE  )
-	  message(FATAL_ERROR "The call to ecbuild_add_option() doesn't specify the FEATURE.")
+    message(FATAL_ERROR "The call to ecbuild_add_option() doesn't specify the FEATURE.")
   endif()
 
-	# check DEFAULT parameter
+  # check DEFAULT parameter
 
   if( NOT DEFINED _p_DEFAULT )
-		set( _p_DEFAULT ON )
+    set( _p_DEFAULT ON )
   else()
-		if( NOT _p_DEFAULT MATCHES "[Oo][Nn]" AND NOT _p_DEFAULT MATCHES "[Oo][Ff][Ff]" )
-			message(FATAL_ERROR "In macro ecbuild_add_option(), DEFAULT is either ON or OFF: \"${_p_DEFAULT}\"")
-		endif()
-	endif()
+    if( NOT _p_DEFAULT MATCHES "[Oo][Nn]" AND NOT _p_DEFAULT MATCHES "[Oo][Ff][Ff]" )
+      message(FATAL_ERROR "In macro ecbuild_add_option(), DEFAULT is either ON or OFF: \"${_p_DEFAULT}\"")
+    endif()
+  endif()
+  ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): defaults to ${_p_DEFAULT}")
 
   # check CONDITION parameter
   if( DEFINED _p_CONDITION )
@@ -47,33 +102,39 @@ macro( ecbuild_add_option )
     endforeach()
     file( APPEND ${_feature_condition_file} " )\n    set(_${_p_FEATURE}_condition TRUE)\n  else()\n    set(_${_p_FEATURE}_condition FALSE)\n  endif()\n")
     include( ${_feature_condition_file} )
+    ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): checking condition ${_p_CONDITION} -> ${_${_p_FEATURE}_condition}")
   else()
     set( _${_p_FEATURE}_condition TRUE )
   endif()
 
-	# check if user provided value
+  # check if user provided value
 
-	get_property( _in_cache CACHE ENABLE_${_p_FEATURE} PROPERTY VALUE )
+  get_property( _in_cache CACHE ENABLE_${_p_FEATURE} PROPERTY VALUE )
 
-	if( NOT "${ENABLE_${_p_FEATURE}}" STREQUAL "" AND _in_cache )
-		set( ${_p_FEATURE}_user_provided_input 1 CACHE BOOL "" )
-	else()
-		set( ${_p_FEATURE}_user_provided_input 0 CACHE BOOL "" )
-	endif()
+  if( NOT "${ENABLE_${_p_FEATURE}}" STREQUAL "" AND _in_cache )
+    ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): ENABLE_${_p_FEATURE} was found in cache")
+    set( ${_p_FEATURE}_user_provided_input 1 CACHE BOOL "" )
+  else()
+    ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): ENABLE_${_p_FEATURE} not found in cache")
+    set( ${_p_FEATURE}_user_provided_input 0 CACHE BOOL "" )
+  endif()
 
-	mark_as_advanced( ${_p_FEATURE}_user_provided_input )
+  mark_as_advanced( ${_p_FEATURE}_user_provided_input )
 
 
-	# define the option -- for cmake GUI
+  # define the option -- for cmake GUI
 
-	option( ENABLE_${_p_FEATURE} "${_p_DESCRIPTION}" ${_p_DEFAULT} )
+  option( ENABLE_${_p_FEATURE} "${_p_DESCRIPTION}" ${_p_DEFAULT} )
+  ecbuild_set_feature( ${_p_FEATURE} ENABLED ${_p_DEFAULT} PURPOSE "${_p_DESCRIPTION}" )
 
+  ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): ENABLE_${_p_FEATURE} = ${ENABLE_${_p_FEATURE}}")
   set( _do_search ${ENABLE_${_p_FEATURE}} )
   if( _p_FEATURE STREQUAL "OMP" )
     set( _do_search TRUE )
   endif()
 
   if( _do_search  )
+    ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): feature enabled")
 
     set( HAVE_${_p_FEATURE} 1 )
 
@@ -81,7 +142,9 @@ macro( ecbuild_add_option )
 
       ### search for dependent packages
 
+      set( _failed_to_find_packages )  # clear variable
       foreach( pkg ${_p_REQUIRED_PACKAGES} )
+        ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for dependent package ${pkg}")
 
         string(REPLACE " " ";" pkglist ${pkg}) # string to list
 
@@ -102,17 +165,23 @@ macro( ecbuild_add_option )
         string( TOLOWER ${pkgname} pkgLOWER )
 
         if( ${pkgname}_FOUND OR ${pkgUPPER}_FOUND OR ${pkgLOWER}_FOUND )
+
+          ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): ${pkgname} has already been found")
           set( ${pkgname}_already_found 1 )
-        else()
 
-          ecbuild_add_extra_search_paths( ${pkgLOWER} ) # adds search paths specific to ECMWF
+        else()
 
           if( pkgproject )
+
+            ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for ecbuild project ${pkgname}")
             ecbuild_use_package( ${pkglist} )
+
           else()
+
             if( pkgname STREQUAL "MPI" )
               set( _find_args ${pkglist} )
               list( REMOVE_ITEM _find_args "MPI" )
+              ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for MPI")
               ecbuild_find_mpi( ${_find_args} )
             elseif( pkgname STREQUAL "OMP" )
               set( _find_args ${pkglist} )
@@ -120,15 +189,27 @@ macro( ecbuild_add_option )
               if( NOT ENABLE_${_p_FEATURE} )
                 list( APPEND _find_args STUBS )
               endif()
+              ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for OpenMP")
               ecbuild_find_omp( ${_find_args} )
+            elseif( pkgname STREQUAL "Python" OR pkgname STREQUAL "PYTHON" )
+              set( _find_args ${pkglist} )
+              list( REMOVE_ITEM _find_args ${pkgname} )
+              ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for Python")
+              ecbuild_find_python( ${_find_args} )
             else()
+              ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): searching for package ${pkgname}")
               find_package( ${pkglist} )
             endif()
+
           endif()
 
-          # append to list of third-party libraries (to be forward to other packages )
-          string( TOUPPER ${PROJECT_NAME} PNAME )
-          list( APPEND ${PNAME}_TPLS ${pkgname} )
+        endif()
+
+        # if found append to list of third-party libraries (to be forward to other packages )
+        if( ${pkgname}_FOUND OR ${pkgUPPER}_FOUND OR ${pkgLOWER}_FOUND )
+
+          list( APPEND ${PROJECT_NAME_CAPS}_TPLS ${pkgname} )
+          list( REMOVE_DUPLICATES ${PROJECT_NAME_CAPS}_TPLS )
 
         endif()
 
@@ -147,49 +228,50 @@ macro( ecbuild_add_option )
         endif()
 
       endforeach()
-    else()
+    else( _${_p_FEATURE}_condition )
       set( HAVE_${_p_FEATURE} 0 )
-    endif()
+    endif( _${_p_FEATURE}_condition )
 
-		# FINAL CHECK
+    ecbuild_set_feature( ${_p_FEATURE} ENABLED ${HAVE_${_p_FEATURE}} )
+    # FINAL CHECK
 
-		if( HAVE_${_p_FEATURE} )
+    if( HAVE_${_p_FEATURE} )
 
-			message( STATUS "Feature ${_p_FEATURE} enabled" )
+      message( STATUS "Feature ${_p_FEATURE} enabled" )
 
-		else() # if user provided input and we cannot satisfy FAIL otherwise WARN
+    else() # if user provided input and we cannot satisfy FAIL otherwise WARN
 
-			if( ${_p_FEATURE}_user_provided_input )
+      if( ${_p_FEATURE}_user_provided_input )
         if( _${_p_FEATURE}_condition )
           message( FATAL_ERROR "Feature ${_p_FEATURE} cannot be enabled -- following required packages weren't found: ${_failed_to_find_packages}" )
         else()
           message( FATAL_ERROR "Feature ${_p_FEATURE} cannot be enabled -- following condition was not met: ${_p_CONDITION}" )
         endif()
-			else()
-				message( STATUS "Feature ${_p_FEATURE} was not enabled (also not requested) -- following required packages weren't found: ${_failed_to_find_packages}" )
-				set( ENABLE_${_p_FEATURE} OFF )
-			endif()
+      else()
+        if( _${_p_FEATURE}_condition )
+          message( STATUS "Feature ${_p_FEATURE} was not enabled (also not requested) -- following condition was not met: ${_p_CONDITION}" )
+        else()
+          message( STATUS "Feature ${_p_FEATURE} was not enabled (also not requested) -- following required packages weren't found: ${_failed_to_find_packages}" )
+        endif()
+        set( ENABLE_${_p_FEATURE} OFF )
+        ecbuild_set_feature( ${_p_FEATURE} ENABLED OFF )
+      endif()
 
-		endif()
+    endif()
 
   else( _do_search )
 
-		set( HAVE_${_p_FEATURE} 0 )
+    ecbuild_debug("ecbuild_add_option(${_p_FEATURE}): feature disabled")
+    set( HAVE_${_p_FEATURE} 0 )
+    ecbuild_set_feature( ${_p_FEATURE} ENABLED OFF )
 
   endif( _do_search )
 
 
-	if( ${_p_ADVANCED} )
-		mark_as_advanced( ENABLE_${_p_FEATURE} )
-	else()
-		add_feature_info( ${_p_FEATURE} ENABLE_${_p_FEATURE} "${_p_DESCRIPTION}")
-	endif()
-
-  if( HAVE_${_p_FEATURE} )
-    string( TOUPPER PNAME ${PROJECT_NAME} )
-    set( ${PNAME}_HAVE_${_p_FEATURE} 1 )
-    set( ${PNAME}_FEATURES "${${PNAME}_FEATURES};${PNAME}_HAVE_${_p_FEATURE}" CACHE INTERNAL "" )
-    list( REMOVE_DUPLICATES ${PNAME}_FEATURES )
+  if( ${_p_ADVANCED} )
+    mark_as_advanced( ENABLE_${_p_FEATURE} )
   endif()
 
+  set( ${PROJECT_NAME_CAPS}_HAVE_${_p_FEATURE} ${HAVE_${_p_FEATURE}} )
+
 endmacro( ecbuild_add_option  )
diff --git a/cmake/ecbuild_add_persistent.cmake b/cmake/ecbuild_add_persistent.cmake
index c8ef383..42788c7 100644
--- a/cmake/ecbuild_add_persistent.cmake
+++ b/cmake/ecbuild_add_persistent.cmake
@@ -7,55 +7,79 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding persistent layer object classes
+#.rst:
+#
+# ecbuild_add_persistent
+# ======================
+#
+# Add persistent layer object classes. ::
+#
+#   ecbuild_add_persistent( SRC_LIST <variable>
+#                           FILES <file1> [<file2> ...] ]
+#                           [ NAMESPACE <namespace> ] )
+#
+# Options
+# -------
+#
+# SRC_LIST : required
+#   CMake variable to append the generated persistent layer objects to
+#
+# FILES : required
+#   list of base names of files to build persistent class information for
+#
+#   The source file is expected to have a .h extension, the generated file
+#   gets a .b extension.
+#
+# NAMESPACE : optional
+#   C++ namespace to place the persistent class information in
+#
 ##############################################################################
-	
+  
 # define the script to build the persistent class information
 set( sg_perl "${CMAKE_CURRENT_LIST_DIR}/sg.pl" CACHE INTERNAL "perl script to generate persistent objects" )
 
 macro( ecbuild_add_persistent )
 
-	ecbuild_find_perl( REQUIRED )
+  ecbuild_find_perl( REQUIRED )
 
-	set( options )
-    set( single_value_args SRC_LIST NAMESPACE )
-    set( multi_value_args  FILES ) 
+  set( options )
+  set( single_value_args SRC_LIST NAMESPACE )
+  set( multi_value_args  FILES ) 
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_add_persistent(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_add_persistent(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    if( NOT _PAR_SRC_LIST  )
-      message(FATAL_ERROR "The call to ecbuild_add_persistent() doesn't specify the SRC_LIST.")
-    endif()
+  if( NOT _PAR_SRC_LIST  )
+    message(FATAL_ERROR "The call to ecbuild_add_persistent() doesn't specify the SRC_LIST.")
+  endif()
 
-    if( NOT _PAR_FILES )
-      message(FATAL_ERROR "The call to ecbuild_add_persistent() doesn't specify the FILES.")
-    endif()
+  if( NOT _PAR_FILES )
+    message(FATAL_ERROR "The call to ecbuild_add_persistent() doesn't specify the FILES.")
+  endif()
 
-    foreach( file ${_PAR_FILES} )
+  foreach( file ${_PAR_FILES} )
 
-      get_filename_component( _file_dir    ${file} PATH )
-      get_filename_component( _file_we     ${file} NAME_WE )
+    get_filename_component( _file_dir    ${file} PATH )
+    get_filename_component( _file_we     ${file} NAME_WE )
+
+    set( file ${_file_we} )
+    if( _file_dir )
+      file( MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_file_dir} )
+      set( file ${_file_dir}/${_file_we} )
+    endif()
 
-      set( file ${_file_we} )
-      if( _file_dir )
-         file( MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_file_dir} )
-         set( file ${_file_dir}/${_file_we} )
-      endif()
+    # debug_var(file)
 
-      # debug_var(file)
+    add_custom_command( OUTPUT  ${file}.b
+                        COMMAND ${PERL_EXECUTABLE} ${sg_perl} ${CMAKE_CURRENT_SOURCE_DIR}/${file}.h
+                                ${CMAKE_CURRENT_BINARY_DIR}/${_file_dir} ${_PAR_NAMESPACE}
+                        DEPENDS ${sg_perl} ${file}.h )
+    set_source_files_properties( ${file}.h PROPERTIES OBJECT_DEPENDS "${file}.b" )
+    list( APPEND ${_PAR_SRC_LIST} ${CMAKE_CURRENT_BINARY_DIR}/${file}.b )
 
-      add_custom_command(
-        OUTPUT  ${file}.b
-		COMMAND ${PERL_EXECUTABLE} ${sg_perl} ${CMAKE_CURRENT_SOURCE_DIR}/${file}.h ${CMAKE_CURRENT_BINARY_DIR}/${_file_dir} ${_PAR_NAMESPACE}
-		DEPENDS ${sg_perl} ${file}.h
-        )
-      set_source_files_properties( ${file}.h PROPERTIES OBJECT_DEPENDS "${file}.b" )
-      list( APPEND ${_PAR_SRC_LIST} ${CMAKE_CURRENT_BINARY_DIR}/${file}.b )
-    
-    endforeach()
+  endforeach()
 
 endmacro( ecbuild_add_persistent  )
diff --git a/cmake/ecbuild_add_resources.cmake b/cmake/ecbuild_add_resources.cmake
index 12f47af..83f3c7e 100644
--- a/cmake/ecbuild_add_resources.cmake
+++ b/cmake/ecbuild_add_resources.cmake
@@ -7,58 +7,52 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a resources
+#.rst:
+#
+# ecbuild_add_resources
+# =====================
+#
+# Add resources as project files but optionally exclude them from packaging. ::
+#
+#   ecbuild_add_resources( TARGET <name>
+#                          [ SOURCES <source1> [<source2> ...] ]
+#                          [ SOURCES_PACK <source1> [<source2> ...] ]
+#                          [ SOURCES_DONT_PACK <source1> [<source2> ...] ]
+#                          [ PACK <file1> [<file2> ...] ]
+#                          [ DONT_PACK <file1> [<file2> ...] ]
+#                          [ DONT_PACK_DIRS <directory1> [<directory2> ...] ]
+#                          [ DONT_PACK_REGEX <regex1> [<regex2> ...] ] )
+#
+# Options
+# -------
+#
+# TARGET : required
+#   target name (target will only be created if there are any sources)
+#
+# SOURCES : optional, alias for SOURCES_PACK
+#   list of source files included when packaging
+#
+# SOURCES_PACK : optional, alias for SOURCES
+#   list of source files included when packaging
+#
+# SOURCES_DONT_PACK : optional
+#   list of source files excluded when packaging
+#
+# PACK : optional, priority over DONT_PACK, DONT_PACK_DIRS, DONT_PACK_REGEX
+#   list of files to include when packaging
+#
+# DONT_PACK : optional
+#   list of files to exclude when packaging
+#
+# DONT_PACK_DIRS : optional
+#   list of directories to exclude when packaging
+#
+# DONT_PACK_REGEX : optional
+#   list of regular expressions to match files and directories to exclude when
+#   packaging
+#
 ##############################################################################
 
-macro( ecbuild_dont_pack )
-
-    set( options )
-    set( single_value_args REGEX )
-    set( multi_value_args  FILES DIRS )
-
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
-
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_add_resources(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
-
-    if( NOT DEFINED _PAR_REGEX AND NOT  DEFINED _PAR_FILES AND NOT  DEFINED _PAR_DIRS )
-      message(FATAL_ERROR "Call to ecbuild_dont_pack does not speficify any list to avoid packing.")
-    endif()
-
-    set( LOCAL_FILES_NOT_TO_PACK "" )
-
-    # all recursive files are not to pack
-    if( DEFINED _PAR_REGEX )
-        file( GLOB_RECURSE all_files_in_subdirs RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${_PAR_REGEX} )
-        list( APPEND LOCAL_FILES_NOT_TO_PACK ${all_files_in_subdirs} )
-    endif()
-
-    # selected dirs not to pack
-    if( DEFINED _PAR_DIRS )
-        foreach( dir ${_PAR_DIRS} )
-            list( APPEND LOCAL_FILES_NOT_TO_PACK ${dir}/ )
-        endforeach()
-    endif()
-
-    # selected files not to pack
-    if( DEFINED _PAR_FILES )
-        list( APPEND LOCAL_FILES_NOT_TO_PACK ${_PAR_FILES} )
-    endif()
-
-    # transform the local files  to full absolute paths
-    # and place them in the global list of files not to pack
-    foreach( file ${LOCAL_FILES_NOT_TO_PACK} )
-        list( APPEND ECBUILD_DONT_PACK_FILES ${CMAKE_CURRENT_SOURCE_DIR}/${file} )
-    endforeach()
-
-    # save cache if we added any files not to pack
-    if( LOCAL_FILES_NOT_TO_PACK )
-        set( ECBUILD_DONT_PACK_FILES ${ECBUILD_DONT_PACK_FILES} CACHE INTERNAL "" )
-    endif()
-
-endmacro()
-
 macro( ecbuild_add_resources )
 
     set( options )
@@ -155,4 +149,3 @@ macro( ecbuild_add_resources )
     endif()
 
 endmacro( ecbuild_add_resources  )
-
diff --git a/cmake/ecbuild_add_test.cmake b/cmake/ecbuild_add_test.cmake
index 44f850f..f651de9 100644
--- a/cmake/ecbuild_add_test.cmake
+++ b/cmake/ecbuild_add_test.cmake
@@ -7,309 +7,433 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a test
+#.rst:
+#
+# ecbuild_add_test
+# ================
+#
+# Add a test as a script or an executable with a given list of source files. ::
+#
+#   ecbuild_add_test( [ TARGET <name> ]
+#                     [ SOURCES <source1> [<source2> ...] ]
+#                     [ COMMAND <executable> ]
+#                     [ TYPE EXE|SCRIPT|PYTHON ]
+#                     [ ARGS <argument1> [<argument2> ...] ]
+#                     [ RESOURCES <file1> [<file2> ...] ]
+#                     [ TEST_DATA <file1> [<file2> ...] ]
+#                     [ BOOST ]
+#                     [ MPI <number-of-ranks> ]
+#                     [ ENABLED ON|OFF ]
+#                     [ LIBS <library1> [<library2> ...] ]
+#                     [ INCLUDES <path1> [<path2> ...] ]
+#                     [ DEFINITIONS <definition1> [<definition2> ...] ]
+#                     [ PERSISTENT <file1> [<file2> ...] ]
+#                     [ GENERATED <file1> [<file2> ...] ]
+#                     [ DEPENDS <target1> [<target2> ...] ]
+#                     [ TEST_DEPENDS <target1> [<target2> ...] ]
+#                     [ CONDITION <condition1> [<condition2> ...] ]
+#                     [ ENVIRONMENT <variable1> [<variable2> ...] ]
+#                     [ WORKING_DIRECTORY <path> ]
+#                     [ CFLAGS <flag1> [<flag2> ...] ]
+#                     [ CXXFLAGS <flag1> [<flag2> ...] ]
+#                     [ FFLAGS <flag1> [<flag2> ...] ]
+#                     [ LINKER_LANGUAGE <lang> ] )
+#
+# Options
+# -------
+#
+# TARGET : either TARGET or COMMAND must be provided, unless TYPE is PYTHON
+#   target name to be built
+#
+# SOURCES : required if TARGET is provided
+#   list of source files to be compiled
+#
+# COMMAND : either TARGET or COMMAND must be provided, unless TYPE is PYTHON
+#   command or script to execute (no executable is built)
+#
+# TYPE : optional
+#   test type, one of:
+#
+#   :EXE:    run built executable, default if TARGET is provided
+#   :SCRIPT: run command or script, default if COMMAND is provided
+#   :PYTHON: run a Python script (requires the Python interpreter to be found)
+#
+# ARGS : optional
+#   list of arguments to pass to TARGET or COMMAND when running the test
+#
+# RESOURCES : optional
+#   list of files to copy from the test source directory to the test directory
+#
+# TEST_DATA : optional
+#   list of test data files to download
+#
+# BOOST : optional
+#   use the Boost Unit Test Framework
+#
+# MPI : optional
+#   number of MPI tasks to use.
+#
+#   If greater than 1, and MPI is not available, the test is disabled.
+#
+# ENABLED : optional
+#   if set to OFF, the test is built but not enabled as a test case
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# PERSISTENT : optional
+#   list of persistent layer object files
+#
+# GENERATED : optional
+#   list of files to mark as generated (sets GENERATED source file property)
+#
+# DEPENDS : optional
+#   list of targets to be built before this target
+#
+# TEST_DEPENDS : optional
+#   list of tests to be run before this one
+#
+# CONDITION : optional
+#   list of conditions, all of which must evaluate to true for this target to be built
+#
+# ENVIRONMENT : optional
+#   list of environment variables to set in the test environment
+#
+# WORKING_DIRECTORY : optional
+#   directory to switch to before running the test
+#
+# CFLAGS : optional
+#   list of C compiler flags to use for all C source files
+#
+# CXXFLAGS : optional
+#   list of C++ compiler flags to use for all C++ source files
+#
+# FFLAGS : optional
+#   list of Fortran compiler flags to use for all Fortran source files
+#
+# LINKER_LANGUAGE : optional
+#   sets the LINKER_LANGUAGE property on the target
+#
 ##############################################################################
 
-# Arguments:
-#  TARGET : name of test
-#  ENABLED [optional]: (default ON)
-#  COMMAND [optional]: Run command instead of executable
-#  TYPE [optional]: EXE / SCRIPT / PYTHON  (default EXE)
-#  MPI [optional]: number of mpi-tasks to use. If greater than 1,
-#                  and MPI is not available, the test is disabled
-#  SOURCES: sources to be compiled
-#  LIBS: Libraries needed for linking
-#  INCLUDES: Extra include directories
-#  DEPENDS: Add explicit dependency to other targets (for building)
-#  TEST_DEPENDS: add explicity dependency on another test running before
-#  ARGS: Command-line arguments to COMMAND OR TARGET
-
 macro( ecbuild_add_test )
 
-    set( options           BOOST )
-    set( single_value_args TARGET ENABLED COMMAND TYPE LINKER_LANGUAGE MPI WORKING_DIRECTORY )
-    set( multi_value_args  SOURCES LIBS INCLUDES TEST_DEPENDS DEPENDS ARGS PERSISTENT DEFINITIONS RESOURCES TEST_DATA CFLAGS CXXFLAGS FFLAGS GENERATED CONDITION ENVIRONMENT )
+  set( options           BOOST )
+  set( single_value_args TARGET ENABLED COMMAND TYPE LINKER_LANGUAGE MPI WORKING_DIRECTORY )
+  set( multi_value_args  SOURCES LIBS INCLUDES TEST_DEPENDS DEPENDS ARGS
+                         PERSISTENT DEFINITIONS RESOURCES TEST_DATA CFLAGS
+                         CXXFLAGS FFLAGS GENERATED CONDITION ENVIRONMENT )
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_add_test(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_add_test(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    set( _TEST_DIR ${CMAKE_CURRENT_BINARY_DIR} )
+  set( _TEST_DIR ${CMAKE_CURRENT_BINARY_DIR} )
 
-    # Check for MPI
-    if(_PAR_MPI)
-      if( (_PAR_MPI GREATER 1) AND ( (NOT HAVE_MPI) OR (NOT MPIEXEC) ) )
-        set( _PAR_ENABLED 0 )
-      endif()
-      if( (_PAR_MPI EQUAL 1) AND (NOT HAVE_MPI) )
-        set( _PAR_MPI 0 )
-      endif()
+  # Check for MPI
+  if(_PAR_MPI)
+    if( (_PAR_MPI GREATER 1) AND ( (NOT HAVE_MPI) OR (NOT MPIEXEC) ) )
+      ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): ${_PAR_MPI} MPI ranks requested but MPI not available - disabling test")
+      set( _PAR_ENABLED 0 )
     endif()
-
-    # default is enabled
-    if( NOT DEFINED _PAR_ENABLED )
-      set( _PAR_ENABLED 1 )
+    if( (_PAR_MPI EQUAL 1) AND (NOT HAVE_MPI) )
+      ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): 1 MPI rank requested but MPI not available - disabling MPI")
+      set( _PAR_MPI 0 )
     endif()
+  endif()
 
+  # default is enabled
+  if( NOT DEFINED _PAR_ENABLED )
+    set( _PAR_ENABLED 1 )
+  endif()
 
-    ### check test type
 
-    # command implies script
-    if( DEFINED _PAR_COMMAND )
-        set( _PAR_TYPE "SCRIPT" )
-    endif()
+  ### check test type
 
-    # default of TYPE
-    if( NOT _PAR_TYPE AND DEFINED _PAR_TARGET )
-        set( _PAR_TYPE "EXE" )
-        if( NOT _PAR_SOURCES )
-           message(FATAL_ERROR "The call to ecbuild_add_test() defines neither a TARGET without SOURCES.")
-        endif()
-    endif()
+  # command implies script
+  if( DEFINED _PAR_COMMAND )
+    set( _PAR_TYPE "SCRIPT" )
+  endif()
 
-    if( _PAR_TYPE MATCHES "PYTHON" )
-        if( PYTHONINTERP_FOUND )
-            set( _PAR_COMMAND ${PYTHON_EXECUTABLE} )
-        else()
-            message( FATAL_ERROR "Requested a python test but python interpreter not found - PYTHON_EXECUTABLE: [${PYTHON_EXECUTABLE}]" )
-        endif()
+  # default of TYPE
+  if( NOT _PAR_TYPE AND DEFINED _PAR_TARGET )
+    set( _PAR_TYPE "EXE" )
+    if( NOT _PAR_SOURCES )
+      message(FATAL_ERROR "The call to ecbuild_add_test() defines a TARGET without SOURCES.")
     endif()
+  endif()
 
-    ### further checks
-
-    if( NOT _PAR_TARGET AND NOT _PAR_COMMAND )
-        message(FATAL_ERROR "The call to ecbuild_add_test() defines neither a TARGET nor a COMMAND.")
+  if( _PAR_TYPE MATCHES "PYTHON" )
+    if( PYTHONINTERP_FOUND )
+      set( _PAR_COMMAND ${PYTHON_EXECUTABLE} )
+    else()
+      message( WARNING "Requested a python test but python interpreter not found - disabling test\nPYTHON_EXECUTABLE: [${PYTHON_EXECUTABLE}]" )
+      set( _PAR_ENABLED 0 )
     endif()
-
-    if( NOT _PAR_COMMAND AND NOT _PAR_SOURCES )
-      message(FATAL_ERROR "The call to ecbuild_add_test() defines neither a COMMAND nor SOURCES, so no test can be defined or built.")
+  endif()
+
+  ### further checks
+
+  if( _PAR_ENABLED AND NOT _PAR_TARGET AND NOT _PAR_COMMAND )
+    message(FATAL_ERROR "The call to ecbuild_add_test() defines neither a TARGET nor a COMMAND.")
+  endif()
+
+  if( _PAR_ENABLED AND NOT _PAR_COMMAND AND NOT _PAR_SOURCES )
+    message(FATAL_ERROR "The call to ecbuild_add_test() defines neither a COMMAND nor SOURCES, so no test can be defined or built.")
+  endif()
+
+  if( _PAR_TYPE MATCHES "SCRIPT" AND NOT _PAR_COMMAND )
+    message(FATAL_ERROR "The call to ecbuild_add_test() defines a 'script' but doesn't specify the COMMAND.")
+  endif()
+
+  ### conditional build
+
+  if( DEFINED _PAR_CONDITION )
+    set(_target_condition_file "${_TEST_DIR}/set_${_PAR_TARGET}_condition.cmake")
+    file( WRITE  ${_target_condition_file} "  if( ")
+    foreach( term ${_PAR_CONDITION} )
+      file( APPEND ${_target_condition_file} " ${term}")
+    endforeach()
+    file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
+    include( ${_target_condition_file} )
+  else()
+    set( _${_PAR_TARGET}_condition TRUE )
+  endif()
+
+  # boost unit test linking to unit_test lib ?
+
+  if( _PAR_BOOST AND ENABLE_TESTS AND _${_PAR_TARGET}_condition )
+
+    if( HAVE_BOOST_UNIT_TEST )
+      if( BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
+        include_directories( ${ECBUILD_BOOST_HEADER_DIRS} )
+        include_directories( ${Boost_INCLUDE_DIRS}  ) # temporary until we ship Boost Unit Test with ecBuild
+      else()
+        include_directories( ${ECBUILD_BOOST_HEADER_DIRS} ${Boost_INCLUDE_DIRS} )
+      endif()
+    else()
+      ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): boost unit test framework not available - not building test")
+      set( _${_PAR_TARGET}_condition FALSE )
     endif()
 
-    if( _PAR_TYPE MATCHES "SCRIPT" AND NOT _PAR_COMMAND )
-        message(FATAL_ERROR "The call to ecbuild_add_test() defines a 'script' but doesn't specify the COMMAND.")
-    endif()
+  endif()
 
-    ### conditional build
+  ### enable the tests
 
-    if( DEFINED _PAR_CONDITION )
-        set(_target_condition_file "${CMAKE_CURRENT_BINARY_DIR}/set_${_PAR_TARGET}_condition.cmake")
-        file( WRITE  ${_target_condition_file} "  if( ")
-        foreach( term ${_PAR_CONDITION} )
-            file( APPEND ${_target_condition_file} " ${term}")
-        endforeach()
-        file( APPEND ${_target_condition_file} " )\n    set(_${_PAR_TARGET}_condition TRUE)\n  else()\n    set(_${_PAR_TARGET}_condition FALSE)\n  endif()\n")
-        include( ${_target_condition_file} )
-    else()
-        set( _${_PAR_TARGET}_condition TRUE )
+  if( ENABLE_TESTS AND _${_PAR_TARGET}_condition )
+
+    # add resources
+
+    if( DEFINED _PAR_RESOURCES )
+      ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): copying resources ${_PAR_RESOURCES}")
+      foreach( rfile ${_PAR_RESOURCES} )
+        execute_process( COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${rfile} ${_TEST_DIR} )
+      endforeach()
     endif()
 
-	# boost unit test linking to unit_test lib ?
+    # build executable
 
-	if( _PAR_BOOST AND ENABLE_TESTS AND _${_PAR_TARGET}_condition )
+    if( DEFINED _PAR_SOURCES )
 
-		if( HAVE_BOOST_UNIT_TEST )
-			if( BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
-				include_directories( ${ECBUILD_BOOST_HEADER_DIRS} )
-			else()
-				include_directories( ${ECBUILD_BOOST_HEADER_DIRS} ${Boost_INCLUDE_DIRS} )
-			endif()
-		else()
-			set( _${_PAR_TARGET}_condition FALSE )
-		endif()
+      # add include dirs if defined
+      if( DEFINED _PAR_INCLUDES )
+        list(REMOVE_DUPLICATES _PAR_INCLUDES )
+        foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
+          if( path )
+            ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): add ${path} to include_directories")
+            include_directories( ${path} )
+          else()
+            ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): ${path} not found - not adding to include_directories")
+          endif()
+        endforeach()
+      endif()
 
-	endif()
+      # add persistent layer files
+      if( DEFINED _PAR_PERSISTENT )
+        if( DEFINED PERSISTENT_NAMESPACE )
+          ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
+        else()
+          ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
+        endif()
+      endif()
 
-	### enable the tests
+      # add the test target
 
-    if( ENABLE_TESTS AND _${_PAR_TARGET}_condition )
+      add_executable( ${_PAR_TARGET} ${_PAR_SOURCES} )
 
-      # add resources
+      # add extra dependencies
+      if( DEFINED _PAR_DEPENDS)
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): add dependency on ${_PAR_DEPENDS}")
+        add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
+      endif()
 
-      if( DEFINED _PAR_RESOURCES )
-        foreach( rfile ${_PAR_RESOURCES} )
-          execute_process( COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${rfile} ${CMAKE_CURRENT_BINARY_DIR} )
+      # add the link libraries
+      if( DEFINED _PAR_LIBS )
+        list(REMOVE_DUPLICATES _PAR_LIBS )
+        list(REMOVE_ITEM _PAR_LIBS debug)
+        list(REMOVE_ITEM _PAR_LIBS optimized)
+        foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
+          if( lib )
+            ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): linking with ${lib}")
+            target_link_libraries( ${_PAR_TARGET} ${lib} )
+          else()
+            ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): ${lib} not found - not linking")
+          endif()
         endforeach()
       endif()
 
-      # build executable
-
-      if( DEFINED _PAR_SOURCES )
-
-                # add include dirs if defined
-                if( DEFINED _PAR_INCLUDES )
-                  list(REMOVE_DUPLICATES _PAR_INCLUDES )
-                  foreach( path ${_PAR_INCLUDES} ) # skip NOTFOUND
-                    if( path )
-                      include_directories( ${path} )
-                    endif()
-                  endforeach()
-                endif()
-
-                # add persistent layer files
-                if( DEFINED _PAR_PERSISTENT )
-		            if( DEFINED PERSISTENT_NAMESPACE )
-        		        ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} NAMESPACE ${PERSISTENT_NAMESPACE} )
-            		else()
-                		ecbuild_add_persistent( SRC_LIST _PAR_SOURCES FILES ${_PAR_PERSISTENT} )
-            		endif()
-                endif()
-
-                # add the test target
-
-                add_executable( ${_PAR_TARGET} ${_PAR_SOURCES} )
-
-                # add extra dependencies
-                if( DEFINED _PAR_DEPENDS)
-                  add_dependencies( ${_PAR_TARGET} ${_PAR_DEPENDS} )
-                endif()
-
-                # add the link libraries
-                if( DEFINED _PAR_LIBS )
-                  list(REMOVE_DUPLICATES _PAR_LIBS )
-                  list(REMOVE_ITEM _PAR_LIBS debug)
-                  list(REMOVE_ITEM _PAR_LIBS optimized)
-                  foreach( lib ${_PAR_LIBS} ) # skip NOTFOUND
-                    if( lib )
-                      target_link_libraries( ${_PAR_TARGET} ${lib} )
-                    else()
-                      message( WARNING "Lib ${lib} was skipped" )
-                    endif()
-                  endforeach()
-                endif()
-
-                # add test libraries
-				if( _PAR_BOOST AND BOOST_UNIT_TEST_FRAMEWORK_LINKED AND HAVE_BOOST_UNIT_TEST )
-                    target_link_libraries( ${_PAR_TARGET} ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} ${Boost_TEST_EXEC_MONITOR_LIBRARY} )
-                endif()
-
-                # add local flags
-                if( DEFINED _PAR_CFLAGS )
-                    set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
-                endif()
-                if( DEFINED _PAR_CXXFLAGS )
-                    set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
-                endif()
-                if( DEFINED _PAR_FFLAGS )
-                    set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
-                endif()
-                if( DEFINED _PAR_GENERATED )
-                    set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
-                endif()
-
-
-                # modify definitions to compilation ( -D... )
-                get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
-
-                if( DEFINED _PAR_DEFINITIONS )
-                    list( APPEND _target_defs ${_PAR_DEFINITIONS} )
-                endif()
-
-				if( _PAR_BOOST AND BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
-					list( APPEND _target_defs BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
-				endif()
-
-			    set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
-
-                # set build location to local build dir
-                # not the project base as defined for libs and execs
-                set_property( TARGET ${_PAR_TARGET} PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} )
-
-				# whatever project settings are, we always build tests with the build_rpath, not the install_rpath
-				set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
-				set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
-
-                # set linker language
-                if( DEFINED _PAR_LINKER_LANGUAGE )
-                    set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
-                endif()
-
-                # make sure target is removed before - some problems with AIX
-                get_target_property(EXE_FILENAME ${_PAR_TARGET} OUTPUT_NAME)
-                add_custom_command(
-                      TARGET ${_PAR_TARGET}
-                      PRE_BUILD
-                      COMMAND ${CMAKE_COMMAND} -E remove ${EXE_FILENAME}
-                )
-
-				set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
-				set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
-
-      endif() # _PAR_SOURCES
-
-      if( DEFINED _PAR_COMMAND AND NOT _PAR_TARGET ) # in the absence of target, we use the command as a name
-          set( _PAR_TARGET ${_PAR_COMMAND} )
+      # add test libraries
+      if( _PAR_BOOST AND BOOST_UNIT_TEST_FRAMEWORK_LINKED AND HAVE_BOOST_UNIT_TEST )
+        target_link_libraries( ${_PAR_TARGET} ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} ${Boost_TEST_EXEC_MONITOR_LIBRARY} )
       endif()
 
-      # scripts dont have actual build targets
-      # we build a phony target to trigger the dependencies
-      if( DEFINED _PAR_COMMAND AND DEFINED _PAR_DEPENDS )
+      # filter sources
+      ecbuild_separate_sources( TARGET ${_PAR_TARGET} SOURCES ${_PAR_SOURCES} )
 
-          add_custom_target( ${_PAR_TARGET}.x ALL COMMAND ${CMAKE_COMMAND} -E touch ${_PAR_TARGET}.x )
+      # add local flags
+      if( DEFINED _PAR_CFLAGS )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): use C flags ${_PAR_CFLAGS}")
+        set_source_files_properties( ${${_PAR_TARGET}_c_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_CFLAGS}" )
+      endif()
+      if( DEFINED _PAR_CXXFLAGS )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): use C++ flags ${_PAR_CFLAGS}")
+        set_source_files_properties( ${${_PAR_TARGET}_cxx_srcs} PROPERTIES COMPILE_FLAGS "${_PAR_CXXFLAGS}" )
+      endif()
+      if( DEFINED _PAR_FFLAGS )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): use Fortran flags ${_PAR_CFLAGS}")
+        set_source_files_properties( ${${_PAR_TARGET}_f_srcs}   PROPERTIES COMPILE_FLAGS "${_PAR_FFLAGS}" )
+      endif()
+      if( DEFINED _PAR_GENERATED )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): mark as generated ${_PAR_GENERATED}")
+        set_source_files_properties( ${_PAR_GENERATED} PROPERTIES GENERATED 1 )
+      endif()
 
-          add_dependencies( ${_PAR_TARGET}.x ${_PAR_DEPENDS} )
 
+      # modify definitions to compilation ( -D... )
+      get_property( _target_defs TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS )
+
+      if( DEFINED _PAR_DEFINITIONS )
+        list( APPEND _target_defs ${_PAR_DEFINITIONS} )
       endif()
 
+      if( _PAR_BOOST AND BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
+        list( APPEND _target_defs BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY )
+      endif()
 
-      # define the arguments
-      set( TEST_ARGS "" )
-      if( DEFINED _PAR_ARGS  )
-        list( APPEND TEST_ARGS ${_PAR_ARGS} )
+      if( _target_defs )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): using definitions ${_target_defs}")
+        set_property( TARGET ${_PAR_TARGET} PROPERTY COMPILE_DEFINITIONS ${_target_defs} )
       endif()
 
-      # Wrap with MPIEXEC
-      if( _PAR_MPI )
-        if( DEFINED _PAR_COMMAND )
-          set( _PAR_COMMAND ${MPIEXEC} -n ${_PAR_MPI} ${_PAR_COMMAND} )
-        else()
-          set( _PAR_COMMAND ${MPIEXEC} -n ${_PAR_MPI} ${_PAR_TARGET} )
-        endif()
+      # set build location to local build dir
+      # not the project base as defined for libs and execs
+      set_property( TARGET ${_PAR_TARGET} PROPERTY RUNTIME_OUTPUT_DIRECTORY ${_TEST_DIR} )
+
+      # whatever project settings are, we always build tests with the build_rpath, not the install_rpath
+      set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
+      set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
+
+      # set linker language
+      if( DEFINED _PAR_LINKER_LANGUAGE )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): using linker language ${_PAR_LINKER_LANGUAGE}")
+        set_property( TARGET ${_PAR_TARGET} PROPERTY LINKER_LANGUAGE ${_PAR_LINKER_LANGUAGE} )
       endif()
 
-      ### define the test
+      # make sure target is removed before - some problems with AIX
+      get_target_property(EXE_FILENAME ${_PAR_TARGET} OUTPUT_NAME)
+      add_custom_command( TARGET ${_PAR_TARGET}
+                          PRE_BUILD
+                          COMMAND ${CMAKE_COMMAND} -E remove ${EXE_FILENAME} )
 
-      if( _PAR_ENABLED ) # we can disable and still build it but not run it with 'make tests'
+      set_property( TARGET ${_PAR_TARGET} PROPERTY SKIP_BUILD_RPATH         FALSE )
+      set_property( TARGET ${_PAR_TARGET} PROPERTY BUILD_WITH_INSTALL_RPATH FALSE )
 
-          if( DEFINED _PAR_COMMAND )
-              add_test( ${_PAR_TARGET} ${_PAR_COMMAND} ${TEST_ARGS} ${_working_dir} ) # run a command as test
-          else()
-              add_test( ${_PAR_TARGET} ${_PAR_TARGET}  ${TEST_ARGS} ${_working_dir} ) # run the test that was generated
-          endif()
+    endif() # _PAR_SOURCES
 
-          # get test data
+    if( DEFINED _PAR_COMMAND AND NOT _PAR_TARGET ) # in the absence of target, we use the command as a name
+      set( _PAR_TARGET ${_PAR_COMMAND} )
+    endif()
 
-          if( _PAR_TEST_DATA )
+    # scripts dont have actual build targets
+    # we build a phony target to trigger the dependencies
+    if( DEFINED _PAR_COMMAND AND DEFINED _PAR_DEPENDS )
 
-             ecbuild_get_test_multidata( TARGET ${_PAR_TARGET}_data NAMES ${_PAR_TEST_DATA} )
+      add_custom_target( ${_PAR_TARGET}.x ALL COMMAND ${CMAKE_COMMAND} -E touch ${_PAR_TARGET}.x )
 
-             list( APPEND _PAR_TEST_DEPENDS ${_PAR_TARGET}_data )
+      add_dependencies( ${_PAR_TARGET}.x ${_PAR_DEPENDS} )
 
-          endif()
+    endif()
 
-          if( DEFINED _PAR_ENVIRONMENT )
-              set_property( TEST ${_PAR_TARGET} APPEND PROPERTY ENVIRONMENT "${_PAR_ENVIRONMENT}" )
-          endif()
 
-          if( DEFINED _PAR_WORKING_DIRECTORY )
-              set_tests_properties( ${_PAR_TARGET} PROPERTIES WORKING_DIRECTORY "${_PAR_WORKING_DIRECTORY}")
-          endif()
+    # define the arguments
+    set( TEST_ARGS "" )
+    if( DEFINED _PAR_ARGS  )
+      list( APPEND TEST_ARGS ${_PAR_ARGS} )
+    endif()
 
-          if( DEFINED _PAR_TEST_DEPENDS )
-              set_property( TEST ${_PAR_TARGET} APPEND PROPERTY DEPENDS "${_PAR_TEST_DEPENDS}" )
-          endif()
+    # Wrap with MPIEXEC
+    if( _PAR_MPI )
+      if( DEFINED _PAR_COMMAND )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): running as ${MPIEXEC} -n ${_PAR_MPI} ${_TEST_DIR}/${_PAR_COMMAND}")
+        set( _PAR_COMMAND ${MPIEXEC} -n ${_PAR_MPI} ${_TEST_DIR}/${_PAR_COMMAND} )
+      else()
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): running as ${MPIEXEC} -n ${_PAR_MPI} ${_TEST_DIR}/${_PAR_TARGET}")
+        set( _PAR_COMMAND ${MPIEXEC} -n ${_PAR_MPI} ${_TEST_DIR}/${_PAR_TARGET} )
+      endif()
+    endif()
+
+    ### define the test
+
+    if( _PAR_ENABLED ) # we can disable and still build it but not run it with 'make tests'
+
+      if( DEFINED _PAR_COMMAND )
+        add_test( ${_PAR_TARGET} ${_PAR_COMMAND} ${TEST_ARGS} ${_working_dir} ) # run a command as test
+      else()
+        add_test( ${_PAR_TARGET} ${_PAR_TARGET}  ${TEST_ARGS} ${_working_dir} ) # run the test that was generated
+      endif()
 
+      # get test data
+
+      if( _PAR_TEST_DATA )
+
+        ecbuild_get_test_multidata( TARGET ${_PAR_TARGET}_data NAMES ${_PAR_TEST_DATA} )
+
+        list( APPEND _PAR_TEST_DEPENDS ${_PAR_TARGET}_data )
+
+      endif()
+
+      if( DEFINED _PAR_ENVIRONMENT )
+        set_property( TEST ${_PAR_TARGET} APPEND PROPERTY ENVIRONMENT "${_PAR_ENVIRONMENT}" )
       endif()
 
-      # add to the overall list of tests
-      list( APPEND ECBUILD_ALL_TESTS ${_PAR_TARGET} )
-      list( REMOVE_DUPLICATES ECBUILD_ALL_TESTS )
-      set( ECBUILD_ALL_TESTS ${ECBUILD_ALL_TESTS} CACHE INTERNAL "" )
+      if( DEFINED _PAR_WORKING_DIRECTORY )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): set working directory to ${_PAR_WORKING_DIRECTORY}")
+        set_tests_properties( ${_PAR_TARGET} PROPERTIES WORKING_DIRECTORY "${_PAR_WORKING_DIRECTORY}")
+      endif()
+
+      if( DEFINED _PAR_TEST_DEPENDS )
+        ecbuild_debug("ecbuild_add_test(${_PAR_TARGET}): set test dependencies to ${_PAR_TEST_DEPENDS}")
+        set_property( TEST ${_PAR_TARGET} APPEND PROPERTY DEPENDS "${_PAR_TEST_DEPENDS}" )
+      endif()
+
+    endif()
+
+    # add to the overall list of tests
+    list( APPEND ECBUILD_ALL_TESTS ${_PAR_TARGET} )
+    list( REMOVE_DUPLICATES ECBUILD_ALL_TESTS )
+    set( ECBUILD_ALL_TESTS ${ECBUILD_ALL_TESTS} CACHE INTERNAL "" )
 
-    endif() # _condition
+  endif() # _condition
 
-    # finally mark project files
-    ecbuild_declare_project_files( ${_PAR_SOURCES} )
+  # finally mark project files
+  ecbuild_declare_project_files( ${_PAR_SOURCES} )
 
 endmacro( ecbuild_add_test )
diff --git a/cmake/ecbuild_append_to_rpath.cmake b/cmake/ecbuild_append_to_rpath.cmake
index 6868e50..db1efb4 100644
--- a/cmake/ecbuild_append_to_rpath.cmake
+++ b/cmake/ecbuild_append_to_rpath.cmake
@@ -6,32 +6,46 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to append paths to rpath
-
-# if dir is absolute, it simply appends
-# if dir is relative,
-#    then it will try to make it relative to the executables
-#    else it will fallback to making it absolute by prepending the install path
+##############################################################################
+#.rst:
+#
+# ecbuild_append_to_rpath
+# =======================
+#
+# Append paths to the rpath. ::
+#
+#   ecbuild_append_to_rpath( RPATH_DIRS )
+#
+# ``RPATH_DIRS`` is a list of directories to append to ``CMAKE_INSTALL_RPATH``.
+#
+# * If a directory is absolute, simply append it.
+# * If a directory is relative, build a platform-dependent relative path
+#   (using ``@loader_path`` on Mac OSX, ``$ORIGIN`` on Linux and Solaris)
+#   or fall back to making it absolute by prepending the install prefix.
+#
+##############################################################################
 
 function( _path_append var path )
 	if( "${${var}}" STREQUAL "" )
 		set( ${var} "${path}" PARENT_SCOPE )
 	else()
-		set( ${var} "${${var}}:${path}" PARENT_SCOPE )
+		list( FIND ${var} ${path} _found )
+		if( _found EQUAL "-1" )
+			set( ${var} "${${var}}:${path}" PARENT_SCOPE )
+		endif()
 	endif()
 endfunction()
 
 macro( ecbuild_append_to_rpath RPATH_DIRS )
    
    if( NOT ${ARGC} EQUAL 1 )
-	   message( SEND_ERROR "ecbuild_append_to_rpath takes 1 argument")
+     message( SEND_ERROR "ecbuild_append_to_rpath takes 1 argument")
    endif()
 
    foreach( RPATH_DIR ${RPATH_DIRS} )
      
 		if( NOT ${RPATH_DIR} STREQUAL "" )
-        
+
 			file( TO_CMAKE_PATH ${RPATH_DIR} RPATH_DIR ) # sanitize the path
 
 			if( IS_ABSOLUTE ${RPATH_DIR} )
@@ -48,6 +62,7 @@ macro( ecbuild_append_to_rpath RPATH_DIRS )
 						set( CMAKE_INSTALL_NAME_DIR "@loader_path/${RPATH_DIR}" )
 					endif()
 					_path_append( CMAKE_INSTALL_RPATH "@loader_path/${RPATH_DIR}" )
+
 					set( _done 1 )
 
 				endif()
diff --git a/cmake/ecbuild_bundle.cmake b/cmake/ecbuild_bundle.cmake
index 2a75e84..2d9b779 100644
--- a/cmake/ecbuild_bundle.cmake
+++ b/cmake/ecbuild_bundle.cmake
@@ -1,15 +1,13 @@
-# Manages an external git repository
-# Usage:
-# git(DIR <directory> URL <giturl> [BRANCH <gitbranch>] [TAG <gittag>] [UPDATE] )
+# (C) Copyright 1996-2015 ECMWF.
 #
-# Arguments:
-#  - DIR: directory name where repo will be cloned to
-#  - URL: location of origin git repository
-#  - BRANCH (optional): Branch to clone
-#  - TAG (optional): Tag or commit-id to checkout
-#  - UPDATE (optional) : Option to try to update every cmake run
-#  - NOREMOTE (optional) : Option to avoid remote operations that require network
-#                          changes to tags that havent been fetched might fail
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# Set policies
+include( ecbuild_policies NO_POLICY_SCOPE )
 
 macro( debug_here VAR )
   message( STATUS " >>>>> ${VAR} [${${VAR}}]")
@@ -17,222 +15,18 @@ endmacro()
 
 include(CMakeParseArguments)
 
-set( ECBUILD_GIT  ON  CACHE BOOL "Turn on/off ecbuild_git() function" )
-
-if( ECBUILD_GIT )
-
-  find_package(Git)
-
-  set( ECMWF_USER $ENV{USER} CACHE STRING "ECMWF git user" )
-  set( ECMWF_GIT  SSH        CACHE STRING "ECMWF git protocol" )
-
-  set( ECMWF_GIT_SSH   "ssh://git@software.ecmwf.int:7999"                  CACHE INTERNAL "ECMWF ssh address" )
-  set( ECMWF_GIT_HTTPS "https://${ECMWF_USER}@software.ecmwf.int/stash/scm" CACHE INTERNAL "ECMWF https address" )
-
-  if( ECMWF_GIT MATCHES "[Ss][Ss][Hh]" )
-    set( ECMWF_GIT_ADDRESS ${ECMWF_GIT_SSH} CACHE INTERNAL "" )
-  else()
-    set( ECMWF_GIT_ADDRESS ${ECMWF_GIT_HTTPS} CACHE INTERNAL "" )
-  endif()
-  
-endif()
-
-macro( ecbuild_git )
-
-  set( options UPDATE NOREMOTE )
-  set( single_value_args PROJECT DIR URL TAG BRANCH )
-  set( multi_value_args )
-  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${_FIRST_ARG} ${ARGN} )
-
-  if( DEFINED _PAR_BRANCH AND DEFINED _PAR_TAG )
-    message( FATAL_ERROR "Cannot defined both BRANCH and TAG in macro ecbuild_git" )
-  endif()
-
-  if( _PAR_UPDATE AND _PAR_NOREMOTE )
-    message( FATAL_ERROR "Cannot pass both NOREMOTE and UPDATE in macro ecbuild_git" )
-  endif()
-
-  if(_PAR_UNPARSED_ARGUMENTS)
-    message(FATAL_ERROR "Unknown keywords given to ecbuild_git(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-  endif()
-
-  if( ECBUILD_GIT )
-
-    set( _needs_switch 0 )
-
-    get_filename_component( ABS_PAR_DIR "${_PAR_DIR}" ABSOLUTE )
-    get_filename_component( PARENT_DIR  "${_PAR_DIR}/.." ABSOLUTE )
-
-    ### clone if no directory
-
-    if( NOT EXISTS "${_PAR_DIR}" )
-
-      message( STATUS "Cloning ${_PAR_PROJECT} from ${_PAR_URL} into ${_PAR_DIR}...")
-      execute_process(
-        COMMAND ${GIT_EXECUTABLE} "clone" ${_PAR_URL} ${clone_args} ${_PAR_DIR} "-q"
-        RESULT_VARIABLE nok ERROR_VARIABLE error
-        WORKING_DIRECTORY "${PARENT_DIR}")
-      if(nok)
-        message(FATAL_ERROR "${_PAR_DIR} git clone failed: ${error}\n")
-      endif()
-      message( STATUS "${_PAR_DIR} retrieved.")
-      set( _needs_switch 1 )
-
-    endif()
-
-    ### check current tag and sha1
-
-    if( IS_DIRECTORY "${_PAR_DIR}/.git" )
-
-        execute_process(
-          COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
-          OUTPUT_VARIABLE _sha1 RESULT_VARIABLE nok ERROR_VARIABLE error OUTPUT_STRIP_TRAILING_WHITESPACE
-          WORKING_DIRECTORY "${ABS_PAR_DIR}" )
-        if(nok)
-          message(STATUS "git rev-parse HEAD on ${_PAR_DIR} failed:\n ${error}")
-        endif()
-
-        execute_process(
-          COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
-          OUTPUT_VARIABLE _current_branch RESULT_VARIABLE nok ERROR_VARIABLE error OUTPUT_STRIP_TRAILING_WHITESPACE
-          WORKING_DIRECTORY "${ABS_PAR_DIR}" )
-        if( nok OR _current_branch STREQUAL "" )
-          message(STATUS "git rev-parse --abbrev-ref HEAD on ${_PAR_DIR} failed:\n ${error}")
-        endif()
-
-        #message(STATUS "git describe --exact-match --abbrev=0 @ ${ABS_PAR_DIR}")
-        execute_process(
-          COMMAND ${GIT_EXECUTABLE} describe --exact-match --abbrev=0
-          OUTPUT_VARIABLE _current_tag RESULT_VARIABLE nok ERROR_VARIABLE error
-          OUTPUT_STRIP_TRAILING_WHITESPACE  ERROR_STRIP_TRAILING_WHITESPACE
-          WORKING_DIRECTORY "${ABS_PAR_DIR}" )
-
-        if( error MATCHES "no tag exactly matches" OR error MATCHES "No names found" )
-          unset( _current_tag )
-        else()
-          if( nok )
-            message(STATUS "git describe --exact-match --abbrev=0 on ${_PAR_DIR} failed:\n ${error}")
-          endif()
-        endif()
-
-        if( NOT _current_tag ) # try nother method
-          #message(STATUS "git name-rev --tags --name-only @ ${ABS_PAR_DIR}")
-          execute_process(
-            COMMAND ${GIT_EXECUTABLE} name-rev --tags --name-only ${_sha1}
-            OUTPUT_VARIABLE _current_tag RESULT_VARIABLE nok ERROR_VARIABLE error OUTPUT_STRIP_TRAILING_WHITESPACE
-            WORKING_DIRECTORY "${ABS_PAR_DIR}" )
-          if( nok OR _current_tag STREQUAL "" )
-            message(STATUS "git name-rev --tags --name-only on ${_PAR_DIR} failed:\n ${error}")
-          endif()
-        endif()
-
-    endif()
-
-    if( DEFINED _PAR_BRANCH AND NOT "${_current_branch}" STREQUAL "${_PAR_BRANCH}" )
-      set( _needs_switch 1 )
-    endif()
-
-    if( DEFINED _PAR_TAG AND NOT "${_current_tag}" STREQUAL "${_PAR_TAG}" )
-      set( _needs_switch 1 )
-    endif()
-
-    if( DEFINED _PAR_BRANCH AND _PAR_UPDATE AND NOT _PAR_NOREMOTE )
-
-      add_custom_target( git_update_${_PAR_PROJECT}
-                         COMMAND "${GIT_EXECUTABLE}" pull -q
-                         WORKING_DIRECTORY "${ABS_PAR_DIR}"
-                         COMMENT "git pull of branch ${_PAR_BRANCH} on ${_PAR_DIR}" )
-
-      set( git_update_targets "git_update_${_PAR_PROJECT};${git_update_targets}" )
-
-    endif()
-
-    ### updates
-
-    if( _needs_switch AND IS_DIRECTORY "${_PAR_DIR}/.git" )
-
-      # debug_here( ABS_PAR_DIR )
-      # debug_here( _sha1 )
-      # debug_here( _current_branch )
-      # debug_here( _current_tag )
-      # debug_here( _PAR_TAG )
-      # debug_here( _PAR_BRANCH )
-      # debug_here( _needs_switch )
-      # debug_here( _PAR_UPDATE )
-
-      if( DEFINED _PAR_BRANCH )
-        set ( _gitref ${_PAR_BRANCH} )
-        message(STATUS "Updating ${_PAR_PROJECT} to head of BRANCH ${_PAR_BRANCH}...")
-      else()
-        message(STATUS "Updating ${_PAR_PROJECT} to TAG ${_PAR_TAG}...")
-        set ( _gitref ${_PAR_TAG} )
-      endif()
-
-      # fetching latest tags and branches
-
-      if( NOT _PAR_NOREMOTE )
-
-          message(STATUS "git fetch --all @ ${ABS_PAR_DIR}")
-          execute_process(COMMAND "${GIT_EXECUTABLE}" fetch --all -q
-            RESULT_VARIABLE nok ERROR_VARIABLE error
-            WORKING_DIRECTORY "${ABS_PAR_DIR}")
-          if(nok)
-            message(STATUS "git fetch --all in ${_PAR_DIR} failed:\n ${error}")
-          endif()
-
-          message(STATUS "git fetch --all --tags @ ${ABS_PAR_DIR}")
-          execute_process(COMMAND "${GIT_EXECUTABLE}" fetch --all --tags -q
-            RESULT_VARIABLE nok ERROR_VARIABLE error
-            WORKING_DIRECTORY "${ABS_PAR_DIR}")
-          if(nok)
-            message(STATUS "git fetch --all --tags in ${_PAR_DIR} failed:\n ${error}")
-          endif()
-
-      else()
-          message(STATUS "${_PAR_DIR} marked NOREMOTE : Skipping git fetch")
-      endif()
-
-      # checking out gitref
-
-      message(STATUS "git checkout ${_gitref} @ ${ABS_PAR_DIR}")
-      execute_process(COMMAND "${GIT_EXECUTABLE}" checkout -q "${_gitref}"
-        RESULT_VARIABLE nok ERROR_VARIABLE error
-        WORKING_DIRECTORY "${ABS_PAR_DIR}")
-      if(nok)
-        message(FATAL_ERROR "git checkout ${_gitref} on ${_PAR_DIR} failed:\n ${error}")
-      endif()
-
-      if( DEFINED _PAR_BRANCH AND _PAR_UPDATE ) #############################################################################
-
-            execute_process(COMMAND "${GIT_EXECUTABLE}" pull -q
-              RESULT_VARIABLE nok ERROR_VARIABLE error
-              WORKING_DIRECTORY "${ABS_PAR_DIR}")
-            if(nok)
-              message(STATUS "git pull of branch ${_PAR_BRANCH} on ${_PAR_DIR} failed:\n ${error}")
-            endif()
-
-      endif() ####################################################################################
-
-    endif( _needs_switch AND IS_DIRECTORY "${_PAR_DIR}/.git" )
-
-  endif( ECBUILD_GIT )
-
-endmacro()
-
-########################################################################################################################
-
-macro( ecmwf_stash )
+include(ecbuild_git)
 
-  set( options )
-  set( single_value_args STASH )
-  set( multi_value_args )
-  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${_FIRST_ARG} ${ARGN} )
-
-  ecbuild_git( URL "${ECMWF_GIT_ADDRESS}/${_PAR_STASH}.git" ${_PAR_UNPARSED_ARGUMENTS} )
-
-endmacro()
-
-########################################################################################################################
+##############################################################################
+#.rst:
+#
+# ecbuild_bundle_initialize
+# =========================
+#
+# Initialise the ecBuild environment for a bundle. *Must* be called *before*
+# any call to ecbuild_bundle.
+#
+##############################################################################
 
 macro( ecbuild_bundle_initialize )
 
@@ -258,21 +52,105 @@ macro( ecbuild_bundle_initialize )
 
 endmacro()
 
-########################################################################################################################
+##############################################################################
+#.rst:
+#
+# ecbuild_bundle
+# ==============
+#
+# Declare a subproject to be built as part of this bundle. ::
+#
+#   ecbuild_bundle( PROJECT <name>
+#                   STASH <repository> | GIT <giturl>
+#                   [ BRANCH <gitbranch> | TAG <gittag> ]
+#                   [ UPDATE | NOREMOTE ] )
+#                   [ MANUAL ] )
+#
+# Options
+# -------
+#
+# PROJECT : required
+#   project name for the Git repository to be managed
+#
+# STASH : cannot be combined with GIT, either is required
+#   Stash repository in the form <project>/<repository>
+#
+# URL : cannot be combined with STASH, either is required
+#   Git URL of the remote repository to clone (see ``git help clone``)
+#
+# BRANCH : optional, cannot be combined with TAG
+#   Git branch to check out
+#
+# TAG : optional, cannot be combined with BRANCH
+#   Git tag or commit id to check out
+#
+# UPDATE : optional, requires BRANCH, cannot be combined with NOREMOTE
+#   Create a CMake target update to fetch changes from the remote repository
+#
+# NOREMOTE : optional, cannot be combined with UPDATE
+#   Do not fetch changes from the remote repository
+#
+# MANUAL : optional
+#   Do not automatically switch branches or tags
+#
+# Usage
+# -----
+#
+# A bundle is used to build a number of projects together. Each subproject
+# needs to be declared with a call to ecbuild_bundle, where the order of
+# projects is important and needs to respect dependencies: if project B
+# depends on project A, A should be listed before B in the bundle.
+#
+# The first time a bundle is built, the sources of all subprojects are cloned
+# into directories named according to project in the *source* tree of the
+# bundle (which means these directories should be added to ``.gitignore``).
+#
+# Subprojects are configured and built in order. Due to being added as a
+# subproject, the usual project discovery mechanism (i.e. locating and
+# importing a ``<project>-config.cmake`` file) is not used. Also there are no
+# ``<project>-config.cmake`` files being generated for individual subprojects.
+# However there *are* package-config files being generated for each library.
+#
+# To switch off a subproject when building a bundle, set the CMake variable
+# ``BUNDLE_SKIP_<PNAME>`` where ``PNAME`` is the capitalised project name.
+#
+##############################################################################
 
 macro( ecbuild_bundle )
 
   set( options )
-  set( single_value_args PROJECT )
+  set( single_value_args PROJECT STASH GIT )
   set( multi_value_args )
   cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${_FIRST_ARG} ${ARGN} )
 
-  ecmwf_stash( PROJECT ${_PAR_PROJECT} DIR ${PROJECT_SOURCE_DIR}/${_PAR_PROJECT} ${_PAR_UNPARSED_ARGUMENTS} )
+  string(TOUPPER "${_PAR_PROJECT}" PNAME)
+
+  if( BUNDLE_SKIP_${PNAME} )
+      message( STATUS "Skipping bundle project ${PNAME}" )
+  else()
+
+      if( _PAR_STASH )
+          ecmwf_stash( PROJECT ${_PAR_PROJECT} DIR ${PROJECT_SOURCE_DIR}/${_PAR_PROJECT} STASH ${_PAR_STASH} ${_PAR_UNPARSED_ARGUMENTS} )
+      elseif( _PAR_GIT )
+          ecbuild_git( PROJECT ${_PAR_PROJECT} DIR ${PROJECT_SOURCE_DIR}/${_PAR_PROJECT} URL ${_PAR_GIT} ${_PAR_UNPARSED_ARGUMENTS} )
+      endif()
 
-  ecbuild_use_package( PROJECT ${_PAR_PROJECT} )
+      ecbuild_use_package( PROJECT ${_PAR_PROJECT} )
+  endif()
 
 endmacro()
 
+##############################################################################
+#.rst:
+#
+# ecbuild_bundle_finalize
+# =======================
+#
+# Finalise the ecBuild environment for a bundle. *Must* be called *after* the
+# last call to ecbuild_bundle.
+#
+##############################################################################
+
 macro( ecbuild_bundle_finalize )
 
   add_custom_target( update DEPENDS ${git_update_targets} )
diff --git a/cmake/ecbuild_cache.cmake b/cmake/ecbuild_cache.cmake
index af12cf1..2752392 100644
--- a/cmake/ecbuild_cache.cmake
+++ b/cmake/ecbuild_cache.cmake
@@ -6,6 +6,30 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
+##############################################################################
+#.rst:
+#
+# ecBuild Cache
+# =============
+#
+# During initialisation, ecBuild introspects the compiler and operating system
+# and performs a number of checks. The result of these is written to a
+# dedicated ``ecbuild-cache.cmake`` file in the build tree. This cache may be
+# used to speed up subsequent *clean* builds i.e. those where no CMakeCache.txt
+# exists yet.
+#
+# To use the ecBuild cache, configure with ``-DECBUILD_CACHE=<cache-file>``,
+# where ``<cache-file>`` is the path to an existing ``ecbuild-cache.cmake``.
+#
+# .. note ::
+#
+#   The ecBuild cache is specific to compiler *and* operating system. Do *not*
+#   attempt to use a cache file created on a different machine or with a
+#   different compiler!
+#
+##############################################################################
+
+# Prepare the cache and clobber any existing ecbuild-cache.cmake
 macro( ecbuild_prepare_cache )
     include( CheckSymbolExists )
     include( CheckIncludeFiles )
@@ -16,7 +40,7 @@ macro( ecbuild_prepare_cache )
     file(WRITE ${ecbuild_cache_file} "# ecbuild cache file\n\n")    
 endmacro()
 
-
+# Buffer the CMake variable var to be written to the ecBuild cache
 function( ecbuild_cache_var var )
   if( NOT ${var} )
     set( ${var} 0 )
@@ -24,6 +48,7 @@ function( ecbuild_cache_var var )
   set( ECBUILD_CACHE_BUFFER "${ECBUILD_CACHE_BUFFER}set( ${var} ${${var}} )\n" CACHE INTERNAL "Cache buffer" )
 endfunction()
 
+# Call check_symbol_exists only if the output is not defined yet
 function( ecbuild_cache_check_symbol_exists symbol includes output )
   if( NOT DEFINED ${output} )
     check_symbol_exists( ${symbol} ${includes} ${output} )
@@ -31,6 +56,7 @@ function( ecbuild_cache_check_symbol_exists symbol includes output )
   ecbuild_cache_var( ${output} )
 endfunction()
 
+# Call check_include_files only if the output is not defined yet
 function( ecbuild_cache_check_include_files includes output )
   if( NOT DEFINED ${output} )
     check_include_files( ${includes} ${output} )
@@ -38,6 +64,7 @@ function( ecbuild_cache_check_include_files includes output )
   ecbuild_cache_var( ${output} )
 endfunction()
 
+# Call check_c_source_compiles only if the output is not defined yet
 function( ecbuild_cache_check_c_source_compiles source output )
   if( NOT DEFINED ${output} )
     check_c_source_compiles( "${source}" ${output} )
@@ -45,6 +72,7 @@ function( ecbuild_cache_check_c_source_compiles source output )
   ecbuild_cache_var( ${output} )
 endfunction()
 
+# Call check_cxx_source_compiles only if the output is not defined yet
 function( ecbuild_cache_check_cxx_source_compiles source output )
   if( NOT DEFINED ${output} )
     check_cxx_source_compiles( "${source}" ${output} )
@@ -52,6 +80,7 @@ function( ecbuild_cache_check_cxx_source_compiles source output )
   ecbuild_cache_var( ${output} )
 endfunction()
 
+# Call check_type_size only if the output is not defined yet
 function( ecbuild_cache_check_type_size type output )
   if( NOT DEFINED ${output} )
     check_type_size( "${type}" ${output} )
@@ -59,7 +88,8 @@ function( ecbuild_cache_check_type_size type output )
   ecbuild_cache_var( ${output} )
 endfunction()
 
+# Flush the ecBuild cache to disk and reset the buffer
 function( ecbuild_flush_cache )
   file( APPEND ${ecbuild_cache_file} "${ECBUILD_CACHE_BUFFER}" )
   set( ECBUILD_CACHE_BUFFER "" CACHE INTERNAL "Cache buffer" )
-endfunction()
\ No newline at end of file
+endfunction()
diff --git a/cmake/ecbuild_check_c_source.cmake b/cmake/ecbuild_check_c_source.cmake
index 12a26c1..4460455 100644
--- a/cmake/ecbuild_check_c_source.cmake
+++ b/cmake/ecbuild_check_c_source.cmake
@@ -7,7 +7,48 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro that runs the given C code and returns its output
+#.rst:
+#
+# ecbuild_check_c_source_return
+# =============================
+#
+# Compile and run a given C source code and return its output. ::
+#
+#   ecbuild_check_c_source_return( <source>
+#                                  VAR <name>
+#                                  OUTPUT <name>
+#                                  [ INCLUDES <path1> [ <path2> ... ] ]
+#                                  [ LIBS <library1> [ <library2> ... ] ]
+#                                  [ DEFINITIONS <definition1> [ <definition2> ... ] ] )
+#
+# Options
+# -------
+#
+# VAR : required
+#   name of the check and name of the CMake variable to write result to
+#
+# OUTPUT : required
+#   name of CMake variable to write the output to
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# Usage
+# -----
+#
+# This will write the given source to a .c file and compile and run it with
+# try_run. If successful, ``${VAR}`` is set to 1 and ``${OUTPUT}`` is set to
+# the output of the successful run in the CMake cache.
+#
+# The check will not run if ``${VAR}`` is defined (e.g. from ecBuild cache).
+#
+##############################################################################
 
 macro( ecbuild_check_c_source_return SOURCE )
 
@@ -48,7 +89,7 @@ macro( ecbuild_check_c_source_return SOURCE )
         if( _PAR_INCLUDES )
             list( APPEND __add_incs ${_PAR_INCLUDES} )
         endif()
-		if( __add_incs )
+        if( __add_incs )
             set(CHECK_C_SOURCE_COMPILES_ADD_INCLUDES "-DINCLUDE_DIRECTORIES:STRING=${__add_incs}")
         endif()
     
@@ -113,9 +154,29 @@ macro( ecbuild_check_c_source_return SOURCE )
 endmacro()
 
 ##############################################################################
-# macro that only adds a c flag if compiler supports it
+#.rst:
+#
+# ecbuild_add_c_flags
+# ===================
+#
+# Add C compiler flags to CMAKE_C_FLAGS only if supported by the compiler. ::
+#
+#   ecbuild_add_c_flags( <flag1> [ <flag2> ... ]
+#                        [ BUILD <build> ]
+#                        [ NAME <name> ] )
+#
+# Options
+# -------
+#
+# BUILD : optional
+#   add flags to ``CMAKE_C_FLAGS_<build>`` instead of ``CMAKE_C_FLAGS``
+#
+# NAME : optional
+#   name of the check (if omitted, checks are enumerated)
+#
+##############################################################################
 
-macro( cmake_add_c_flags m_c_flags )
+macro( ecbuild_add_c_flags m_c_flags )
 
   set( _flags ${m_c_flags} )
 
@@ -159,3 +220,7 @@ macro( cmake_add_c_flags m_c_flags )
   unset( _flag_ok )
 endmacro()
 
+macro( cmake_add_c_flags m_c_flags )
+  message( DEPRECATION " cmake_add_c_flags is deprecated, use ecbuild_add_c_flags instead." )
+  ecbuild_add_c_flags( ${m_c_flags} )
+endmacro()
diff --git a/cmake/ecbuild_check_compiler.cmake b/cmake/ecbuild_check_compiler.cmake
index 406f1d2..4333abd 100644
--- a/cmake/ecbuild_check_compiler.cmake
+++ b/cmake/ecbuild_check_compiler.cmake
@@ -81,7 +81,6 @@ if( CMAKE_CXX_COMPILER_LOADED AND ENABLE_OS_TESTS )
     # check for __FUNCTION__
     ecbuild_cache_check_cxx_source_compiles( "#include <iostream>\nint main(int argc, char* argv[]) { std::cout << __FUNCTION__ << std::endl; }"
       EC_HAVE_FUNCTION_DEF )
-    
 
     # check for c++ abi, usually present in GNU compilers
     ecbuild_cache_check_cxx_source_compiles( "#include <cxxabi.h>\n int main() { char * type; int status; char * r = abi::__cxa_demangle(type, 0, 0, &status); }"
@@ -94,7 +93,7 @@ if( CMAKE_CXX_COMPILER_LOADED AND ENABLE_OS_TESTS )
     # check for sstream
     ecbuild_cache_check_cxx_source_compiles( "#include <sstream>\nint main() { std::stringstream s; }"
 	  EC_HAVE_CXX_SSTREAM )
- 
+
 endif()
 
 ############################################################################################
@@ -102,23 +101,23 @@ endif()
 
 if( CMAKE_COMPILER_IS_GNUCC )
 
-    cmake_add_c_flags("-pipe") # use pipe for faster compilation
+    ecbuild_add_c_flags("-pipe") # use pipe for faster compilation
 
     if( ENABLE_WARNINGS )
-        cmake_add_c_flags("-Wall")
-        cmake_add_c_flags("-pedantic")
-        #    cmake_add_c_flags("-Wextra")
+        ecbuild_add_c_flags("-Wall")
+        # ecbuild_add_c_flags("-pedantic")
+        # ecbuild_add_c_flags("-Wextra")
     endif()
 
 endif()
 
 if( CMAKE_COMPILER_IS_GNUCXX )
 
-   cmake_add_cxx_flags("-pipe") # use pipe for faster compilation
+   ecbuild_add_cxx_flags("-pipe") # use pipe for faster compilation
 
     if( ENABLE_WARNINGS )
-        cmake_add_cxx_flags("-Wall")
-        #    cmake_add_cxx_flags("-Wextra")
+        ecbuild_add_cxx_flags("-Wall")
+        #    ecbuild_add_cxx_flags("-Wextra")
     endif()
 
 endif()
@@ -139,3 +138,14 @@ endif()
 if( "${CMAKE_Fortran_COMPILER_ID}" STREQUAL "Cray" )
   set(CMAKE_Fortran_LINK_EXECUTABLE "<CMAKE_Fortran_COMPILER> <CMAKE_Fortran_LINK_FLAGS> <LINK_FLAGS> <FLAGS> <OBJECTS>  -o <TARGET> <LINK_LIBRARIES> -Wl,-Bdynamic" )
 endif()
+
+############################################################################################
+# Fortran compiler specific flags
+# if( NOT HAVE_SINGLE_PRECISION )
+#  if(CMAKE_Fortran_COMPILER_ID STREQUAL "PGI")
+#      ecbuild_add_fortran_flags("-r8")
+#  elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
+#      # NOTE that if we add -fdefault-real-8 then we NEED -fdefault-double-8 to avoid quadmath
+#      ecbuild_add_fortran_flags("-fdefault-real-8 -fdefault-double-8")
+#  endif()
+# endif()
diff --git a/cmake/ecbuild_check_cxx11.cmake b/cmake/ecbuild_check_cxx11.cmake
index ef1b24e..51c5dc6 100644
--- a/cmake/ecbuild_check_cxx11.cmake
+++ b/cmake/ecbuild_check_cxx11.cmake
@@ -6,9 +6,33 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to check for cxx11 features
-# uses macros from the project github.com/UCL/GreatCMakeCookOff
+##############################################################################
+#.rst:
+#
+# ecbuild_check_cxx11
+# ===================
+#
+# Check for C++11 features. ::
+#
+#   ecbuild_check_cxx11( [ FEATURES <feature1> [ <feature2> ... ] ]
+#                        [ REQUIRED <feature1> [ <feature2> ... ] ]
+#                        [ PRINT ] )
+#
+# This function uses macros from http://github.com/UCL/GreatCMakeCookOff
+#
+# Options
+# -------
+#
+# FEATURES : optional, checks for all features if omitted
+#   list of features to check for
+#
+# REQUIRED : optional
+#   list of required features to check for
+#
+# PRINT : optional
+#   print a summary of features check for, found and not found
+#
+##############################################################################
 
 function( ecbuild_check_cxx11 )
 
@@ -28,7 +52,15 @@ function( ecbuild_check_cxx11 )
 
 	cxx11_find_all_features( ALL_FEATURES ) # list all available features to check
 
-	if( NOT _p_FEATURES AND NOT _p_REQUIRED ) # no input, then searhc for all features
+	# Save CXX flags
+	set( CXX_FLAGS_SNASHOT ${CMAKE_CXX_FLAGS} )
+
+	# Add C++11 flags
+	include( ${ECBUILD_MACROS_DIR}/ecbuild_get_cxx11_flags.cmake )
+	ecbuild_get_cxx11_flags( CXX11_FLAGS )
+	set( CMAKE_CXX_FLAGS "${CXX11_FLAGS} ${CMAKE_CXX_FLAGS}" )
+
+	if( NOT _p_FEATURES AND NOT _p_REQUIRED ) # no input, then search for all features
 
 		cxx11_feature_check()
 
@@ -44,7 +76,16 @@ function( ecbuild_check_cxx11 )
 
 	endif()
 
-	foreach( f ${ALL_FEATURES} )
+	# Restore CXX flags
+	set( CMAKE_CXX_FLAGS ${CXX_FLAGS_SNAPSHOT} )
+
+	if( _p_FEATURES OR _p_REQUIRED )
+		set( CXX11_CHECKED_FEATURES ${_p_FEATURES} ${_p_REQUIRED} )
+	else()
+		set( CXX11_CHECKED_FEATURES ${ALL_FEATURES} )
+	endif()
+
+	foreach( f ${CXX11_CHECKED_FEATURES} )
 		# message( "HAS_CXX11_${FEAT}" )
 		string( TOUPPER ${f} FEAT )
 		if( HAS_CXX11_${FEAT} )
@@ -54,13 +95,38 @@ function( ecbuild_check_cxx11 )
 		endif()
 	endforeach()
 
+  if( CXX11_CHECKED_FEATURES )
+    list( SORT CXX11_CHECKED_FEATURES )
+	endif()
+	if( CXX11_SUPPORTED_FEATURES )
+		list( SORT CXX11_SUPPORTED_FEATURES )
+	endif()
+	if( CXX11_NOT_SUPPORTED_FEATURES )
+		list( SORT CXX11_NOT_SUPPORTED_FEATURES )
+	endif()
+
+	set( CXX11_CHECKED_FEATURES       ${CXX11_CHECKED_FEATURES}       PARENT_SCOPE )
 	set( CXX11_SUPPORTED_FEATURES     ${CXX11_SUPPORTED_FEATURES}     PARENT_SCOPE )
 	set( CXX11_NOT_SUPPORTED_FEATURES ${CXX11_NOT_SUPPORTED_FEATURES} PARENT_SCOPE )
 
 	if( _p_PRINT )
+		if( CXX11_CHECKED_FEATURES )
+			join( CXX11_CHECKED_FEATURES " " CXX11_CHECKED_FEATURES_STR )
+			message( STATUS "Checked C++11 features: ${CXX11_CHECKED_FEATURES_STR}" )
+		else()
+			message( STATUS "Checked no C++11 features" )
+		endif()
 		if( CXX11_SUPPORTED_FEATURES )
 			join( CXX11_SUPPORTED_FEATURES " " CXX11_SUPPORTED_FEATURES_STR )
 			message( STATUS "Found C++11 features: ${CXX11_SUPPORTED_FEATURES_STR}" )
+		else()
+			message( STATUS "Found no C++11 features" )
+		endif()
+		if( CXX11_NOT_SUPPORTED_FEATURES )
+			join( CXX11_NOT_SUPPORTED_FEATURES " " CXX11_NOT_SUPPORTED_FEATURES_STR )
+			message( STATUS "Not found C++11 features: ${CXX11_NOT_SUPPORTED_FEATURES_STR}" )
+		else()
+			message( STATUS "Found all checked C++11 features" )
 		endif()
 	endif()
 
diff --git a/cmake/ecbuild_check_cxx_source.cmake b/cmake/ecbuild_check_cxx_source.cmake
index a48ae5a..ee3588b 100644
--- a/cmake/ecbuild_check_cxx_source.cmake
+++ b/cmake/ecbuild_check_cxx_source.cmake
@@ -7,7 +7,48 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro that runs the given C++ code and returns its output
+#.rst:
+#
+# ecbuild_check_cxx_source_return
+# ===============================
+#
+# Compile and run a given C++ code and return its output. ::
+#
+#   ecbuild_check_cxx_source_return( <source>
+#                                    VAR <name>
+#                                    OUTPUT <name>
+#                                    [ INCLUDES <path1> [ <path2> ... ] ]
+#                                    [ LIBS <library1> [ <library2> ... ] ]
+#                                    [ DEFINITIONS <definition1> [ <definition2> ... ] ] )
+#
+# Options
+# -------
+#
+# VAR : required
+#   name of the check and name of the CMake variable to write result to
+#
+# OUTPUT : required
+#   name of CMake variable to write the output to
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# Usage
+# -----
+#
+# This will write the given source to a .cxx file and compile and run it with
+# try_run. If successful, ``${VAR}`` is set to 1 and ``${OUTPUT}`` is set to
+# the output of the successful run in the CMake cache.
+#
+# The check will not run if ``${VAR}`` is defined (e.g. from ecBuild cache).
+#
+##############################################################################
 
 macro( ecbuild_check_cxx_source_return SOURCE )
 
@@ -49,7 +90,7 @@ macro( ecbuild_check_cxx_source_return SOURCE )
         if( _p_INCLUDES )
             list( APPEND __add_incs ${_p_INCLUDES} )
         endif()
-		if( __add_incs )
+        if( __add_incs )
             set(CHECK_CXX_SOURCE_COMPILES_ADD_INCLUDES "-DINCLUDE_DIRECTORIES:STRING=${__add_incs}")
         endif()
     
@@ -69,8 +110,8 @@ macro( ecbuild_check_cxx_source_return SOURCE )
           COMPILE_OUTPUT_VARIABLE compile_OUTPUT 
           RUN_OUTPUT_VARIABLE     run_OUTPUT )
    
-	  # debug_var( ${_p_VAR}_COMPILED )
-	  # debug_var( ${_p_VAR}_EXITCODE )
+        # debug_var( ${_p_VAR}_COMPILED )
+        # debug_var( ${_p_VAR}_EXITCODE )
 
         # if it did not compile make the return value fail code of 1
 
@@ -122,9 +163,24 @@ macro( ecbuild_check_cxx_source_return SOURCE )
 endmacro()
 
 ##############################################################################
-# macro that only adds a cxx flag if compiler supports it
+#.rst:
+#
+# ecbuild_add_cxx_flags
+# =====================
+#
+# Add C++ compiler flags to CMAKE_CXX_FLAGS only if supported by compiler. ::
+#
+#   ecbuild_add_cxx_flags( <flag1> [ <flag2> ... ] [ BUILD <build> ] )
+#
+# Options
+# -------
+#
+# BUILD : optional
+#   add flags to ``CMAKE_CXX_FLAGS_<build>`` instead of ``CMAKE_CXX_FLAGS``
+#
+##############################################################################
 
-macro( cmake_add_cxx_flags m_cxx_flags )
+macro( ecbuild_add_cxx_flags m_cxx_flags )
 
   set( _flags ${m_cxx_flags} )
   if( _flags AND CMAKE_CXX_COMPILER_LOADED )
@@ -158,3 +214,8 @@ macro( cmake_add_cxx_flags m_cxx_flags )
   unset( _flags )
 
 endmacro()
+
+macro( cmake_add_cxx_flags m_cxx_flags )
+  message( DEPRECATION " cmake_add_cxx_flags is deprecated, use ecbuild_add_cxx_flags instead." )
+  ecbuild_add_cxx_flags( ${m_cxx_flags} )
+endmacro()
diff --git a/cmake/ecbuild_check_fortran_source.cmake b/cmake/ecbuild_check_fortran_source.cmake
index da04a70..9f95502 100644
--- a/cmake/ecbuild_check_fortran_source.cmake
+++ b/cmake/ecbuild_check_fortran_source.cmake
@@ -7,7 +7,48 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro that runs the given Fortran code and returns its output
+#.rst:
+#
+# ecbuild_check_fortran_source_return
+# ===================================
+#
+# Compile and run a given Fortran code and return its output. ::
+#
+#   ecbuild_check_fortran_source_return( <source>
+#                                        VAR <name>
+#                                        OUTPUT <name>
+#                                        [ INCLUDES <path1> [ <path2> ... ] ]
+#                                        [ LIBS <library1> [ <library2> ... ] ]
+#                                        [ DEFINITIONS <def1> [ <def2> ... ] ] )
+#
+# Options
+# -------
+#
+# VAR : required
+#   name of the check and name of the CMake variable to write result to
+#
+# OUTPUT : required
+#   name of CMake variable to write the output to
+#
+# INCLUDES : optional
+#   list of paths to add to include directories
+#
+# LIBS : optional
+#   list of libraries to link against (CMake targets or external libraries)
+#
+# DEFINITIONS : optional
+#   list of definitions to add to preprocessor defines
+#
+# Usage
+# -----
+#
+# This will write the given source to a .f file and compile and run it with
+# try_run. If successful, ``${VAR}`` is set to 1 and ``${OUTPUT}`` is set to
+# the output of the successful run in the CMake cache.
+#
+# The check will not run if ``${VAR}`` is defined (e.g. from ecBuild cache).
+#
+##############################################################################
 
 macro( ecbuild_check_fortran_source_return SOURCE )
 
@@ -114,10 +155,27 @@ macro( ecbuild_check_fortran_source_return SOURCE )
 endmacro()
 
 ##############################################################################
-# macro that only adds a Fortran flag if compiler supports it
+#.rst:
+#
+# ecbuild_add_fortran_flags
+# =========================
+#
+# Add Fortran compiler flags to CMAKE_Fortran_FLAGS only if supported by the
+# compiler. ::
+#
+#   ecbuild_add_fortran_flags( <flag1> [ <flag2> ... ] [ BUILD <build> ] )
+#
+# Options
+# -------
+#
+# BUILD : optional
+#   add flags to ``CMAKE_Fortran_FLAGS_<build>`` instead of
+#   ``CMAKE_Fortran_FLAGS``
+#
+##############################################################################
 
 include( CheckFortranCompilerFlag )
-macro( cmake_add_fortran_flags m_fortran_flags )
+macro( ecbuild_add_fortran_flags m_fortran_flags )
 
   set( _flags ${m_fortran_flags} )
 
@@ -155,3 +213,7 @@ macro( cmake_add_fortran_flags m_fortran_flags )
 
 endmacro()
 
+macro( cmake_add_fortran_flags m_fortran_flags )
+  message( DEPRECATION " cmake_add_fortran_flags is deprecated, use ecbuild_add_fortran_flags instead." )
+  ecbuild_add_fortran_flags( ${m_fortran_flags} )
+endmacro()
diff --git a/cmake/ecbuild_check_functions.cmake b/cmake/ecbuild_check_functions.cmake
index e859432..0369797 100644
--- a/cmake/ecbuild_check_functions.cmake
+++ b/cmake/ecbuild_check_functions.cmake
@@ -1,5 +1,5 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
 # In applying this licence, ECMWF does not waive the privileges and immunities 
@@ -10,7 +10,7 @@
 # os capability checks
 
 if( ENABLE_OS_FUNCTIONS_TEST )
-    
+
     ### symbol checks ##################
 
     ecbuild_cache_check_symbol_exists( fseek        "stdio.h"                         EC_HAVE_FSEEK  )
@@ -22,17 +22,17 @@ if( ENABLE_OS_FUNCTIONS_TEST )
     ecbuild_cache_check_symbol_exists( fopen        "stdio.h"                         EC_HAVE_FOPEN  )
     ecbuild_cache_check_symbol_exists( flock        "sys/file.h"                      EC_HAVE_FLOCK  )
     ecbuild_cache_check_symbol_exists( mmap         "sys/mman.h"                      EC_HAVE_MMAP   )
-    
+
     ecbuild_cache_check_symbol_exists( posix_memalign "stdlib.h"                      EC_HAVE_POSIX_MEMALIGN )
-    
+
     ecbuild_cache_check_symbol_exists( F_GETLK      "fcntl.h"                         EC_HAVE_F_GETLK  )
     ecbuild_cache_check_symbol_exists( F_SETLK      "fcntl.h"                         EC_HAVE_F_SETLK  )
     ecbuild_cache_check_symbol_exists( F_SETLKW     "fcntl.h"                         EC_HAVE_F_SETLKW  )
-     
+
     ecbuild_cache_check_symbol_exists( F_GETLK64     "fcntl.h"                        EC_HAVE_F_GETLK64  )
     ecbuild_cache_check_symbol_exists( F_SETLK64     "fcntl.h"                        EC_HAVE_F_SETLK64  )
     ecbuild_cache_check_symbol_exists( F_SETLKW64    "fcntl.h"                        EC_HAVE_F_SETLKW64  )
-    
+
     ecbuild_cache_check_symbol_exists( MAP_ANONYMOUS "sys/mman.h"                     EC_HAVE_MAP_ANONYMOUS )
     ecbuild_cache_check_symbol_exists( MAP_ANON      "sys/mman.h"                     EC_HAVE_MAP_ANON )
 
@@ -48,7 +48,7 @@ if( ENABLE_OS_FUNCTIONS_TEST )
     ecbuild_cache_check_include_files( sys/types.h    EC_HAVE_SYS_TYPES_H   )
     ecbuild_cache_check_include_files( malloc.h       EC_HAVE_MALLOC_H      )
     ecbuild_cache_check_include_files( sys/malloc.h   EC_HAVE_SYS_MALLOC_H  )
-    
+
     ecbuild_cache_check_include_files( sys/param.h    EC_HAVE_SYS_PARAM_H   )
     ecbuild_cache_check_include_files( sys/mount.h    EC_HAVE_SYS_MOUNT_H   )
     ecbuild_cache_check_include_files( sys/vfs.h      EC_HAVE_SYS_VFS_H     )
@@ -93,7 +93,7 @@ if( ENABLE_OS_FUNCTIONS_TEST )
     ecbuild_cache_check_c_source_compiles( "#include <sys/statvfs.h>\nint main(){ struct statvfs v; }" EC_HAVE_STRUCT_STATVFS )
     # test for struct statvfs64
     ecbuild_cache_check_c_source_compiles( "#define _LARGEFILE64_SOURCE\n#include <sys/statvfs.h>\nint main(){ struct statvfs64 v; }" EC_HAVE_STRUCT_STATVFS64 )
-        
+
     # test for fsync
     ecbuild_cache_check_symbol_exists(fsync "unistd.h" EC_HAVE_FSYNC)
     # test for fdatasync
@@ -106,7 +106,7 @@ if( ENABLE_OS_FUNCTIONS_TEST )
     ecbuild_cache_check_c_source_compiles( "#include <sys/procfs.h>\nint main(){ return 0; }\n" EC_HAVE_SYSPROCFS )
     # test for backtrace
     ecbuild_cache_check_c_source_compiles( "#include <unistd.h>\n#include <execinfo.h>\n int main(){ void ** buffer; int i = backtrace(buffer, 256); }\n" EC_HAVE_EXECINFO_BACKTRACE )
-           
+
     #### reentrant funtions support  #############
 
     # test for gmtime_r
@@ -120,6 +120,53 @@ if( ENABLE_OS_FUNCTIONS_TEST )
     # test for gethostbyname_r
     ecbuild_cache_check_c_source_compiles( "#include <netdb.h>\nint main(){ const char *name; struct hostent *ret; char *buf; struct hostent **result; size_t buflen; int *h_errnop; int i = gethostbyname_r(name,ret,buf,buflen,result,h_errnop); }\n" EC_HAVE_GETHOSTBYNAME_R )
 
+    #### special compiler __atributes__  #############
+
+    # test for __attribute__ ((__constructor__)) -- usually present in GCC, Clang, Intel on Linux, Solaris, MacOSX; not present in AIX XLC
+    ecbuild_cache_check_c_source_compiles( "#include <stdio.h>\nstatic int argc_;static char** argv_;static char** envp_;\nint main(){printf(\"%d\", argc_);}\n__attribute__ ((__constructor__)) static void before_main(int argc, char* argv[], char* envp[]){argc_ = argc;argv_ = argv;envp_ = envp;}\n" EC_HAVE_ATTRIBUTE_CONSTRUCTOR )
+
+    if( NOT DEFINED EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV )
+        ecbuild_check_c_source_return("
+            #include <stdio.h>
+            #include <string.h>
+            int main(){return 0;}
+            __attribute__ ((__constructor__))
+            static void before_main(int argc, char* argv[], char* envp[])
+            {
+                printf(\"%d:%d\",argc, strstr(argv[0],\"cmTryCompileExec\")?1:0);
+            }"
+            VAR    EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV
+            OUTPUT EC_ATTRIBUTE_CONSTRUCTOR_INITS_OUTPUT )
+
+        if( EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV AND NOT EC_ATTRIBUTE_CONSTRUCTOR_INITS_OUTPUT STREQUAL "1:1" )
+          set(EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV 0 CACHE INTERNAL "ATTRIBUTE_CONSTRUCTOR doesnt init argv correctly")
+        endif()
+    endif()
+    ecbuild_cache_var( EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV )
+
+
+    #### check for some Linux stuff #############
+
+    if( NOT DEFINED EC_HAVE_PROCFS )
+        ecbuild_check_c_source_return("
+            #include <sys/types.h>
+            #include <dirent.h>
+            int main()
+            {
+                DIR* d = opendir(\"/proc\");
+                if(d)
+                    return 0;
+                else
+                    return -1;
+            }"
+            VAR    EC_HAVE_PROCFS
+            OUTPUT EC_HAVE_PROCFS_OUTPUT )
+    endif()
+    ecbuild_cache_var( EC_HAVE_PROCFS )
+
+#    debug_var(EC_HAVE_PROCFS)
+#    debug_var(EC_HAVE_PROCFS_OUTPUT)
+
 endif()
 
 
diff --git a/cmake/ecbuild_check_os.cmake b/cmake/ecbuild_check_os.cmake
index 8373c4a..399a888 100644
--- a/cmake/ecbuild_check_os.cmake
+++ b/cmake/ecbuild_check_os.cmake
@@ -237,78 +237,78 @@ if( UNIX )
 
 		if( CMAKE_COMPILER_IS_GNUCC )
 			if( EC_OS_BITS EQUAL "64" )
-				cmake_add_c_flags("-maix64")
+				ecbuild_add_c_flags("-maix64")
 			endif()
 			if( EC_OS_BITS EQUAL "32" )
-				cmake_add_c_flags("-maix32")
+				ecbuild_add_c_flags("-maix32")
 			endif()
 		endif()
 
 		if( CMAKE_COMPILER_IS_GNUCXX )
 			if( EC_OS_BITS EQUAL "64" )
-				cmake_add_cxx_flags("-maix64")
+				ecbuild_add_cxx_flags("-maix64")
 			endif()
 			if( EC_OS_BITS EQUAL "32" )
-				cmake_add_cxx_flags("-maix32")
+				ecbuild_add_cxx_flags("-maix32")
 			endif()
 		endif()
 
 		if( CMAKE_C_COMPILER_ID MATCHES "XL" )
 
-			cmake_add_c_flags("-qpic=large")
-#            cmake_add_c_flags("-qweaksymbol")
+			ecbuild_add_c_flags("-qpic=large")
+#            ecbuild_add_c_flags("-qweaksymbol")
 
 			if(EC_OS_BITS EQUAL "32" )
-				cmake_add_c_flags("-q32")
+				ecbuild_add_c_flags("-q32")
 			endif()
 
 			if(${CMAKE_BUILD_TYPE} MATCHES "Release" OR ${CMAKE_BUILD_TYPE} MATCHES "Production" )
-					cmake_add_c_flags("-qstrict")
-					cmake_add_c_flags("-qinline")
+					ecbuild_add_c_flags("-qstrict")
+					ecbuild_add_c_flags("-qinline")
 			endif()
 
 			if(${CMAKE_BUILD_TYPE} MATCHES "Debug")
-					cmake_add_c_flags("-qfullpath")
-					cmake_add_c_flags("-qkeepparm")
+					ecbuild_add_c_flags("-qfullpath")
+					ecbuild_add_c_flags("-qkeepparm")
 			endif()
 
 		endif()
 
 		if( CMAKE_CXX_COMPILER_ID MATCHES "XL" )
 
-			cmake_add_cxx_flags("-qpic=large")
-			cmake_add_cxx_flags("-bmaxdata:0x40000000")
-			cmake_add_cxx_flags("-qrtti")
-			cmake_add_cxx_flags("-qfuncsect")
+			ecbuild_add_cxx_flags("-qpic=large")
+			ecbuild_add_cxx_flags("-bmaxdata:0x40000000")
+			ecbuild_add_cxx_flags("-qrtti")
+			ecbuild_add_cxx_flags("-qfuncsect")
 
-#           cmake_add_cxx_flags("-qweaksymbol")
+#           ecbuild_add_cxx_flags("-qweaksymbol")
 
 			if(EC_OS_BITS EQUAL "32" )
-				cmake_add_cxx_flags("-q32")
+				ecbuild_add_cxx_flags("-q32")
 			endif()
 
 			if(${CMAKE_BUILD_TYPE} MATCHES "Release" OR ${CMAKE_BUILD_TYPE} MATCHES "Production" )
-					cmake_add_cxx_flags("-qstrict")
-					cmake_add_cxx_flags("-qinline")
+					ecbuild_add_cxx_flags("-qstrict")
+					ecbuild_add_cxx_flags("-qinline")
 			endif()
 
 			if(${CMAKE_BUILD_TYPE} MATCHES "Debug")
-					cmake_add_cxx_flags("-qfullpath")
-					cmake_add_cxx_flags("-qkeepparm")
+					ecbuild_add_cxx_flags("-qfullpath")
+					ecbuild_add_cxx_flags("-qkeepparm")
 			endif()
 
 		endif()
 
 		if( CMAKE_Fortran_COMPILER_ID MATCHES "XL" )
 
-			cmake_add_fortran_flags("-qxflag=dealloc_cfptr")
-			cmake_add_fortran_flags("-qextname")
-			cmake_add_fortran_flags("-qdpc=e")
-			cmake_add_fortran_flags("-bmaxdata:0x40000000")
-			cmake_add_fortran_flags("-bloadmap:loadmap -bmap:loadmap")
+			ecbuild_add_fortran_flags("-qxflag=dealloc_cfptr")
+			ecbuild_add_fortran_flags("-qextname")
+			ecbuild_add_fortran_flags("-qdpc=e")
+			ecbuild_add_fortran_flags("-bmaxdata:0x40000000")
+			ecbuild_add_fortran_flags("-bloadmap:loadmap -bmap:loadmap")
 
 			if(EC_OS_BITS EQUAL "32" )
-				cmake_add_fortran_flags("-q32")
+				ecbuild_add_fortran_flags("-q32")
 			endif()
 		endif()
 
diff --git a/cmake/ecbuild_config.h.in b/cmake/ecbuild_config.h.in
index 8e68a8e..68d31f8 100644
--- a/cmake/ecbuild_config.h.in
+++ b/cmake/ecbuild_config.h.in
@@ -11,6 +11,15 @@
 #ifndef @PROJECT_NAME at _ecbuild_config_h
 #define @PROJECT_NAME at _ecbuild_config_h
 
+/* ecbuild info */
+
+#ifndef ECBUILD_VERSION_STR
+#define ECBUILD_VERSION_STR "@ECBUILD_VERSION_STR@"
+#endif
+#ifndef ECBUILD_MACROS_DIR
+#define ECBUILD_MACROS_DIR  "@ECBUILD_MACROS_DIR@"
+#endif
+
 /* cpu arch info */
 
 #cmakedefine EC_BIG_ENDIAN       @EC_BIG_ENDIAN@
@@ -112,6 +121,12 @@
 #cmakedefine EC_HAVE_READDIR_R
 #cmakedefine EC_HAVE_GETHOSTBYNAME_R
 
+/* --- compiler __attribute__ support --- */
+
+#cmakedefine EC_HAVE_ATTRIBUTE_CONSTRUCTOR
+#cmakedefine EC_ATTRIBUTE_CONSTRUCTOR_INITS_ARGV
+#cmakedefine EC_HAVE_PROCFS
+
 /* --- c compiler support --- */
 
 #cmakedefine EC_HAVE_C_INLINE
@@ -149,6 +164,16 @@
 #define @PNAME at _CXX_COMPILER     "@CMAKE_CXX_COMPILER@"
 #define @PNAME at _CXX_FLAGS        "@EC_CXX_FLAGS@"
 
+/* Needed for finding per package config files */
+
+#define @PNAME at _INSTALL_DIR       "@CMAKE_INSTALL_PREFIX@"
+#define @PNAME at _INSTALL_BIN_DIR   "@CMAKE_INSTALL_PREFIX@/@INSTALL_BIN_DIR@"
+#define @PNAME at _INSTALL_LIB_DIR   "@CMAKE_INSTALL_PREFIX@/@INSTALL_LIB_DIR@"
+#define @PNAME at _INSTALL_DATA_DIR  "@CMAKE_INSTALL_PREFIX@/@INSTALL_DATA_DIR@"
+
+#define @PNAME at _DEVELOPER_SRC_DIR "@CMAKE_SOURCE_DIR@"
+#define @PNAME at _DEVELOPER_BIN_DIR "@CMAKE_BINARY_DIR@"
+
 #cmakedefine EC_HAVE_FORTRAN
 
 #ifdef EC_HAVE_FORTRAN
diff --git a/cmake/ecbuild_debug_var.cmake b/cmake/ecbuild_debug_var.cmake
index 63a5104..7084c7c 100644
--- a/cmake/ecbuild_debug_var.cmake
+++ b/cmake/ecbuild_debug_var.cmake
@@ -25,6 +25,18 @@ macro( debug_var VAR )
 endmacro( debug_var )
 
 ##############################################################################
+# macro for debugging a cmake list
+
+macro( debug_list VAR )
+
+    message( STATUS "${VAR}:" )
+    foreach( _elem ${${VAR}} )
+      message( STATUS "  ${_elem}" )
+    endforeach()
+
+endmacro( debug_list )
+
+##############################################################################
 # macro for debugging a environment variable within cmake
 
 macro( debug_env_var VAR )
diff --git a/cmake/ecbuild_declare_project.cmake b/cmake/ecbuild_declare_project.cmake
index fa6286c..7b7835c 100644
--- a/cmake/ecbuild_declare_project.cmake
+++ b/cmake/ecbuild_declare_project.cmake
@@ -6,140 +6,166 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-# macro to initialize a project
+##############################################################################
+#.rst:
+#
+# ecbuild_declare_project
+# =======================
+#
+# Initialise an ecBuild project. A CMake project must have previously been
+# declared with ``project( <name> ... )``. Sets the following CMake variables
+# (where ``PNAME`` is the capitalised project name):
+#
+# :<PNAME>_GIT_SHA1:            Git revision (if project is a Git repo)
+# :<PNAME>_GIT_SHA1_SHORT:      short Git revision (if project is a Git repo)
+# :<PNAME>_VERSION:             version in format ``MAJOR.MINOR.PATCH``
+# :<PNAME>_VERSION_STR:         version as given in ``VERSION.cmake`` or 0.0.0
+# :<PNAME>_MAJOR_VERSION:       major version number
+# :<PNAME>_MINOR_VERSION:       minor version number
+# :<PNAME>_PATCH_VERSION:       patch version number
+# :<PNAME>_INSTALL_BIN_DIR:     directory for installing executables
+# :<PNAME>_INSTALL_LIB_DIR:     directory for installing libraries
+# :<PNAME>_INSTALL_INCLUDE_DIR: directory for installing include files
+# :<PNAME>_INSTALL_DATA_DIR:    directory for installing data
+# :<PNAME>_INSTALL_CMAKE_DIR:   directory for installing CMake files
+#
+##############################################################################
 
 macro( ecbuild_declare_project )
 
-	string( TOUPPER ${PROJECT_NAME} PNAME )
+  string( TOUPPER ${PROJECT_NAME} PNAME )
 
-	# reset the lists of targets (executables, libs, tests & resources)
+  # reset the lists of targets (executables, libs, tests & resources)
 
-	set( ${PROJECT_NAME}_ALL_EXES "" CACHE INTERNAL "" )
-	set( ${PROJECT_NAME}_ALL_LIBS "" CACHE INTERNAL "" )
+  set( ${PROJECT_NAME}_ALL_EXES "" CACHE INTERNAL "" )
+  set( ${PROJECT_NAME}_ALL_LIBS "" CACHE INTERNAL "" )
 
-	# if git project get its HEAD SHA1
-	# leave it here so we may use ${PNAME}_GIT_SHA1 on the version file
+  # if git project get its HEAD SHA1
+  # leave it here so we may use ${PNAME}_GIT_SHA1 on the version file
 
-	if( EXISTS ${PROJECT_SOURCE_DIR}/.git )
-		get_git_head_revision( GIT_REFSPEC ${PNAME}_GIT_SHA1 )
-		if( ${PNAME}_GIT_SHA1 )
-		  string( SUBSTRING "${${PNAME}_GIT_SHA1}" 0 7 ${PNAME}_GIT_SHA1_SHORT )
-#		  debug_var( ${PNAME}_GIT_SHA1 )
-#		  debug_var( ${PNAME}_GIT_SHA1_SHORT )
-        else()
-          message( STATUS "Could not get git-sha1 for project ${PNAME}")
-        endif()
-	endif()
+  if( EXISTS ${PROJECT_SOURCE_DIR}/.git )
+    get_git_head_revision( GIT_REFSPEC ${PNAME}_GIT_SHA1 )
+    if( ${PNAME}_GIT_SHA1 )
+      string( SUBSTRING "${${PNAME}_GIT_SHA1}" 0 7 ${PNAME}_GIT_SHA1_SHORT )
+      #     debug_var( ${PNAME}_GIT_SHA1 )
+      #     debug_var( ${PNAME}_GIT_SHA1_SHORT )
+    else()
+      message( STATUS "Could not get git-sha1 for project ${PNAME}")
+    endif()
+  endif()
 
-	# read and parse project version file
-	if( EXISTS ${PROJECT_SOURCE_DIR}/VERSION.cmake )
-		include( ${PROJECT_SOURCE_DIR}/VERSION.cmake )
-	else()
-		set( ${PROJECT_NAME}_VERSION_STR "0.0.0" )
-	endif()
+  # read and parse project version file
+  if( EXISTS ${PROJECT_SOURCE_DIR}/VERSION.cmake )
+    include( ${PROJECT_SOURCE_DIR}/VERSION.cmake )
+  else()
+    set( ${PROJECT_NAME}_VERSION_STR "0.0.0" )
+  endif()
 
-	string( REPLACE "." " " _version_list ${${PROJECT_NAME}_VERSION_STR} ) # dots to spaces
+  string( REPLACE "." " " _version_list ${${PROJECT_NAME}_VERSION_STR} ) # dots to spaces
 
-	separate_arguments( _version_list )
+  separate_arguments( _version_list )
 
-	list( GET _version_list 0 ${PNAME}_MAJOR_VERSION )
-	list( GET _version_list 1 ${PNAME}_MINOR_VERSION )
-	list( GET _version_list 2 ${PNAME}_PATCH_VERSION )
+  list( GET _version_list 0 ${PNAME}_MAJOR_VERSION )
+  list( GET _version_list 1 ${PNAME}_MINOR_VERSION )
+  list( GET _version_list 2 ${PNAME}_PATCH_VERSION )
 
-	# cleanup patch version of any extra qualifiers ( -dev -rc1 ... )
+  # cleanup patch version of any extra qualifiers ( -dev -rc1 ... )
 
-	string( REGEX REPLACE "^([0-9]+).*" "\\1" ${PNAME}_PATCH_VERSION "${${PNAME}_PATCH_VERSION}" )
+  string( REGEX REPLACE "^([0-9]+).*" "\\1" ${PNAME}_PATCH_VERSION "${${PNAME}_PATCH_VERSION}" )
 
-	set( ${PNAME}_VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}.${${PNAME}_PATCH_VERSION}" CACHE INTERNAL "package ${PNAME} version" )
+  set( ${PNAME}_VERSION "${${PNAME}_MAJOR_VERSION}.${${PNAME}_MINOR_VERSION}.${${PNAME}_PATCH_VERSION}"
+       CACHE INTERNAL "package ${PNAME} version" )
 
-	set( ${PNAME}_VERSION_STR "${${PROJECT_NAME}_VERSION_STR}" CACHE INTERNAL "package ${PNAME} version string" ) # ignore caps
+  set( ${PNAME}_VERSION_STR "${${PROJECT_NAME}_VERSION_STR}"
+       CACHE INTERNAL "package ${PNAME} version string" ) # ignore caps
 
-#    debug_var( ${PNAME}_VERSION )
-#    debug_var( ${PNAME}_VERSION_STR )
-#    debug_var( ${PNAME}_MAJOR_VERSION )
-#    debug_var( ${PNAME}_MINOR_VERSION )
-#    debug_var( ${PNAME}_PATCH_VERSION )
+  #    debug_var( ${PNAME}_VERSION )
+  #    debug_var( ${PNAME}_VERSION_STR )
+  #    debug_var( ${PNAME}_MAJOR_VERSION )
+  #    debug_var( ${PNAME}_MINOR_VERSION )
+  #    debug_var( ${PNAME}_PATCH_VERSION )
 
-	# install dirs for this project
+  # install dirs for this project
 
-	set( INSTALL_BIN_DIR bin )
-	set( INSTALL_LIB_DIR lib )
-    set( INSTALL_INCLUDE_DIR include )
-	set( INSTALL_DATA_DIR share/${PROJECT_NAME} )
-	set( INSTALL_CMAKE_DIR share/${PROJECT_NAME}/cmake )
+  set( INSTALL_BIN_DIR bin )
+  set( INSTALL_LIB_DIR lib )
+  set( INSTALL_INCLUDE_DIR include )
+  set( INSTALL_DATA_DIR share/${PROJECT_NAME} )
+  set( INSTALL_CMAKE_DIR share/${PROJECT_NAME}/cmake )
 
-	mark_as_advanced( INSTALL_BIN_DIR )
-	mark_as_advanced( INSTALL_LIB_DIR )
-	mark_as_advanced( INSTALL_INCLUDE_DIR )
-	mark_as_advanced( INSTALL_DATA_DIR )
-	mark_as_advanced( INSTALL_CMAKE_DIR )
+  mark_as_advanced( INSTALL_BIN_DIR )
+  mark_as_advanced( INSTALL_LIB_DIR )
+  mark_as_advanced( INSTALL_INCLUDE_DIR )
+  mark_as_advanced( INSTALL_DATA_DIR )
+  mark_as_advanced( INSTALL_CMAKE_DIR )
 
-	# overrides of install dirs
+  # overrides of install dirs
 
-	foreach( p LIB BIN INCLUDE DATA CMAKE )
-		if( ${PNAME}_INSTALL_${p}_DIR )
-			set( INSTALL_${p}_DIR ${${PNAME}_INSTALL_${p}_DIR} )
-		endif()
-	endforeach()
+  foreach( p LIB BIN INCLUDE DATA CMAKE )
+    if( ${PNAME}_INSTALL_${p}_DIR )
+      set( INSTALL_${p}_DIR ${${PNAME}_INSTALL_${p}_DIR} )
+    endif()
+  endforeach()
 
-	# warnings for non-relocatable projects
+  # warnings for non-relocatable projects
 
-	foreach( p LIB BIN INCLUDE DATA CMAKE )
-		if( IS_ABSOLUTE ${INSTALL_${p}_DIR} )
-			message( WARNING "Defining INSTALL_${p}_DIR as absolute path '${INSTALL_${p}_DIR}' makes this build non-relocatable, possibly breaking the installation of RPMS and DEB packages" )
-		endif()
-	endforeach()
+  foreach( p LIB BIN INCLUDE DATA CMAKE )
+    if( IS_ABSOLUTE ${INSTALL_${p}_DIR} )
+      message( WARNING "Defining INSTALL_${p}_DIR as absolute path '${INSTALL_${p}_DIR}' makes this build non-relocatable, possibly breaking the installation of RPMS and DEB packages" )
+    endif()
+  endforeach()
 
-	# make relative paths absolute ( needed later on ) and cache them ...
-	foreach( p LIB BIN INCLUDE DATA CMAKE )
+  # make relative paths absolute ( needed later on ) and cache them ...
+  foreach( p LIB BIN INCLUDE DATA CMAKE )
 
-		set( var INSTALL_${p}_DIR )
+    set( var INSTALL_${p}_DIR )
 
-		if( NOT IS_ABSOLUTE "${${var}}" )
-			set( ${PNAME}_FULL_INSTALL_${p}_DIR "${CMAKE_INSTALL_PREFIX}/${${var}}" CACHE INTERNAL "${PNAME} ${p} full install path" )
-		else()
-			message( WARNING "Setting an absolute path for ${VAR} in project ${PNAME}, breakes generation of relocatable binary packages (rpm,deb,...)" )
-			set( ${PNAME}_FULL_INSTALL_${p}_DIR "${${var}}" CACHE INTERNAL "${PNAME} ${p} full install path" )
-		endif()
+    if( NOT IS_ABSOLUTE "${${var}}" )
+      set( ${PNAME}_FULL_INSTALL_${p}_DIR "${CMAKE_INSTALL_PREFIX}/${${var}}"
+           CACHE INTERNAL "${PNAME} ${p} full install path" )
+    else()
+      message( WARNING "Setting an absolute path for ${VAR} in project ${PNAME}, breakes generation of relocatable binary packages (rpm,deb,...)" )
+      set( ${PNAME}_FULL_INSTALL_${p}_DIR "${${var}}"
+           CACHE INTERNAL "${PNAME} ${p} full install path" )
+    endif()
 
-#        debug_var( ${PNAME}_FULL_INSTALL_${p}_DIR )
+    #        debug_var( ${PNAME}_FULL_INSTALL_${p}_DIR )
 
-	endforeach()
+  endforeach()
 
-	# correctly set CMAKE_INSTALL_RPATH
+  # correctly set CMAKE_INSTALL_RPATH
 
-	if( ENABLE_RPATHS )
+  if( ENABLE_RPATHS )
 
-		if( ENABLE_RELATIVE_RPATHS )
+    if( ENABLE_RELATIVE_RPATHS )
 
-			file( RELATIVE_PATH relative_rpath ${${PNAME}_FULL_INSTALL_BIN_DIR} ${${PNAME}_FULL_INSTALL_LIB_DIR} )
-			# debug_var( relative_rpath )
+      file( RELATIVE_PATH relative_rpath ${${PNAME}_FULL_INSTALL_BIN_DIR} ${${PNAME}_FULL_INSTALL_LIB_DIR} )
+      # debug_var( relative_rpath )
 
-			ecbuild_append_to_rpath( ${relative_rpath} )
+      ecbuild_append_to_rpath( ${relative_rpath} )
 
-		else() # make rpaths absolute
+    else() # make rpaths absolute
 
-		    if( IS_ABSOLUTE ${INSTALL_LIB_DIR} )
-		        ecbuild_append_to_rpath( "${INSTALL_LIB_DIR}" )
-		    else()
-		        ecbuild_append_to_rpath( "${CMAKE_INSTALL_PREFIX}/${INSTALL_LIB_DIR}" ) 
-		    endif()
+      if( IS_ABSOLUTE ${INSTALL_LIB_DIR} )
+        ecbuild_append_to_rpath( "${INSTALL_LIB_DIR}" )
+      else()
+        ecbuild_append_to_rpath( "${CMAKE_INSTALL_PREFIX}/${INSTALL_LIB_DIR}" ) 
+      endif()
 
-		endif()
-    
-	endif()
+    endif()
 
-	# debug_var( CMAKE_INSTALL_RPATH )
+  endif()
 
-	# print project header
+  # debug_var( CMAKE_INSTALL_RPATH )
 
-	message( STATUS "---------------------------------------------------------" )
+  # print project header
 
-	if( ${PNAME}_GIT_SHA1_SHORT )
-		message( STATUS "[${PROJECT_NAME}] (${${PNAME}_VERSION_STR}) [${${PNAME}_GIT_SHA1_SHORT}]" )
-	else()
-		message( STATUS "[${PROJECT_NAME}] (${${PNAME}_VERSION_STR})" )
-	endif()
+  message( STATUS "---------------------------------------------------------" )
 
-endmacro( ecbuild_declare_project )
+  if( ${PNAME}_GIT_SHA1_SHORT )
+    message( STATUS "[${PROJECT_NAME}] (${${PNAME}_VERSION_STR}) [${${PNAME}_GIT_SHA1_SHORT}]" )
+  else()
+    message( STATUS "[${PROJECT_NAME}] (${${PNAME}_VERSION_STR})" )
+  endif()
 
+endmacro( ecbuild_declare_project )
diff --git a/cmake/ecbuild_define_build_types.cmake b/cmake/ecbuild_define_build_types.cmake
index 9ec2ef0..f239f01 100644
--- a/cmake/ecbuild_define_build_types.cmake
+++ b/cmake/ecbuild_define_build_types.cmake
@@ -1,8 +1,8 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
-# In applying this licence, ECMWF does not waive the privileges and immunities 
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
@@ -35,8 +35,8 @@ mark_as_advanced(
     CMAKE_CXX_FLAGS_PRODUCTION
     CMAKE_C_FLAGS_PRODUCTION
     CMAKE_EXE_LINKER_FLAGS_PRODUCTION
-	CMAKE_SHARED_LINKER_FLAGS_PRODUCTION
-	CMAKE_MODULE_LINKER_FLAGS_PRODUCTION )
+	  CMAKE_SHARED_LINKER_FLAGS_PRODUCTION
+	  CMAKE_MODULE_LINKER_FLAGS_PRODUCTION )
 
 ############################################################################################
 # fixes for specific compilers
@@ -99,12 +99,39 @@ endif()
 
 # fail if build type is not one of the defined ones
 if( NOT CMAKE_BUILD_TYPE MATCHES "None"  AND
-	NOT CMAKE_BUILD_TYPE MATCHES "Debug" AND
-	NOT CMAKE_BUILD_TYPE MATCHES "Bit" AND
-	NOT CMAKE_BUILD_TYPE MATCHES "Production" AND
+	  NOT CMAKE_BUILD_TYPE MATCHES "Debug" AND
+	  NOT CMAKE_BUILD_TYPE MATCHES "Bit" AND
+	  NOT CMAKE_BUILD_TYPE MATCHES "Production" AND
     NOT CMAKE_BUILD_TYPE MATCHES "Release"  AND
     NOT CMAKE_BUILD_TYPE MATCHES "RelWithDebInfo" )
     message( FATAL_ERROR "CMAKE_BUILD_TYPE is not recognized. ${_BUILD_TYPE_MSG}" )
 endif()
 
+############################################################################################
+# overrides of the flags per build type
+
+foreach( _btype NONE DEBUG BIT PRODUCTION RELEASE RELWITHDEBINFO )
+
+  # OVERRIDE Compiler FLAGS per language (we override because CMake forcely defines them)
+  foreach( _lang C CXX Fortran )
+    if( ECBUILD_${_lang}_FLAGS_${_btype} )
+      set( CMAKE_${_lang}_FLAGS_${_btype} ${ECBUILD_${_lang}_FLAGS_${_btype}} )
+    endif()
+  endforeach()
+
+  # OVERRIDE Linker FLAGS per object type (we override because CMake forcely defines them)
+  foreach( _obj EXE SHARED MODULE )
+    if( ECBUILD_${_obj}_LINKER_FLAGS_${_btype} )
+      set( CMAKE_${_obj}_LINKER_FLAGS_${_btype} ${ECBUILD_${_obj}_LINKER_FLAGS_${_btype}} )
+    endif()
+  endforeach()
+
+endforeach()
+
+# APPEND Linker FLAGS per language (we append because CMake typically leaves them empty)
 
+foreach( _lang C CXX Fortran )
+  if( ECBUILD_${_lang}_LINK_FLAGS )
+    set( CMAKE_${_lang}_LINK_FLAGS "${CMAKE_${_lang}_LINK_FLAGS} ${ECBUILD_${_lang}_LINK_FLAGS}" )
+  endif()
+endforeach()
\ No newline at end of file
diff --git a/cmake/ecbuild_define_options.cmake b/cmake/ecbuild_define_options.cmake
index a79fcf3..3999db8 100644
--- a/cmake/ecbuild_define_options.cmake
+++ b/cmake/ecbuild_define_options.cmake
@@ -26,7 +26,7 @@ option( ENABLE_FORTRAN_C_INTERFACE "Enable Fortran/C Interface" OFF )
 mark_as_advanced( ENABLE_FORTRAN_C_INTERFACE )
 
 option( DEVELOPER_MODE           "activates developer mode"               OFF )
-option( CHECK_UNUSED_FILES       "check for unused project files"         ON )
+option( CHECK_UNUSED_FILES       "check for unused project files (slow)"  OFF )
 
 mark_as_advanced( DEVELOPER_MODE  )
 mark_as_advanced( CHECK_UNUSED_FILES  )
@@ -38,3 +38,9 @@ cmake_dependent_option( ENABLE_OS_ENDINESS_TEST  "Run OS endiness tests"       O
 cmake_dependent_option( ENABLE_OS_FUNCTIONS_TEST "Run OS functions tests"      ON "ENABLE_OS_TESTS" OFF)
 
 mark_as_advanced( ENABLE_OS_TYPES_TEST ENABLE_OS_ENDINESS_TEST ENABLE_OS_FUNCTIONS_TEST  )
+
+option( ECBUILD_USE_INCLUDE_DIRECTORIES "Forces to use global include_directories() instead of target specific. Adverse effect on PkgConfig generation." OFF )
+
+mark_as_advanced( ECBUILD_USE_INCLUDE_DIRECTORIES )
+
+set( CMAKE_NO_SYSTEM_FROM_IMPORTED ON )
\ No newline at end of file
diff --git a/cmake/ecbuild_define_uninstall.cmake b/cmake/ecbuild_define_uninstall.cmake
new file mode 100644
index 0000000..cc6efa9
--- /dev/null
+++ b/cmake/ecbuild_define_uninstall.cmake
@@ -0,0 +1,7 @@
+### adds uninstall target ###############
+
+configure_file(
+  "${CMAKE_CURRENT_LIST_DIR}/ecbuild_uninstall.cmake.in"
+  "${CMAKE_CURRENT_BINARY_DIR}/ecbuild_uninstall.cmake" IMMEDIATE @ONLY)
+
+add_custom_target( uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/ecbuild_uninstall.cmake")
diff --git a/cmake/ecbuild_dont_pack.cmake b/cmake/ecbuild_dont_pack.cmake
new file mode 100644
index 0000000..099ee1d
--- /dev/null
+++ b/cmake/ecbuild_dont_pack.cmake
@@ -0,0 +1,82 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+##############################################################################
+#.rst:
+#
+# ecbuild_dont_pack
+# =================
+#
+# Specify files and directories to exclude from packaging. ::
+#
+#   ecbuild_dont_pack( [ FILES <file1> [ <file2> ... ] ]
+#                      [ DIRS <dir1> [ <dir2> ... ] ]
+#                      [ REGEX <regex> ] )
+#
+# Options
+# -------
+#
+# FILES : optional, one of FILES, DIRS, REGEX required
+#   list of files to exclude from packaging
+#
+# DIRS : optional, one of FILES, DIRS, REGEX required
+#   list of directories to exclude from packaging
+#
+# REGEX : optional, one of FILES, DIRS, REGEX required
+#   regular expression to match files / directories to exclude from packaging
+#
+##############################################################################
+
+macro( ecbuild_dont_pack )
+
+    set( options )
+    set( single_value_args REGEX )
+    set( multi_value_args  FILES DIRS )
+
+    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+
+    if(_PAR_UNPARSED_ARGUMENTS)
+      message(FATAL_ERROR "Unknown keywords given to ecbuild_dont_pack(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+    endif()
+
+    if( NOT DEFINED _PAR_REGEX AND NOT  DEFINED _PAR_FILES AND NOT  DEFINED _PAR_DIRS )
+      message(FATAL_ERROR "Call to ecbuild_dont_pack does not speficify any list to avoid packing.")
+    endif()
+
+    set( LOCAL_FILES_NOT_TO_PACK "" )
+
+    # all recursive files are not to pack
+    if( DEFINED _PAR_REGEX )
+        file( GLOB_RECURSE all_files_in_subdirs RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${_PAR_REGEX} )
+        list( APPEND LOCAL_FILES_NOT_TO_PACK ${all_files_in_subdirs} )
+    endif()
+
+    # selected dirs not to pack
+    if( DEFINED _PAR_DIRS )
+        foreach( dir ${_PAR_DIRS} )
+            list( APPEND LOCAL_FILES_NOT_TO_PACK ${dir}/ )
+        endforeach()
+    endif()
+
+    # selected files not to pack
+    if( DEFINED _PAR_FILES )
+        list( APPEND LOCAL_FILES_NOT_TO_PACK ${_PAR_FILES} )
+    endif()
+
+    # transform the local files  to full absolute paths
+    # and place them in the global list of files not to pack
+    foreach( file ${LOCAL_FILES_NOT_TO_PACK} )
+        list( APPEND ECBUILD_DONT_PACK_FILES ${CMAKE_CURRENT_SOURCE_DIR}/${file} )
+    endforeach()
+
+    # save cache if we added any files not to pack
+    if( LOCAL_FILES_NOT_TO_PACK )
+        set( ECBUILD_DONT_PACK_FILES ${ECBUILD_DONT_PACK_FILES} CACHE INTERNAL "" )
+    endif()
+
+endmacro()
diff --git a/cmake/ecbuild_download_resource.cmake b/cmake/ecbuild_download_resource.cmake
new file mode 100644
index 0000000..d313704
--- /dev/null
+++ b/cmake/ecbuild_download_resource.cmake
@@ -0,0 +1,47 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+##############################################################################
+#.rst:
+#
+# ecbuild_download_resource
+# =========================
+#
+# Download a file from a given URL and save to FILE at configure time. ::
+#
+#   ecbuild_download_resource( FILE URL )
+#
+# curl or wget is required (curl is preferred if available).
+#
+##############################################################################
+
+function( ecbuild_download_resource _p_OUT _p_URL )
+
+  if( NOT EXISTS ${_p_OUT} )
+
+    find_program( CURL_PROGRAM curl )
+    if( CURL_PROGRAM )
+      execute_process( COMMAND ${CURL_PROGRAM} --silent --show-error --fail --output ${_p_OUT} ${_p_URL}
+                       WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} RESULT_VARIABLE CMD_RESULT )
+    else()
+      find_program( WGET_PROGRAM wget )
+      if( WGET_PROGRAM )
+        execute_process( COMMAND ${WGET_PROGRAM} -nv -O ${_p_OUT} ${_p_URL}
+                         WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} RESULT_VARIABLE CMD_RESULT )
+      else()
+        message(FATAL_ERROR "Could not find curl or wget. Error downloading ${_p_URL}")
+      endif()
+    endif()
+
+    if(CMD_RESULT)
+      message(FATAL_ERROR "Error downloading ${_p_URL}")
+    endif()
+
+  endif()
+
+endfunction()
diff --git a/cmake/ecbuild_echo_targets.cmake b/cmake/ecbuild_echo_targets.cmake
index 015192b..ddaa2e4 100644
--- a/cmake/ecbuild_echo_targets.cmake
+++ b/cmake/ecbuild_echo_targets.cmake
@@ -1,14 +1,25 @@
+# (C) Copyright 1996-2015 ECMWF.
 #
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+##############################################################################
+#.rst:
+#
+# ecbuild_echo_target_property
+# ============================
+#
+# Output a given property of a given target. ::
 #
-# FUNCTION ecbuild_echo_targets ( <list-of-targets> )
+#   ecbuild_echo_target_property( <target> <property> )
 #
-#   Writes all possible target properties of the specified list-of-targets.
-#   This is very useful for debugging
-# 
+##############################################################################
 
+function(ecbuild_echo_target_property tgt prop)
 
-function(echo_target_property tgt prop)
- 
   cmake_policy(PUSH)
 
   if( POLICY CMP0026 )
@@ -19,7 +30,7 @@ function(echo_target_property tgt prop)
   get_property(v TARGET ${tgt} PROPERTY ${prop})
   get_property(d TARGET ${tgt} PROPERTY ${prop} DEFINED)
   get_property(s TARGET ${tgt} PROPERTY ${prop} SET)
- 
+
   # only produce output for values that are set
   #if(s)
     message("tgt='${tgt}' prop='${prop}'")
@@ -32,13 +43,25 @@ function(echo_target_property tgt prop)
   cmake_policy(POP)
 
 endfunction()
- 
-function(echo_target tgt)
+
+##############################################################################
+#.rst:
+#
+# ecbuild_echo_target
+# ===================
+#
+# Output all possible target properties of a given target. ::
+#
+#   ecbuild_echo_target( <target> )
+#
+##############################################################################
+
+function(ecbuild_echo_target tgt)
   if(NOT TARGET ${tgt})
     message("There is no target named '${tgt}'")
     return()
   endif()
- 
+
   set(props
 DEBUG_OUTPUT_NAME
 DEBUG_POSTFIX
@@ -181,18 +204,30 @@ VS_WINRT_REFERENCES
 WIN32_EXECUTABLE
 XCODE_ATTRIBUTE_WHATEVER
 )
- 
+
   message("======================== ${tgt} ========================")
   foreach(p ${props})
-    echo_target_property("${t}" "${p}")
+    ecbuild_echo_target_property("${t}" "${p}")
   endforeach()
   message("")
 endfunction()
- 
- 
+
+##############################################################################
+#.rst:
+#
+# ecbuild_echo_targets
+# ====================
+#
+# Output all possible target properties of the specified list-of-targets.
+# This is very useful for debugging. ::
+#
+#   ecbuild_echo_targets( <list-of-targets> )
+#
+##############################################################################
+
 function(ecbuild_echo_targets)
   set(tgts ${ARGV})
   foreach(t ${tgts})
-    echo_target("${t}")
+    ecbuild_echo_target("${t}")
   endforeach()
-endfunction()
\ No newline at end of file
+endfunction()
diff --git a/cmake/ecbuild_enable_fortran.cmake b/cmake/ecbuild_enable_fortran.cmake
index dfb28d4..5560148 100644
--- a/cmake/ecbuild_enable_fortran.cmake
+++ b/cmake/ecbuild_enable_fortran.cmake
@@ -7,50 +7,68 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-
-# macro for enabling the fortan language
+#.rst:
+#
+# ecbuild_enable_fortran
+# ======================
+#
+# Enable the Fortran language. ::
+#
+#   ecbuild_enable_fortran( [ MODULE_DIRECTORY <directory> ] [ REQUIRED ] )
+#
+# Options
+# -------
+#
+# MODULE_DIRECTORY : optional, defaults to ``${CMAKE_BINARY_DIR}/module``
+#   set the CMAKE_Fortran_MODULE_DIRECTORY
+#
+# REQUIRED : optional
+#   fail if no working Fortran compiler was detected
+#
+##############################################################################
 
 macro( ecbuild_enable_fortran )
 
-    set( options REQUIRED  )
-    set( single_value_args MODULE_DIRECTORY )
-    set( multi_value_args  )
+  set( options REQUIRED  )
+  set( single_value_args MODULE_DIRECTORY )
+  set( multi_value_args  )
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_enable_fortran(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_enable_fortran(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    enable_language( Fortran )
+  enable_language( Fortran )
 
-    if( DEFINED _PAR_REQUIRED )
-      if( CMAKE_Fortran_COMPILER_FORCED )
-        set( CMAKE_Fortran_COMPILER_WORKS 1 )
-      endif()
-      if( NOT CMAKE_Fortran_COMPILER OR NOT CMAKE_Fortran_COMPILER_WORKS )
-          message( FATAL_ERROR "Fortran compiler required by project ${PROJECT_NAME} but does not seem to work" )
-      endif()
+  if( DEFINED _PAR_REQUIRED )
+    if( CMAKE_Fortran_COMPILER_FORCED )
+      set( CMAKE_Fortran_COMPILER_WORKS 1 )
     endif()
-
-    if( CMAKE_Fortran_COMPILER_LOADED )
-        include(CheckFortranFunctionExists)
-		if( CMAKE_C_COMPILER_LOADED AND ENABLE_FORTRAN_C_INTERFACE )
-			include(FortranCInterface)
-		endif()
-		set( EC_HAVE_FORTRAN 1 )
+    if( NOT CMAKE_Fortran_COMPILER OR NOT CMAKE_Fortran_COMPILER_WORKS )
+      message( FATAL_ERROR "Fortran compiler required by project ${PROJECT_NAME} but does not seem to work" )
     endif()
+  endif()
 
-    if( DEFINED _PAR_MODULE_DIRECTORY )
-        set( CMAKE_Fortran_MODULE_DIRECTORY  ${_PAR_MODULE_DIRECTORY} )
-    else()
-        set( CMAKE_Fortran_MODULE_DIRECTORY  ${CMAKE_BINARY_DIR}/module CACHE PATH "directory for all fortran modules." )
+  if( CMAKE_Fortran_COMPILER_LOADED )
+    include(CheckFortranFunctionExists)
+    if( CMAKE_C_COMPILER_LOADED AND ENABLE_FORTRAN_C_INTERFACE )
+      include(FortranCInterface)
     endif()
+    set( EC_HAVE_FORTRAN 1 )
+  endif()
+
+  if( DEFINED _PAR_MODULE_DIRECTORY )
+    set( CMAKE_Fortran_MODULE_DIRECTORY  ${_PAR_MODULE_DIRECTORY} )
+  else()
+    set( CMAKE_Fortran_MODULE_DIRECTORY  ${CMAKE_BINARY_DIR}/module
+         CACHE PATH "directory for all fortran modules." )
+  endif()
 
-	file( MAKE_DIRECTORY ${CMAKE_Fortran_MODULE_DIRECTORY} )
+  file( MAKE_DIRECTORY ${CMAKE_Fortran_MODULE_DIRECTORY} )
 
-    include_directories( ${CMAKE_Fortran_MODULE_DIRECTORY} )
+  include_directories( ${CMAKE_Fortran_MODULE_DIRECTORY} )
 
-    install( CODE "EXECUTE_PROCESS (COMMAND \"${CMAKE_COMMAND}\" -E copy_directory \"${CMAKE_Fortran_MODULE_DIRECTORY}/\${BUILD_TYPE}\" \"${INSTALL_INCLUDE_DIR}\")" )
+  install( CODE "EXECUTE_PROCESS (COMMAND \"${CMAKE_COMMAND}\" -E copy_directory \"${CMAKE_Fortran_MODULE_DIRECTORY}/\${BUILD_TYPE}\" \"${INSTALL_INCLUDE_DIR}\")" )
 
 endmacro( ecbuild_enable_fortran )
diff --git a/cmake/ecbuild_features.cmake b/cmake/ecbuild_features.cmake
new file mode 100644
index 0000000..5d619a5
--- /dev/null
+++ b/cmake/ecbuild_features.cmake
@@ -0,0 +1,121 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+# Internal macros to handle CMake features
+
+include( FeatureSummary )
+
+function( debug_var _var )
+  message( "${_var} = ${${_var}}" )
+endfunction()
+
+# Write list of enabled features to CMake variable ${OUT}
+macro( ecbuild_enabled_features OUT )
+    get_property( ${OUT}  GLOBAL PROPERTY ENABLED_FEATURES )
+endmacro()
+
+# Write list of disabled features to CMake variable ${OUT}
+macro( ecbuild_disabled_features OUT )
+    get_property( ${OUT}  GLOBAL PROPERTY DISABLED_FEATURES )
+endmacro()
+
+# Enable the feature ${_name} (add to enabled features, remove from disabled)
+function( ecbuild_enable_feature _name )
+  
+  get_property( _enabled_features  GLOBAL PROPERTY ENABLED_FEATURES )
+  get_property( _disabled_features GLOBAL PROPERTY DISABLED_FEATURES )
+  
+  if( _disabled_features )
+    list( REMOVE_ITEM _disabled_features ${_name} )
+  endif()
+
+  list( APPEND _enabled_features ${_name} )
+  list( REMOVE_DUPLICATES _enabled_features )
+    
+  set_property(GLOBAL PROPERTY ENABLED_FEATURES  "${_enabled_features}" )
+  set_property(GLOBAL PROPERTY DISABLED_FEATURES "${_disabled_features}" )
+
+endfunction()
+
+# Disable the feature ${_name} (add to disabled features, remove from enabled)
+function( ecbuild_disable_feature _name )
+
+  get_property( _enabled_features  GLOBAL PROPERTY ENABLED_FEATURES )
+  get_property( _disabled_features GLOBAL PROPERTY DISABLED_FEATURES )
+  
+  if( _enabled_features )
+    list( REMOVE_ITEM _enabled_features ${_name} )
+  endif()
+
+  list( APPEND _disabled_features ${_name} )
+  list( REMOVE_DUPLICATES _disabled_features )
+    
+  set_property(GLOBAL PROPERTY ENABLED_FEATURES  "${_enabled_features}" )
+  set_property(GLOBAL PROPERTY DISABLED_FEATURES "${_disabled_features}" )
+  
+endfunction()
+
+# Set description of feature ${_name} to ${_desc}
+function( ecbuild_set_feature_description _name _desc)      
+  set_property(GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION "${_desc}" )
+endfunction()
+
+# Set purpose of feature ${_name} to ${_desc}
+function( ecbuild_set_feature_purpose _name _purpose )
+  get_property( _purpose_list  GLOBAL PROPERTY _CMAKE_${_name}_PURPOSE )
+  list( APPEND _purpose_list ${_purpose} )
+  list( REMOVE_DUPLICATES _purpose_list )
+  set_property(GLOBAL PROPERTY _CMAKE_${_name}_PURPOSE "${_purpose_list}" )
+endfunction()
+
+# en/disable feature ${_name} and set its description and purpose
+function( ecbuild_set_feature _name )
+
+  set(options ) # none
+  set(oneValueArgs ENABLED DESCRIPTION PURPOSE )
+  set(multiValueArgs ) # none
+
+  CMAKE_PARSE_ARGUMENTS( _PAR "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
+  
+  get_property( _feature_desc      GLOBAL PROPERTY _CMAKE_${_name}_DESCRIPTION )  
+  get_property( _enabled_features  GLOBAL PROPERTY ENABLED_FEATURES )
+  get_property( _disabled_features GLOBAL PROPERTY DISABLED_FEATURES )
+  
+  if( DEFINED _PAR_ENABLED )
+    if( _PAR_ENABLED )
+      ecbuild_enable_feature( ${_name} )
+    else()
+      ecbuild_disable_feature( ${_name} )
+    endif()
+  endif()
+  
+  ecbuild_enabled_features( _enabled_features )
+  list (FIND _enabled_features "${_name}" _index)
+  if (${_index} GREATER -1)
+    set( _feature_found 1 )
+  endif()
+
+  ecbuild_disabled_features( _disabled_features )
+  list (FIND _disabled_features "${_name}" _index)
+  if (${_index} GREATER -1)
+    set( _feature_found 1 )
+  endif()
+  
+  if( NOT _feature_found )
+    message( WARNING "Feature ${_name} has not yet been enabled or disabled" )
+  endif()
+  
+  if( _PAR_DESCRIPTION )
+    ecbuild_set_feature_description( ${_name} ${_PAR_DESCRIPTION} )
+  endif()
+  
+  if( _PAR_PURPOSE )
+    ecbuild_set_feature_purpose( ${_name} ${_PAR_PURPOSE} )
+  endif()
+
+endfunction()
diff --git a/cmake/ecbuild_find_fortranlibs.cmake b/cmake/ecbuild_find_fortranlibs.cmake
index b40a5eb..850c4a3 100644
--- a/cmake/ecbuild_find_fortranlibs.cmake
+++ b/cmake/ecbuild_find_fortranlibs.cmake
@@ -1,131 +1,163 @@
-# (C) Copyright 1996-2014 ECMWF.
+# (C) Copyright 1996-2015 ECMWF.
 #
 # This software is licensed under the terms of the Apache Licence Version 2.0
 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 # In applying this licence, ECMWF does not waive the privileges and immunities
-# granted to it by virtue of its status as an intergovernmental organisation nor
-# does it submit to any jurisdiction.
-
-############################################################################################
-# macro to find fortran (static) link libraries
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
 
+##############################################################################
+#.rst:
+#
+# ecbuild_find_fortranlibs
+# ========================
+#
+# Find the Fortran (static) link libraries. ::
+#
+#   ecbuild_find_fortranlibs( [ COMPILER gfortran|pgi|xlf|intel ]
+#                             [ REQUIRED ] )
+#
+# Options
+# -------
+#
+# COMPILER : optional, defaults to gfortran
+#   request a given Fortran compiler (``gfortran``, ``pgi``, ``xlf``, ``intel``)
+#
+# REQUIRED : optional
+#   fail if Fortran libraries were not found
+#
+##############################################################################
 
 macro( ecbuild_find_fortranlibs )
 
-    # parse parameters
+  # parse parameters
+
+  set( options REQUIRED )
+  set( single_value_args COMPILER )
+  set( multi_value_args  )
+
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_find_python(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    set( options REQUIRED )
-	set( single_value_args COMPILER )
-    set( multi_value_args  )
+  if( NOT FORTRANLIBS_FOUND ) # don't repeat search
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+    if( _PAR_COMPILER )
+      set( __known_fcomp 0 )
+    endif()
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_find_python(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+    if( _PAR_COMPILER MATCHES "gfortran" )
+      set( WITH_LIBGFORTRAN 1 )
+      set( __known_fcomp 1 )
     endif()
 
-	if( NOT FORTRANLIBS_FOUND ) # don't repeat search
+    if( _PAR_COMPILER MATCHES "pgi" )
+      set( WITH_PGI_FORTRAN 1 )
+      set( __known_fcomp 1 )
+    endif()
 
-		if( _PAR_COMPILER )
-			set( __known_fcomp 0 )
-		endif()
+    if( _PAR_COMPILER MATCHES "xlf" )
+      set( WITH_XL_FORTRAN 1 )
+      set( __known_fcomp 1 )
+    endif()
 
-		if( _PAR_COMPILER MATCHES "gfortran" )
-			set( WITH_LIBGFORTRAN 1 )
-			set( __known_fcomp 1 )
-		endif()
+    if( _PAR_COMPILER MATCHES "intel" )
+      set( WITH_INTEL_FORTRAN 1 )
+      set( __known_fcomp 1 )
+    endif()
 
-		if( _PAR_COMPILER MATCHES "pgi" )
-			set( WITH_PGI_FORTRAN 1 )
-			set( __known_fcomp 1 )
-		endif()
+    if( _PAR_COMPILER AND NOT __known_fcomp )
+      message( FATAL_ERROR "unknown fortran compiler ${_PAR_COMPILER}" )
+    endif()
 
-		if( _PAR_COMPILER MATCHES "xlf" )
-			set( WITH_XL_FORTRAN 1 )
-			set( __known_fcomp 1 )
-		endif()
+    ### set path from environment variables
 
-		if( _PAR_COMPILER MATCHES "intel" )
-			message( FATAL_ERROR "searching for intel libraries has not been implemented" )
-			set( __known_fcomp 1 )
-		endif()
+    foreach( _fortran_lib PGI XLF LIBGFORTRAN INTEL )
+      if( NOT ${_fortran_lib}_PATH AND NOT "$ENV{${_fortran_lib}_PATH}" STREQUAL "" )
+        set( ${_fortran_lib}_PATH "$ENV{${_fortran_lib}_PATH}" )
+      endif()
+    endforeach()
 
-		if( _PAR_COMPILER AND NOT __known_fcomp )
-			message( FATAL_ERROR "unknown fortran compiler ${_PAR_COMPILER}" )
-		endif()
+    set( _flibs_found 0 )
 
-		### set path from environment variables
+    ### default is to search for gfortran
 
-		foreach( _fortran_lib PGI XLF LIBGFORTRAN )
-			if( NOT ${_fortran_lib}_PATH AND NOT "$ENV{${_fortran_lib}_PATH}" STREQUAL "" )
-				set( ${_fortran_lib}_PATH "$ENV{${_fortran_lib}_PATH}" )
-			endif()
-		endforeach()
+    if( NOT (WITH_PGI_FORTRAN OR WITH_LIBGFORTRAN OR
+             WITH_XL_FORTRAN OR WITH_INTEL_FORTRAN)
+        AND NOT (DEFINED PGI_PATH OR DEFINED LIBGFORTRAN_PATH OR
+                 DEFINED XLF_PATH OR DEFINED INTEL_PATH) )
+      message( WARNING "Finding fortran libs for unspecified Fortran compiler: default search [ gfortran ]" )
+      set( WITH_LIBGFORTRAN 1 )
+    endif()
 
-		set( _flibs_found 0 )
+    ### actual search ...
 
-		### default is to search for gfortran
+    if( WITH_PGI_FORTRAN OR DEFINED PGI_PATH )
 
-		if( NOT WITH_PGI_FORTRAN AND NOT WITH_LIBGFORTRAN AND NOT WITH_XL_FORTRAN
-			AND NOT DEFINED PGI_PATH AND NOT DEFINED LIBGFORTRAN_PATH AND NOT DEFINED XLF_PATH )
-			message( WARNING "Finding fortran libs for unspecified Fortran compiler: default search [ gfortran ]" )
-			set( WITH_LIBGFORTRAN 1 )
-		endif()
+      find_package(PGIFortran)
 
-		### actual search ...
+      if( LIBPGIFORTRAN_FOUND )
+        set( FORTRAN_LIBRARIES ${PGIFORTRAN_LIBRARIES} )
+        set( _flibs_found 1 )
+        set( _flibs_txt "PGI" )
+      endif()
 
-		if( WITH_PGI_FORTRAN OR DEFINED PGI_PATH )
+    endif()
 
-			find_package(PGIFortran)
+    if( WITH_LIBGFORTRAN OR DEFINED LIBGFORTRAN_PATH )
 
-			if( LIBPGIFORTRAN_FOUND )
-				set( FORTRAN_LIBRARIES ${PGIFORTRAN_LIBRARIES} )
-				set( _flibs_found 1 )
-				set( _flibs_txt "PGI" )
-			endif()
+      find_package(LibGFortran)
 
-		endif()
+      if( LIBGFORTRAN_FOUND )
+        set( FORTRAN_LIBRARIES ${GFORTRAN_LIBRARIES} )
+        set( _flibs_found 1 )
+        set( _flibs_txt "gfortran" )
+      endif()
 
-		if( WITH_LIBGFORTRAN OR DEFINED LIBGFORTRAN_PATH )
+    endif()
 
-			find_package(LibGFortran)
+    if( WITH_XL_FORTRAN OR DEFINED XLF_PATH )
 
-			if( LIBGFORTRAN_FOUND )
-				set( FORTRAN_LIBRARIES ${GFORTRAN_LIBRARIES} )
-				set( _flibs_found 1 )
-				set( _flibs_txt "gfortran" )
-			endif()
+      find_package(XLFortranLibs)
 
-		endif()
+      if( LIBXLFORTRAN_FOUND )
+        set( FORTRAN_LIBRARIES ${XLFORTRAN_LIBRARIES} )
+        set( _flibs_found 1 )
+        set( _flibs_txt "XLF" )
+      endif()
 
-		if( WITH_XL_FORTRAN OR DEFINED XLF_PATH )
+    endif()
 
-			find_package(XLFortranLibs)
+    if( WITH_INTEL_FORTRAN OR DEFINED INTEL_PATH )
 
-			if( LIBXLFORTRAN_FOUND )
-				set( FORTRAN_LIBRARIES ${XLFORTRAN_LIBRARIES} )
-				set( _flibs_found 1 )
-				set( _flibs_txt "XLF" )
-			endif()
+      find_package(LibIFort)
 
-		endif()
+      if( LIBIFORT_FOUND )
+        set( FORTRAN_LIBRARIES ${IFORT_LIBRARIES} )
+        set( _flibs_found 1 )
+        set( _flibs_txt "Intel" )
+      endif()
 
-		### set found
+    endif()
 
-		if( _flibs_found )
-			set( FORTRANLIBS_FOUND 1 CACHE INTERNAL "Fortran libraries found" )
-			set( FORTRANLIBS_NAME ${_flibs_txt}  CACHE INTERNAL "Fortran library name" )
-			set( FORTRAN_LIBRARIES ${FORTRAN_LIBRARIES} CACHE INTERNAL "Fortran libraries" )
-			message( STATUS "Found Fortran libraries: ${_flibs_txt}" )
-		else()
-			set( FORTRANLIBS_FOUND 0 )
-			if( _PAR_REQUIRED )
-			   message( FATAL_ERROR "Failed to find Fortran libraries" )
-			else()
-			   message( STATUS "Failed to find Fortran libraries" )
-			endif()
-		endif()
+    ### set found
+
+    if( _flibs_found )
+      set( FORTRANLIBS_FOUND 1 CACHE INTERNAL "Fortran libraries found" )
+      set( FORTRANLIBS_NAME ${_flibs_txt}  CACHE INTERNAL "Fortran library name" )
+      set( FORTRAN_LIBRARIES ${FORTRAN_LIBRARIES} CACHE INTERNAL "Fortran libraries" )
+      message( STATUS "Found Fortran libraries: ${_flibs_txt}" )
+    else()
+      set( FORTRANLIBS_FOUND 0 )
+      if( _PAR_REQUIRED )
+        message( FATAL_ERROR "Failed to find Fortran libraries" )
+      else()
+        message( STATUS "Failed to find Fortran libraries" )
+      endif()
+    endif()
 
-	endif( NOT FORTRANLIBS_FOUND )
+  endif( NOT FORTRANLIBS_FOUND )
 
 endmacro( ecbuild_find_fortranlibs )
diff --git a/cmake/ecbuild_find_lexyacc.cmake b/cmake/ecbuild_find_lexyacc.cmake
index 373b81c..b74c3e1 100644
--- a/cmake/ecbuild_find_lexyacc.cmake
+++ b/cmake/ecbuild_find_lexyacc.cmake
@@ -6,55 +6,79 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to find python
-
-# OUTPUT:
+##############################################################################
+#.rst:
+#
+# ecbuild_find_lexyacc
+# ====================
+#
+# Find flex and bison (preferred) or lex and yacc.
+#
+# Input variables
+# ---------------
+#
+# The following CMake variables can set to skip search for bison or yacc:
+#
+# :SKIP_BISON: do not search for flex and bison
+# :SKIP_YACC:  do not search for lex and yacc
+#
+# Output variables
+# ----------------
+#
+# The following CMake variables are set if flex and bison were found:
+#
+# :FLEX_FOUND:       flex was found
+# :BISON_FOUND:      bison was found
+# :FLEX_EXECUTABLE:  path to the flex executable
+# :BISON_EXECUTABLE: path to the bison executable
+#
+# The following CMake variables are set if lex and yacc were found:
 #
-# BISON_FOUND or YACC_FOUND
-# FLEX_FOUND or LEX_FOUND
+# :LEX_FOUND:       lex was found
+# :YACC_FOUND:      yacc was found
+# :LEX_EXECUTABLE:  path to the lex executable
+# :YACC_EXECUTABLE: path to the yacc executable
 #
-# BISON_EXECUTABLE or YACC_EXECUTABLE
-# FLEX_EXECUTABLE or LEX_EXECUTABLE
+##############################################################################
 
 macro( ecbuild_find_lexyacc )
 
-	# find preferably bison or else yacc
+  # find preferably bison or else yacc
 
-	if( NOT SKIP_BISON )
+  if( NOT SKIP_BISON )
 
-		find_package( BISON 2.3 )
-		find_package( FLEX )
+    find_package( BISON 2.3 )
+    find_package( FLEX )
 
-	endif()
+  endif()
 
-	if( NOT BISON_FOUND AND NOT SKIP_YACC )
+  if( NOT BISON_FOUND AND NOT SKIP_YACC )
 
-		find_package( YACC )
-		find_package( LEX  )
+    find_package( YACC )
+    find_package( LEX  )
 
-	endif()
+  endif()
 
-	if( NOT YACC_FOUND AND NOT BISON_FOUND ) # neither bison nor yacc were found
-		message( FATAL_ERROR "neither bison or yacc were found - at least one is required (together with its lexical analyser" )
-	endif()
+  if( NOT YACC_FOUND AND NOT BISON_FOUND ) # neither bison nor yacc were found
+    message( FATAL_ERROR "neither bison or yacc were found - at least one is required (together with its lexical analyser" )
+  endif()
 
-	if( NOT YACC_FOUND ) # check for both bison & flex together
-		if( BISON_FOUND AND NOT FLEX_FOUND )
-			message( FATAL_ERROR "both bison and flex are required - flex not found" )
-		endif()
-		if( FLEX_FOUND AND NOT BISON_FOUND )
-			message( FATAL_ERROR "both bison and flex are required - bison not found" )
-		endif()
-	endif()
+  if( NOT YACC_FOUND ) # check for both bison & flex together
+    if( BISON_FOUND AND NOT FLEX_FOUND )
+      message( FATAL_ERROR "both bison and flex are required - flex not found" )
+    endif()
+    if( FLEX_FOUND AND NOT BISON_FOUND )
+      message( FATAL_ERROR "both bison and flex are required - bison not found" )
+    endif()
+  endif()
 
-	if( NOT BISON_FOUND ) # check for both yacc & lex together
-		if( YACC_FOUND AND NOT LEX_FOUND )
-			message( FATAL_ERROR "both yacc and lex are required - lex not found" )
-		endif()
-		if( LEX_FOUND AND NOT YACC_FOUND )
-			message( FATAL_ERROR "both yacc and lex are required - yacc not found" )
-		endif()
-	endif()
+  if( NOT BISON_FOUND ) # check for both yacc & lex together
+    if( YACC_FOUND AND NOT LEX_FOUND )
+      message( FATAL_ERROR "both yacc and lex are required - lex not found" )
+    endif()
+    if( LEX_FOUND AND NOT YACC_FOUND )
+      message( FATAL_ERROR "both yacc and lex are required - yacc not found" )
+    endif()
+  endif()
 
 endmacro( ecbuild_find_lexyacc )
diff --git a/cmake/ecbuild_find_mpi.cmake b/cmake/ecbuild_find_mpi.cmake
index 9ed4b3c..d7265f9 100644
--- a/cmake/ecbuild_find_mpi.cmake
+++ b/cmake/ecbuild_find_mpi.cmake
@@ -6,10 +6,69 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to find MPI
-# uses the canonical find_package( MPI )
-# but does more checks
+##############################################################################
+#.rst:
+#
+# ecbuild_find_mpi
+# ================
+#
+# Find MPI and check if MPI compilers successfully compile C/C++/Fortran. ::
+#
+#   ecbuild_find_mpi( [ COMPONENTS <component1> [ <component2> ... ] ]
+#                     [ REQUIRED ] )
+#
+# Options
+# -------
+#
+# COMPONENTS : optional, defaults to C
+#   list of required languages bindings
+#
+# REQUIRED : optional
+#   fail if MPI was not found
+#
+# Input variables
+# ---------------
+#
+# ECBUILD_FIND_MPI : optional, defaults to TRUE
+#   test C/C++/Fortran MPI compiler wrappers (assume working if FALSE)
+#
+# Output variables
+# ----------------
+#
+# The following CMake variables are set if MPI was found: ::
+#
+#   MPI_FOUND
+#   MPI_LIBRARY
+#   MPI_EXTRA_LIBRARY 
+#
+# The following CMake variables are set if C bindings were found: ::
+#
+#   MPI_C_FOUND
+#   MPI_C_COMPILER
+#   MPI_C_COMPILE_FLAGS
+#   MPI_C_INCLUDE_PATH
+#   MPI_C_LIBRARIES
+#   MPI_C_LINK_FLAGS
+#
+# The following CMake variables are set if C++ bindings were found: ::
+#
+#   MPI_CXX_FOUND
+#   MPI_CXX_COMPILER
+#   MPI_CXX_COMPILE_FLAGS
+#   MPI_CXX_INCLUDE_PATH
+#   MPI_CXX_LIBRARIES
+#   MPI_CXX_LINK_FLAGS
+#
+# The following CMake variables are set if Fortran bindings were found: ::
+#
+#   MPI_Fortran_FOUND
+#   MPI_Fortran_COMPILER
+#   MPI_Fortran_COMPILE_FLAGS
+#   MPI_Fortran_INCLUDE_PATH
+#   MPI_Fortran_LIBRARIES
+#   MPI_Fortran_LINK_FLAGS
+#
+##############################################################################
 
 macro( ecbuild_find_mpi )
 
@@ -156,6 +215,32 @@ macro( ecbuild_find_mpi )
 
 endmacro( ecbuild_find_mpi )
 
+##############################################################################
+#.rst:
+#
+# ecbuild_enable_mpi
+# ==================
+#
+# Find MPI, add include directories and set compiler flags. ::
+#
+#   ecbuild_enable_mpi( [ COMPONENTS <component1> [ <component2> ... ] ]
+#                       [ REQUIRED ] )
+#
+# For each MPI language binding found, set the corresponding compiler flags
+# and add the include directories.
+#
+# See ``ecbuild_find_mpi`` for input and output variables.
+#
+# Options
+# -------
+#
+# COMPONENTS : optional, defaults to C
+#   list of required languages bindings
+#
+# REQUIRED : optional
+#   fail if MPI was not found
+#
+##############################################################################
 
 macro( ecbuild_enable_mpi )
 
@@ -180,23 +265,36 @@ macro( ecbuild_enable_mpi )
     endif()
 
     if( MPI_C_FOUND AND NOT C_COMPILER_SUPPORTS_MPI )
-        cmake_add_c_flags("${MPI_C_COMPILE_FLAGS}")
+        ecbuild_add_c_flags("${MPI_C_COMPILE_FLAGS}")
         include_directories(${MPI_C_INCLUDE_PATH})
     endif()
 
     if( MPI_CXX_FOUND AND NOT CXX_COMPILER_SUPPORTS_MPI )
-        cmake_add_cxx_flags("${MPI_CXX_COMPILE_FLAGS}")
+        ecbuild_add_cxx_flags("${MPI_CXX_COMPILE_FLAGS}")
         include_directories(${MPI_CXX_INCLUDE_PATH})
     endif()
 
     if( MPI_Fortran_FOUND AND NOT Fortran_COMPILER_SUPPORTS_MPI )
         include(ecbuild_check_fortran_source)
-        cmake_add_fortran_flags("${MPI_Fortran_COMPILE_FLAGS}")
+        ecbuild_add_fortran_flags("${MPI_Fortran_COMPILE_FLAGS}")
         include_directories(${MPI_Fortran_INCLUDE_PATH})
     endif()
 
 endmacro( ecbuild_enable_mpi )
 
+##############################################################################
+#.rst:
+#
+# ecbuild_include_mpi
+# ===================
+#
+# Add MPI include directories and set compiler flags, assuming MPI was found.
+#
+# For each MPI language binding found, set corresponding compiler flags and
+# add include directories. ``ecbuild_find_mpi`` must have been called before.
+#
+##############################################################################
+
 macro( ecbuild_include_mpi )
 
     set( options )
@@ -211,19 +309,19 @@ macro( ecbuild_include_mpi )
 
     if( MPI_C_FOUND AND NOT C_COMPILER_SUPPORTS_MPI )
         include( ecbuild_check_c_source )
-        cmake_add_c_flags("${MPI_C_COMPILE_FLAGS}")
+        ecbuild_add_c_flags("${MPI_C_COMPILE_FLAGS}")
         include_directories(${MPI_C_INCLUDE_PATH})
     endif()
 
     if( MPI_CXX_FOUND AND NOT CXX_COMPILER_SUPPORTS_MPI )
         include( ecbuild_check_cxx_source )
-        cmake_add_cxx_flags("${MPI_CXX_COMPILE_FLAGS}")
+        ecbuild_add_cxx_flags("${MPI_CXX_COMPILE_FLAGS}")
         include_directories(${MPI_CXX_INCLUDE_PATH})
     endif()
 
     if( MPI_Fortran_FOUND AND NOT Fortran_COMPILER_SUPPORTS_MPI )
         include( ecbuild_check_fortran_source )
-        cmake_add_fortran_flags("${MPI_Fortran_COMPILE_FLAGS}")
+        ecbuild_add_fortran_flags("${MPI_Fortran_COMPILE_FLAGS}")
         include_directories(${MPI_Fortran_INCLUDE_PATH})
     endif()
 
diff --git a/cmake/ecbuild_find_omp.cmake b/cmake/ecbuild_find_omp.cmake
index 86ab139..2de9d74 100644
--- a/cmake/ecbuild_find_omp.cmake
+++ b/cmake/ecbuild_find_omp.cmake
@@ -7,8 +7,7 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a test
-##############################################################################
+# macro for looking for openmp flags
 
 macro( lookup_omp_flags )
   set(_OMP_FLAG_GNU        "-fopenmp")
@@ -74,19 +73,47 @@ macro( lookup_omp_flags )
 
 endmacro()
 
-
-# MACRO ecbuild_find_omp
+##############################################################################
+#.rst:
+#
+# ecbuild_find_omp
+# ================
+#
+# Find OpenMP. ::
+#
+#   ecbuild_find_omp( [ COMPONENTS <component1> [ <component2> ... ] ]
+#                     [ REQUIRED ]
+#                     [ STUBS ] )
+#
+# Options
+# -------
+#
+# COMPONENTS : optional, defaults to C
+#   list of required languages bindings
+#
+# REQUIRED : optional
+#   fail if OpenMP was not found
+#
+# STUBS : optional
+#   search for OpenMP stubs
+#
+# Output variables
+# ----------------
+#
+# The following CMake variables are set if OpenMP was found:
+#
+# :OMP_FOUND: OpenMP was found
+#
+# For each language listed in COMPONENTS, the following variables are set:
 #
-# ecbuild_find_omp( COMPONENTS C CXX Fortran
-#                   STUBS )
-# Sets following variables
-#   - OMP_FOUND
-#   - OMP_<lang>_FOUND
-#   - OMP_<lang>_FLAGS
+# :OMP_<LANG>_FOUND: OpenMP bindings for LANG were found
+# :OMP_<LANG>_FLAGS: OpenMP compiler flags for LANG
 #
-# If STUBS are available, above flags will still hold TRUE,
-# as OMP code will just work.
+# If the STUBS option was given, all variables are also set with the OMPSTUBS
+# instead of the OMP prefix.
 #
+##############################################################################
+
 macro( ecbuild_find_omp )
 
   set( options REQUIRED STUBS )
@@ -166,6 +193,16 @@ macro( ecbuild_find_omp )
 
 endmacro( ecbuild_find_omp )
 
+##############################################################################
+#.rst:
+#
+# ecbuild_enable_omp
+# ==================
+#
+# Find OpenMP for C, C++ and Fortran and set the compiler flags for each
+# language for which OpenMP support was detected.
+#
+##############################################################################
 
 macro( ecbuild_enable_omp )
 
@@ -185,6 +222,17 @@ macro( ecbuild_enable_omp )
 
 endmacro( ecbuild_enable_omp )
 
+##############################################################################
+#.rst:
+#
+# ecbuild_enable_ompstubs
+# =======================
+#
+# Find OpenMP stubs for C, C++ and Fortran and set the compiler flags for each
+# language for which OpenMP stubs were detected.
+#
+##############################################################################
+
 macro( ecbuild_enable_ompstubs )
 
   ecbuild_find_omp( COMPONENTS C CXX Fortran STUBS )
diff --git a/cmake/ecbuild_find_package.cmake b/cmake/ecbuild_find_package.cmake
index e6cea19..cec0072 100644
--- a/cmake/ecbuild_find_package.cmake
+++ b/cmake/ecbuild_find_package.cmake
@@ -7,184 +7,310 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for adding a subproject directory
+#.rst:
+#
+# ecbuild_find_package
+# ====================
+#
+# Find a package and import its configuration. ::
+#
+#   ecbuild_find_package( NAME <name>
+#                         [ VERSION <version> [ EXACT ] ]
+#                         [ COMPONENTS <component1> [ <component2> ... ] ]
+#                         [ REQUIRED ]
+#                         [ QUIET ] )
+#
+# Options
+# -------
+#
+# NAME : required
+#   package name (used as ``Find<name>.cmake`` and ``<name>-config.cmake``)
+#
+# VERSION : optional
+#   minimum required package version
+#
+# COMPONENTS : optional
+#   list of package components to find (behaviour depends on the package)
+#
+# EXACT : optional, requires VERSION
+#   require the exact version rather than a minimum version
+#
+# REQUIRED : optional
+#   fail if package cannot be found
+#
+# QUIET : optional
+#   do not output package information if found
+#
+# Input variables
+# ---------------
+#
+# The following CMake variables influence the behaviour if set (``<name>`` is
+# the package name as given, ``<NAME>`` is the capitalised version):
+#
+# :DEVELOPER_MODE: if enabled, discover projects parallel in the build tree
+# :<name>_PATH:    install prefix path of the package
+# :<NAME>_PATH:    install prefix path of the package
+# :<name>_DIR:     directory containing the ``<name>-config.cmake`` file
+#                  (usually ``<install-prefix>/share/<name>/cmake``)
+#
+# The environment variables ``<name>_PATH``, ``<NAME>_PATH``, ``<name>_DIR``
+# are taken into account only if the corresponding CMake variables are unset.
+#
+# Usage
+# -----
+#
+# The search proceeds as follows:
+#
+# 1.  If any paths have been specified by the user via CMake or environment
+#     variables as given above or a parallel build tree has been discovered in
+#     DEVELOPER_MODE:
+#
+#     * search for ``<name>-config.cmake`` in those paths only
+#     * search using ``Find<name>.cmake`` (which should respect those paths)
+#     * fail if the package was not found in any of those paths
+#
+# 2.  Search for ``<name>-config.cmake`` in the ``CMAKE_PREFIX_PATH`` and if
+#     DEVELOPER_MODE is enabled also in the user package registry.
+#
+# 3.  Search system paths for ``<name>-config.cmake``.
+#
+# 4.  Search system paths using ``Find<name>.cmake``.
+#
+# 5.  If the package was found, and a minimum version was requested, check if
+#     the version is acceptable and if not, unset ``<NAME>_FOUND``.
+#
+# 6.  Fail if the package was not found and is REQUIRED.
+#
 ##############################################################################
 
 macro( ecbuild_find_package )
 
-    set( options REQUIRED QUIET EXACT )
-    set( single_value_args NAME VERSION )
-    set( multi_value_args )
+  set( options REQUIRED QUIET EXACT )
+  set( single_value_args NAME VERSION )
+  set( multi_value_args COMPONENTS )
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_find_package(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_find_package(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    if( NOT _PAR_NAME  )
-      message(FATAL_ERROR "The call to ecbuild_find_package() doesn't specify the NAME.")
-    endif()
+  if( NOT _PAR_NAME  )
+    message(FATAL_ERROR "The call to ecbuild_find_package() doesn't specify the NAME.")
+  endif()
 
-    if( _PAR_EXACT AND NOT _PAR_VERSION )
-      message(FATAL_ERROR "Call to ecbuild_find_package() requests EXACT but doesn't specify VERSION.")
-    endif()
+  if( _PAR_EXACT AND NOT _PAR_VERSION )
+    message(FATAL_ERROR "Call to ecbuild_find_package() requests EXACT but doesn't specify VERSION.")
+  endif()
 
-	# debug_var( _PAR_NAME )
+  # debug_var( _PAR_NAME )
 
-    string( TOUPPER ${_PAR_NAME} PNAME )
+  string( TOUPPER ${_PAR_NAME} PNAME )
 
-    set( _${PNAME}_version "" )
-    if( _PAR_VERSION )
-        set( _${PNAME}_version ${_PAR_VERSION} )
-        if( _PAR_EXACT )
-            set( _${PNAME}_version ${_PAR_VERSION} EXACT )
-        endif()
+  set( _${PNAME}_version "" )
+  if( _PAR_VERSION )
+    set( _${PNAME}_version ${_PAR_VERSION} )
+    if( _PAR_EXACT )
+      set( _${PNAME}_version ${_PAR_VERSION} EXACT )
     endif()
+  endif()
+
+  # check developer mode (search in cmake cache )
+
+  if( NOT ${DEVELOPER_MODE} )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): Not in DEVELOPER_MODE - do not search package registry or recent GUI build paths")
+    set( NO_DEV_BUILD_DIRS NO_CMAKE_PACKAGE_REGISTRY NO_CMAKE_BUILDS_PATH )
+  endif()
+
+  # in DEVELOPER_MODE we give priority to projects parallel in the build tree
+  # so lets prepend a parallel build tree to the search path if we find it
+
+  if( DEVELOPER_MODE )
+    get_filename_component( _proj_bdir "${CMAKE_BINARY_DIR}/../${_PAR_NAME}" ABSOLUTE )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): in DEVELOPER_MODE - searching for ${_PAR_NAME}-config.cmake in ${_proj_bdir}")
+    if( EXISTS ${_proj_bdir}/${_PAR_NAME}-config.cmake )
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): in DEVELOPER_MODE - found parallel build tree in ${_proj_bdir}")
+      if( ${PNAME}_PATH )
+        ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): in DEVELOPER_MODE - ${PNAME}_PATH already set to ${${PNAME}_PATH}, not modifying")
+      else()
+        ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): in DEVELOPER_MODE - setting ${PNAME}_PATH to ${_proj_bdir}")
+        set( ${PNAME}_PATH "${_proj_bdir}" )
+      endif()
+    endif()
+  endif()
 
-	# check developer mode (search in cmake cache )
-
-	if( NOT ${DEVELOPER_MODE} )
-		set( NO_DEV_BUILD_DIRS NO_CMAKE_PACKAGE_REGISTRY NO_CMAKE_BUILDS_PATH )
-	endif()
-
-	# search user defined paths first
-
-	if( ${_PAR_NAME}_PATH OR ${PNAME}_PATH OR ${_PAR_NAME}_DIR OR ${PNAME}_DIR )
-
-		# debug_var( ${_PAR_NAME}_PATH )
-		# debug_var( ${PNAME}_PATH )
-
-		# 1) search using CONFIG mode -- try to locate a configuration file provided by the package (package-config.cmake)
-
-		if( NOT ${_PAR_NAME}_FOUND )
-			find_package( ${_PAR_NAME} ${_${PNAME}_version} NO_MODULE QUIET
-                HINTS ${${PNAME}_PATH} ${_PAR_NAME}_PATH ${${PNAME}_DIR} ${${_PAR_NAME}_DIR}
-                NO_DEFAULT_PATH )
-		endif()
+  # Read environment variables but ONLY if the corresponding CMake variables are unset
 
-		# 2) search using a file Find<package>.cmake if it exists ( macro should itself take *_PATH into account )
+  if( NOT DEFINED ${PNAME}_PATH AND NOT "$ENV{${PNAME}_PATH}" STREQUAL "" )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): setting ${PNAME}_PATH=${${PNAME}_PATH} from environment")
+    set( ${PNAME}_PATH "$ENV{${PNAME}_PATH}" )
+  endif()
 
-		if( NOT ${_PAR_NAME}_FOUND )
-			find_package( ${_PAR_NAME} ${_${PNAME}_version} MODULE QUIET )
-		endif()
+  if( NOT DEFINED ${_PAR_NAME}_PATH AND NOT "$ENV{${_PAR_NAME}_PATH}" STREQUAL "" )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): setting ${_PAR_NAME}_PATH=${${_PAR_NAME}_PATH} from environment")
+    set( ${_PAR_NAME}_PATH "$ENV{${_PAR_NAME}_PATH}" )
+  endif()
 
-		# is <package>_PATH was given and we don't find anything then we FAIL
+  if( NOT DEFINED ${_PAR_NAME}_DIR AND NOT "$ENV{${_PAR_NAME}_DIR}" STREQUAL "" )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): setting ${_PAR_NAME}_DIR=${${_PAR_NAME}_DIR} from environment")
+    set( ${_PAR_NAME}_DIR "$ENV{${_PAR_NAME}_DIR}" )
+  endif()
 
-		if( NOT ${_PAR_NAME}_FOUND )
-			if( ${_PAR_NAME}_PATH )
-				message( FATAL_ERROR "${_PAR_NAME}_PATH was provided by user but package ${_PAR_NAME} wasn't found" )
-			endif()
-			if( ${PNAME}_PATH )
-				message( FATAL_ERROR "${PNAME}_PATH was provided by user but package ${_PAR_NAME} wasn't found" )
-			endif()
-		endif()
+  # search user defined paths first
 
-	endif()
+  if( ${_PAR_NAME}_PATH OR ${PNAME}_PATH OR ${_PAR_NAME}_DIR )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): ${_PAR_NAME}_PATH=${${_PAR_NAME}_PATH}, ${PNAME}_PATH=${${PNAME}_PATH}, ${_PAR_NAME}_DIR=${${_PAR_NAME}_DIR}")
 
-	# 3) search developer cache and recently configured packages in the CMake GUI
+    # 1) search using CONFIG mode -- try to locate a configuration file provided by the package (package-config.cmake)
 
-	if( NOT ${_PAR_NAME}_FOUND )
+    if( NOT ${_PAR_NAME}_FOUND )
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 1) search using CONFIG mode -- try to locate ${_PAR_NAME}-config.cmake")
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}):    using hints ${PNAME}_PATH=${${PNAME}_PATH}, ${_PAR_NAME}_PATH=${${_PAR_NAME}_PATH}, ${_PAR_NAME}_DIR=${${_PAR_NAME}_DIR}")
+      find_package( ${_PAR_NAME} ${_${PNAME}_version} NO_MODULE QUIET
+        COMPONENTS ${_PAR_COMPONENTS}
+        HINTS ${${PNAME}_PATH} ${${_PAR_NAME}_PATH} ${${_PAR_NAME}_DIR}
+        NO_DEFAULT_PATH )
+    endif()
 
-		find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET NO_MODULE HINTS ENV ${PNAME}_PATH
-				${NO_DEV_BUILD_DIRS}
-				NO_CMAKE_ENVIRONMENT_PATH
-				NO_SYSTEM_ENVIRONMENT_PATH
-				NO_CMAKE_SYSTEM_PATH
-				NO_CMAKE_SYSTEM_PACKAGE_REGISTRY )
+    # 2) search using a file Find<package>.cmake if it exists ( macro should itself take *_PATH into account )
 
-	endif()
+    if( NOT ${_PAR_NAME}_FOUND )
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 2) search using a file Find${_PAR_NAME}.cmake if it exists")
+      find_package( ${_PAR_NAME} ${_${PNAME}_version} MODULE QUIET COMPONENTS ${_PAR_COMPONENTS} )
+    endif()
 
-	# 4) search special ECMWF paths
+    # is <package>_PATH was given and we don't find anything then we FAIL
 
-	if( NOT ${_PAR_NAME}_FOUND )
+    if( NOT ${_PAR_NAME}_FOUND )
+      if( ${_PAR_NAME}_PATH )
+        message( FATAL_ERROR "${_PAR_NAME}_PATH was provided by user but package ${_PAR_NAME} wasn't found" )
+      endif()
+      if( ${PNAME}_PATH )
+        message( FATAL_ERROR "${PNAME}_PATH was provided by user but package ${_PAR_NAME} wasn't found" )
+      endif()
+    endif()
 
-		set( _ecmwf_paths ) # clear variable
-		ecbuild_list_extra_search_paths( ${_PAR_NAME} _ecmwf_paths )
+  endif()
 
-		if( _ecmwf_paths )
-			find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET NO_MODULE PATHS ${_ecmwf_paths} NO_DEFAULT_PATH )
-		endif()
+  # 3) search developer cache and recently configured packages in the CMake GUI if in DEVELOPER_MODE
+  #    otherwise only search CMAKE_PREFIX_PATH and <package>_PATH
 
-	endif()
+  if( NOT ${_PAR_NAME}_FOUND )
+    if (NO_DEV_BUILD_DIRS)
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 3) search CMAKE_PREFIX_PATH and \$${PNAME}_PATH")
+    else()
+      ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 3) search CMAKE_PREFIX_PATH and \$${PNAME}_PATH and package registry")
+    endif()
 
-	# 5) search system paths, for <package>-config.cmake
+    find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET NO_MODULE
+      COMPONENTS ${_PAR_COMPONENTS}
+      HINTS ENV ${PNAME}_PATH
+      ${NO_DEV_BUILD_DIRS}
+      NO_CMAKE_ENVIRONMENT_PATH
+      NO_SYSTEM_ENVIRONMENT_PATH
+      NO_CMAKE_SYSTEM_PATH
+      NO_CMAKE_SYSTEM_PACKAGE_REGISTRY )
 
-	if( NOT ${_PAR_NAME}_FOUND )
+  endif()
 
-		find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET NO_MODULE ${NO_DEV_BUILD_DIRS} )
+  # 4) search system paths, for <package>-config.cmake
 
-	endif()
+  if( NOT ${_PAR_NAME}_FOUND )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 5) search system paths, for ${_PAR_NAME}-config.cmake")
 
-	# 6) search system paths, using Find<package>.cmake if it exists
+    find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET NO_MODULE
+      COMPONENTS ${_PAR_COMPONENTS}
+      ${NO_DEV_BUILD_DIRS} )
 
-	if( NOT ${_PAR_NAME}_FOUND )
+  endif()
 
-		find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET MODULE )
+  # 5) search system paths, using Find<package>.cmake if it exists
 
-	endif()
+  if( NOT ${_PAR_NAME}_FOUND )
+    ecbuild_debug("ecbuild_find_package(${_PAR_NAME}): 6) search system paths, using Find${_PAR_NAME}.cmake if it exists")
 
-    # check version found is acceptable
+    find_package( ${_PAR_NAME} ${_${PNAME}_version} QUIET MODULE COMPONENTS ${_PAR_COMPONENTS} )
 
-    if( ${_PAR_NAME}_FOUND )
-        set( _version_acceptable 1 )
-        if( _PAR_VERSION )
-            if( ${_PAR_NAME}_VERSION )
-                if( _PAR_EXACT )
-                    if( NOT ${_PAR_NAME}_VERSION VERSION_EQUAL _PAR_VERSION )
-                        message( WARNING "${PROJECT_NAME} requires (exactly) ${_PAR_NAME} = ${_PAR_VERSION} -- found ${${_PAR_NAME}_VERSION}" )
-                        set( _version_acceptable 0 )
-                    endif()
-                else()
-                    if( _PAR_VERSION VERSION_LESS ${_PAR_NAME}_VERSION OR _PAR_VERSION VERSION_EQUAL ${_PAR_NAME}_VERSION )
-                        set( _version_acceptable 1 )
-                    else()
-                        if( NOT _PAR_QUIET )
-                            message( WARNING "${PROJECT_NAME} requires ${_PAR_NAME} >= ${_PAR_VERSION} -- found ${${_PAR_NAME}_VERSION}" )
-                        endif()
-                        set( _version_acceptable 0 )
-                    endif()
-                endif()
-            else()
-                if( NOT _PAR_QUIET )
-                    message( WARNING "${PROJECT_NAME} found ${_PAR_NAME} but no version information, so cannot check if satisfies ${_PAR_VERSION}" )
-                endif()
-                set( _version_acceptable 0 )
-            endif()
-        endif()
-    endif()
+  endif()
 
-    if( ${_PAR_NAME}_FOUND )
+  # check version found is acceptable
 
-        if( _version_acceptable )
-            set( ${PNAME}_FOUND ${${_PAR_NAME}_FOUND} )
+  if( ${_PAR_NAME}_FOUND )
+    set( _version_acceptable 1 )
+    if( _PAR_VERSION )
+      if( ${_PAR_NAME}_VERSION )
+        if( _PAR_EXACT )
+          if( NOT ${_PAR_NAME}_VERSION VERSION_EQUAL _PAR_VERSION )
+            message( WARNING "${PROJECT_NAME} requires (exactly) ${_PAR_NAME} = ${_PAR_VERSION} -- found ${${_PAR_NAME}_VERSION}" )
+            set( _version_acceptable 0 )
+          endif()
         else()
+          if( _PAR_VERSION VERSION_LESS ${_PAR_NAME}_VERSION OR _PAR_VERSION VERSION_EQUAL ${_PAR_NAME}_VERSION )
+            set( _version_acceptable 1 )
+          else()
             if( NOT _PAR_QUIET )
-                message( WARNING "${PROJECT_NAME} found ${_PAR_NAME} but with unsuitable version" )
+              message( WARNING "${PROJECT_NAME} requires ${_PAR_NAME} >= ${_PAR_VERSION} -- found ${${_PAR_NAME}_VERSION}" )
             endif()
-            set( ${PNAME}_FOUND 0 )
-            set( ${_PAR_NAME}_FOUND 0 )
+            set( _version_acceptable 0 )
+          endif()
         endif()
-
+      else()
+        if( NOT _PAR_QUIET )
+          message( WARNING "${PROJECT_NAME} found ${_PAR_NAME} but no version information, so cannot check if satisfies ${_PAR_VERSION}" )
+        endif()
+        set( _version_acceptable 0 )
+      endif()
+    endif()
+  endif()
+
+  if( ${_PAR_NAME}_FOUND )
+
+    if( _version_acceptable )
+      set( ${PNAME}_FOUND ${${_PAR_NAME}_FOUND} )
+    else()
+      if( NOT _PAR_QUIET )
+        message( WARNING "${PROJECT_NAME} found ${_PAR_NAME} but with unsuitable version" )
+      endif()
+      set( ${PNAME}_FOUND 0 )
+      set( ${_PAR_NAME}_FOUND 0 )
     endif()
 
-	### final messages
-
-	if( NOT ${_PAR_NAME}_FOUND )
-		if( _PAR_REQUIRED )
-			message( FATAL_ERROR
-              "    ${PROJECT_NAME} FAILED to find REQUIRED package ${_PAR_NAME}"
-              "    Provide location with \"-D ${PNAME}_DIR=/...\"\n"
-              "    or export ${PNAME}_DIR in environment"
-            )
-		else()
-			if( NOT _PAR_QUIET )
-				message( STATUS
-                      "${PROJECT_NAME} couldn't find package ${_PAR_NAME}.\n"
-                      "      Provide location with \"-D ${PNAME}_DIR=/...\"\n"
-                      "      or export ${PNAME}_DIR in environment" )
-			endif()
-		endif()
-	endif()
+  endif()
+
+  ### final messages
+
+  set( _failed_message
+    "\n"
+    "  ${PROJECT_NAME} FAILED to find package ${_PAR_NAME}\n"
+    "\n"
+    "    Provide location with \"-D${PNAME}_PATH=/...\" or \"-D${_PAR_NAME}_DIR=/...\" \n"
+    "    You may also export environment variables ${PNAME}_PATH or ${_PAR_NAME}_DIR\n"
+    "\n"
+    "  Values (note CAPITALISATION):\n"
+    "    ${PNAME}_PATH should contain the path to the install prefix (as in <install>/bin <install>/lib <install>/include)\n"
+    "    ${_PAR_NAME}_DIR should be a directory containing a <package>-config.cmake file (usually <install>/share/<package>/cmake)\n"
+    "\n"
+    )
+
+  if( ${_PAR_NAME}_FOUND OR ${PNAME}_FOUND )
+    if( NOT _PAR_QUIET )
+      message( STATUS "[${_PAR_NAME}] (${${_PAR_NAME}_VERSION})" )
+      foreach( var in ITEMS INCLUDE_DIR INCLUDE_DIRS DEFINITIONS LIBRARY LIBRARIES )
+        if( ${PNAME}_${var} )
+          message( STATUS "   ${PNAME}_${var} : [${${PNAME}_${var}}]" )
+        elseif( ${_PAR_NAME}_${var} )
+          message( STATUS "   ${_PAR_NAME}_${var} : [${${_PAR_NAME}_${var}}]" )
+        endif()
+      endforeach()
+    endif()
+  else()
+    if( _PAR_REQUIRED )
+      message( FATAL_ERROR ${_failed_message} " !! ${PROJECT_NAME} requires package ${_PAR_NAME} !!" )
+    else()
+      if( NOT _PAR_QUIET )
+        message( STATUS ${_failed_message} )
+      endif()
+    endif()
+  endif()
 
 endmacro()
diff --git a/cmake/ecbuild_find_perl.cmake b/cmake/ecbuild_find_perl.cmake
index 2d0cd02..f4c933a 100644
--- a/cmake/ecbuild_find_perl.cmake
+++ b/cmake/ecbuild_find_perl.cmake
@@ -6,40 +6,68 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-# OUTPUT:
+##############################################################################
+#.rst:
+#
+# ecbuild_find_perl
+# =================
+#
+# Find perl executable and its version. ::
+#
+#   ecbuild_find_perl( [ REQUIRED ] )
+#
+# Options
+# -------
+#
+# REQUIRED : optional
+#   fail if perl was not found
+#
+# Output variables
+# ----------------
+#
+# The following CMake variables are set if perl was found:
+#
+# :PERL_FOUND:          perl was found
+# :PERL_EXECUTABLE:     path to the perl executable
+# :PERL_VERSION:        perl version
+# :PERL_VERSION_STRING: perl version (same as ``PERL_VERSION``)
+#
+##############################################################################
 
 macro( ecbuild_find_perl )
 
-    # parse parameters
+  # parse parameters
 
-    set( options REQUIRED )
-    set( single_value_args )
-    set( multi_value_args  )
+  set( options REQUIRED )
+  set( single_value_args )
+  set( multi_value_args  )
 
-    cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_p_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_find_perl(): \"${_p_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_p_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_find_perl(): \"${_p_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-	find_package( Perl )
+  find_package( Perl )
 
-    if( NOT PERL_EXECUTABLE AND _p_REQUIRED )
-        message( FATAL_ERROR "Failed to find Perl (REQUIRED)" )
-    endif()
+  if( NOT PERL_EXECUTABLE AND _p_REQUIRED )
+    message( FATAL_ERROR "Failed to find Perl (REQUIRED)" )
+  endif()
 
-    if( PERL_EXECUTABLE )
+  if( PERL_EXECUTABLE )
 
-		execute_process( COMMAND ${PERL_EXECUTABLE} -V:version OUTPUT_VARIABLE  perl_version_output_variable  RESULT_VARIABLE  perl_version_return )
-		if( NOT perl_version_return )
-			string(REGEX REPLACE "version='([^']+)'.*" "\\1" PERL_VERSION ${perl_version_output_variable})
-		endif()
+    execute_process( COMMAND ${PERL_EXECUTABLE} -V:version OUTPUT_VARIABLE  perl_version_output_variable  RESULT_VARIABLE  perl_version_return )
+    if( NOT perl_version_return )
+      string(REGEX REPLACE "version='([^']+)'.*" "\\1" PERL_VERSION ${perl_version_output_variable})
+    endif()
+
+    # from cmake 2.8.8 onwards
+    if( NOT PERL_VERSION_STRING )
+      set( PERL_VERSION_STRING ${PERL_VERSION} )
+    endif()
 
-		# from cmake 2.8.8 onwards
-		if( NOT PERL_VERSION_STRING )
-			set( PERL_VERSION_STRING ${PERL_VERSION} )
-		endif()
+    ecbuild_debug("ecbuild_find_perl: found perl version ${PERL_VERSION_STRING} as ${PERL_EXECUTABLE}")
 
-	endif()
+  endif()
 
-endmacro( ecbuild_find_perl )
\ No newline at end of file
+endmacro( ecbuild_find_perl )
diff --git a/cmake/ecbuild_find_python.cmake b/cmake/ecbuild_find_python.cmake
index d207ee8..3209826 100644
--- a/cmake/ecbuild_find_python.cmake
+++ b/cmake/ecbuild_find_python.cmake
@@ -6,15 +6,44 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to find python
+##############################################################################
+#.rst:
+#
+# ecbuild_find_python
+# ===================
+#
+# Find Python interpreter, its version and the Python libraries. ::
+#
+#   ecbuild_find_python( [ VERSION <version> ] [ REQUIRED ] )
+#
+# Options
+# -------
+#
+# VERSION : optional
+#   minimum required version
+#
+# REQUIRED : optional
+#   fail if Python was not found
+#
+# Output variables
+# ----------------
+#
+# The following CMake variables are set if perl was found:
+#
+# :PYTHONINTERP_FOUND:    Python interpreter was found
+# :PYTHONLIBS_FOUND:      Python libraries were found
+# :PYTHON_FOUND:          Python was found (both interpreter and libraries)
+# :PYTHON_VERSION_MAJOR:  major version number
+# :PYTHON_VERSION_MINOR:  minor version number
+# :PYTHON_VERSION_PATCH:  patch version number
+# :PYTHON_VERSION_STRING: Python version
+# :PYTHON_INCLUDE_DIRS:   Python include directories
+# :PYTHON_LIBRARIES:      Python libraries
+# :PYTHON_SITE_PACKAGES:  Python site packages directory
+#
+##############################################################################
 
-# OUTPUT:
-#   PYTHONINTERP_FOUND
-#   PYTHONLIBS_FOUND
-#   PYTHON_INCLUDE_DIRS
-#   PYTHON_LIBRARIES
-#   PYTHON_SITE_PACKAGES
+set( __test_python ${CMAKE_CURRENT_LIST_DIR}/pymain.c )
 
 macro( ecbuild_find_python )
 
@@ -63,8 +92,9 @@ macro( ecbuild_find_python )
     endif()
 
     if( PYTHONINTERP_FOUND )
+        ecbuild_debug( "ecbuild_find_python: Found Python interpreter version ${PYTHON_VERSION_STRING} at ${PYTHON_EXECUTABLE}" )
 
-        # find pythonn config
+        # find python config
 
         if( PYTHON_EXECUTABLE AND EXISTS ${PYTHON_EXECUTABLE}-config )
             set(PYTHON_CONFIG ${PYTHON_EXECUTABLE}-config CACHE PATH "" FORCE)
@@ -78,6 +108,7 @@ macro( ecbuild_find_python )
         # that don't reliably report linking flags that will work.
         
         if( PYTHON_CONFIG AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL "OpenBSD" )
+            ecbuild_debug( "ecbuild_find_python: Searching for Python include directories and libraries using ${PYTHON_CONFIG}" )
             
             execute_process(COMMAND "${PYTHON_CONFIG}" --ldflags
                             OUTPUT_VARIABLE PYTHON_LIBRARIES
@@ -89,15 +120,13 @@ macro( ecbuild_find_python )
                             OUTPUT_STRIP_TRAILING_WHITESPACE
                             ERROR_QUIET)
 
-#           debug_var(PYTHON_LIBRARIES)
-#           debug_var(PYTHON_INCLUDE_DIR)
-
             string(REGEX REPLACE "^[-I]" "" PYTHON_INCLUDE_DIR "${PYTHON_INCLUDE_DIR}")
             string(REGEX REPLACE "[ ]-I" " " PYTHON_INCLUDE_DIR "${PYTHON_INCLUDE_DIR}")
             
             separate_arguments(PYTHON_INCLUDE_DIR)
 
         else() # revert to finding pythonlibs the standard way (cmake macro)
+            ecbuild_debug( "ecbuild_find_python: Searching for Python include directories and libraries using find_package(PythonLibs)" )
             
             find_package(PythonLibs)
             if( PYTHON_INCLUDE_PATH AND NOT PYTHON_INCLUDE_DIR )
@@ -106,18 +135,35 @@ macro( ecbuild_find_python )
 
         endif()
 
+        # Remove duplicate include directories
+        list(REMOVE_DUPLICATES PYTHON_INCLUDE_DIR)
+
+        # Test if we can link against the Python libraries and include Python.h
+        try_compile( PYTHON_LIBS_WORKING ${CMAKE_CURRENT_BINARY_DIR}
+                     ${__test_python}
+                     CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${PYTHON_INCLUDE_DIR}"
+                     LINK_LIBRARIES ${PYTHON_LIBRARIES} )
+
         # set output variables
 
-        find_package_handle_standard_args( PythonLibs DEFAULT_MSG PYTHON_INCLUDE_DIR PYTHON_LIBRARIES )
+        find_package_handle_standard_args( PythonLibs DEFAULT_MSG
+                                           PYTHON_INCLUDE_DIR PYTHON_LIBRARIES PYTHON_LIBS_WORKING )
+        ecbuild_debug( "ecbuild_find_python: PYTHON_INCLUDE_DIR=${PYTHON_INCLUDE_DIR}" )
+        ecbuild_debug( "ecbuild_find_python: PYTHON_LIBRARIES=${PYTHON_LIBRARIES}" )
 
         set( PYTHON_INCLUDE_DIRS ${PYTHON_INCLUDE_DIR} )
         set( PYTHON_INCLUDE_PATH ${PYTHON_INCLUDE_DIR} )
 
-        list( REMOVE_DUPLICATES PYTHON_INCLUDE_DIRS )
+        # Also set PYTHON_FOUND and Python_FOUND for compatibility with ecbuild_add_option
+        if( PYTHONLIBS_FOUND )
+          set( PYTHON_FOUND 1 )
+          set( Python_FOUND 1 )
+        endif()
 
         # find where python site-packages are ...
 
         execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE)
+        ecbuild_debug( "ecbuild_find_python: PYTHON_SITE_PACKAGES=${PYTHON_SITE_PACKAGES}" )
 
     endif()
 
diff --git a/cmake/ecbuild_generate_config_headers.cmake b/cmake/ecbuild_generate_config_headers.cmake
index abf9aac..53be8f3 100644
--- a/cmake/ecbuild_generate_config_headers.cmake
+++ b/cmake/ecbuild_generate_config_headers.cmake
@@ -6,42 +6,58 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# generates the config header fot the project with the system introspection done by CMake
+##############################################################################
+#.rst:
+#
+# ecbuild_generate_config_headers
+# ===============================
+#
+# Generates the ecBuild configuration header for the project with the system
+# introspection done by CMake. ::
+#
+#   ecbuild_generate_config_headers( [ DESTINATION <directory> ] )
+#
+# Options
+# -------
+#
+# DESTINATION : optional
+#   installation destination directory
+#
+##############################################################################
 
 function( ecbuild_generate_config_headers )
 
-    # parse parameters
+  # parse parameters
 
-    set( options )
-	set( single_value_args DESTINATION )
-    set( multi_value_args  )
+  set( options )
+  set( single_value_args DESTINATION )
+  set( multi_value_args  )
 
-	cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_generate_config_headers(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_generate_config_headers(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-	# generate list of compiler flags
+  # generate list of compiler flags
 
-	string( TOUPPER ${PROJECT_NAME} PNAME )
+  string( TOUPPER ${PROJECT_NAME} PNAME )
 
-	get_property( langs GLOBAL PROPERTY ENABLED_LANGUAGES )
+  get_property( langs GLOBAL PROPERTY ENABLED_LANGUAGES )
 
-	foreach( lang ${langs} )
-		set( EC_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} ${CMAKE_${lang}_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}" )
-	endforeach()
+  foreach( lang ${langs} )
+    set( EC_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} ${CMAKE_${lang}_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}" )
+  endforeach()
 
-	configure_file( ${ECBUILD_MACROS_DIR}/ecbuild_config.h.in  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}_ecbuild_config.h   )
+  configure_file( ${ECBUILD_MACROS_DIR}/ecbuild_config.h.in  ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}_ecbuild_config.h   )
 
-	# install ecbuild configuration
+  # install ecbuild configuration
 
-	set( _destination ${INSTALL_INCLUDE_DIR} )
-	if( _p_DESTINATION )
-		set( _destination ${_p_DESTINATION} )
-	endif()
+  set( _destination ${INSTALL_INCLUDE_DIR} )
+  if( _p_DESTINATION )
+    set( _destination ${_p_DESTINATION} )
+  endif()
 
-	install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}_ecbuild_config.h DESTINATION ${_destination} )
+  install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}_ecbuild_config.h DESTINATION ${_destination} )
 
 endfunction( ecbuild_generate_config_headers )
diff --git a/cmake/ecbuild_generate_rpc.cmake b/cmake/ecbuild_generate_rpc.cmake
index 5bd4f76..19fd3eb 100644
--- a/cmake/ecbuild_generate_rpc.cmake
+++ b/cmake/ecbuild_generate_rpc.cmake
@@ -6,8 +6,35 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to process rpcgen files
+##############################################################################
+#.rst:
+#
+# ecbuild_generate_rpc
+# ====================
+#
+# Process RPC (Remote Procedure Call) Language files using rpcgen. ::
+#
+#   ecbuild_generate_rpc( SOURCE <file>
+#                         [ TARGET_H <file> ]
+#                         [ TARGET_C <file> ]
+#                         [ DEPENDANT <file1> [ <file2> ... ] ] )
+#
+# Options
+# -------
+#
+# SOURCE : required
+#   RPC source file
+#
+# TARGET_H : optional (required if TARGET_C not given)
+#   name of header file to be generated
+#
+# TARGET_C : optional (required if TARGET_H not given)
+#   name of source file to be generated
+#
+# DEPENDANT : optional
+#  list of files which depend on the generated source and header files
+#
+##############################################################################
 
 macro( ecbuild_generate_rpc )
 
diff --git a/cmake/ecbuild_generate_yy.cmake b/cmake/ecbuild_generate_yy.cmake
index 391bed1..67ee422 100644
--- a/cmake/ecbuild_generate_yy.cmake
+++ b/cmake/ecbuild_generate_yy.cmake
@@ -6,108 +6,189 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# macro to process lex/yacc files
+##############################################################################
+#.rst:
+#
+# ecbuild_generate_yy
+# ===================
+#
+# Process lex/yacc files. ::
+#
+#   ecbuild_generate_yy( YYPREFIX <prefix>
+#                        YACC <file>
+#                        LEX <file>
+#                        DEPENDANT <file1> [ <file2> ... ]
+#                        [ SOURCE_DIR <dir> ]
+#                        [ YACC_TARGET <file> ]
+#                        [ LEX_TARGET <file> ]
+#                        [ YACC_FLAGS <flags> ]
+#                        [ LEX_FLAGS <flags> ]
+#                        [ BISON_FLAGS <flags> ]
+#                        [ FLEX_FLAGS <flags> ] )
+#
+# Options
+# -------
+#
+# YYPREFIX : required
+#   prefix to use for file and function names
+#
+# YACC : required
+#   base name of the yacc source file (without .y extension)
+#
+# LEX : required
+#   base name of the lex source file (without .l extension)
+#
+# DEPENDANT : required
+#  list of files which depend on the generated lex and yacc target files
+#
+# SOURCE_DIR : optional, defaults to CMAKE_CURRENT_SOURCE_DIR
+#   directory where yacc and lex source files are located
+#
+# YACC_TARGET : optional, defaults to YACC
+#   base name of the generated yacc target file (without .c extension)
+#
+# LEX_TARGET : optional, defaults to LEX
+#   base name of the generated lex target file (without .c extension)
+#
+# YACC_FLAGS : optional, defaults to -t
+#   flags to pass to yacc executable
+#
+# LEX_FLAGS : optional
+#   flags to pass to lex executable
+#
+# BISON_FLAGS : optional, defaults to -t
+#   flags to pass to bison executable
+#
+# FLEX_FLAGS : optional, defaults to -l
+#   flags to pass to flex executable
+#
+##############################################################################
 
 macro( ecbuild_generate_yy )
 
-	ecbuild_find_lexyacc() # find [ yacc|byson ] and [ lex|flex ]
+  ecbuild_find_lexyacc() # find [ yacc|byson ] and [ lex|flex ]
 
-	ecbuild_find_perl( REQUIRED )
+  ecbuild_find_perl( REQUIRED )
 
-    set( options )
-	set( single_value_args YYPREFIX YACC LEX LEX_FLAGS YACC_FLAGS FLEX_FLAGS BISON_FLAGS )
-    set( multi_value_args  DEPENDANT )
+  set( options )
+  set( single_value_args YYPREFIX YACC LEX SOURCE_DIR YACC_TARGET LEX_TARGET LEX_FLAGS YACC_FLAGS FLEX_FLAGS BISON_FLAGS )
+  set( multi_value_args  DEPENDANT )
 
-    cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-    if(_PAR_UNPARSED_ARGUMENTS)
-      message(FATAL_ERROR "Unknown keywords given to ecbuild_generate_yy(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
-    endif()
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_generate_yy(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-    if( NOT _PAR_YYPREFIX  )
-      message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the YYPREFIX.")
-    endif()
+  if( NOT _PAR_YYPREFIX  )
+    message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the YYPREFIX.")
+  endif()
 
-    if( NOT _PAR_YACC  )
-      message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the YACC file.")
-    endif()
+  if( NOT _PAR_YACC  )
+    message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the YACC file.")
+  endif()
 
-    if( NOT _PAR_LEX  )
-      message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the LEX file.")
-    endif()
+  if( NOT _PAR_LEX  )
+    message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the LEX file.")
+  endif()
 
-    if( NOT _PAR_DEPENDANT )
-      message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the DEPENDANT files.")
-    endif()
+  if( NOT _PAR_DEPENDANT )
+    message(FATAL_ERROR "The call to ecbuild_generate_yy() doesn't specify the DEPENDANT files.")
+  endif()
 
-    set( BASE ${_PAR_YYPREFIX}_${_PAR_YACC} )
+  set( BASE ${_PAR_YYPREFIX}_${_PAR_YACC} )
 
-	## default flags
+  ## default flags
 
-	if( NOT _PAR_LEX_FLAGS )
-		set( _PAR_LEX_FLAGS "" )
-	endif()
+  if( NOT _PAR_LEX_FLAGS )
+    set( _PAR_LEX_FLAGS "" )
+  endif()
 
-	if( NOT _PAR_FLEX_FLAGS )
-		set( _PAR_FLEX_FLAGS "-l" )
-	endif()
+  if( NOT _PAR_FLEX_FLAGS )
+    set( _PAR_FLEX_FLAGS "-l" )
+  endif()
 
-	if( NOT _PAR_YACC_FLAGS )
-		set( _PAR_YACC_FLAGS "-t" )
-	endif()
+  if( NOT _PAR_YACC_FLAGS )
+    set( _PAR_YACC_FLAGS "-t" )
+  endif()
 
-	if( NOT _PAR_BISON_FLAGS )
-		set( _PAR_BISON_FLAGS "-t" )
-	endif()
+  if( NOT _PAR_BISON_FLAGS )
+    set( _PAR_BISON_FLAGS "-t" )
+  endif()
 
-#    debug_var( BASE )
+  #debug_var( BASE )
 
-    set( ${BASE}yy_tmp_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC}.tmp.c )
-    set( ${BASE}yl_tmp_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_LEX}.tmp.c )
+  if( NOT _PAR_YACC_TARGET )
+    set ( _PAR_YACC_TARGET ${_PAR_YACC} )
+  endif()
 
-    set( ${BASE}yy_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC}.c )
-    set( ${BASE}yl_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_LEX}.c )
+  if ( NOT _PAR_LEX_TARGET )
+    set ( _PAR_LEX_TARGET ${_PAR_LEX} )
+  endif()
 
-    add_custom_target( ${_PAR_YYPREFIX}_${DEPENDANT} SOURCES ${_PAR_YACC}.y ${_PAR_LEX}.l )
+  set( ${BASE}yy_tmp_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC_TARGET}.tmp.c )
+  set( ${BASE}yh_tmp_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC_TARGET}.tmp.h )
+  set( ${BASE}yl_tmp_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_LEX_TARGET}.tmp.c )
 
-    if( BISON_FOUND )
-		bison_target( ${BASE}_parser  ${_PAR_YACC}.y  ${${BASE}yy_tmp_target} COMPILE_FLAGS "${_PAR_BISON_FLAGS}" )
-	else()
-		yacc_target( ${BASE}_parser  ${_PAR_YACC}.y   ${${BASE}yy_tmp_target} COMPILE_FLAGS "${_PAR_YACC_FLAGS}" )
-    endif()
+  set( ${BASE}yy_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC_TARGET}.c )
+  set( ${BASE}yh_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_YACC_TARGET}.h )
+  set( ${BASE}yl_target ${CMAKE_CURRENT_BINARY_DIR}/${_PAR_LEX_TARGET}.c )
 
-    if( FLEX_FOUND )
-		flex_target(  ${BASE}_scanner ${_PAR_LEX}.l   ${${BASE}yl_tmp_target} COMPILE_FLAGS "${_PAR_FLEX_FLAGS}" )
-        add_flex_bison_dependency(${BASE}_scanner ${BASE}_parser)
-    else()
-		lex_target(  ${BASE}_scanner ${_PAR_LEX}.l   ${${BASE}yl_tmp_target} COMPILE_FLAGS "${_PAR_LEX_FLAGS}" )
-        add_lex_yacc_dependency(${BASE}_scanner ${BASE}_parser)
-    endif()
+  if( NOT _PAR_SOURCE_DIR )
+    set( _PAR_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} )
+  endif()
+
+  add_custom_target( ${_PAR_YYPREFIX}_${DEPENDANT} SOURCES ${_PAR_SOURCE_DIR}/${_PAR_YACC}.y ${_PAR_SOURCE_DIR}/${_PAR_LEX}.l )
+
+  if( BISON_FOUND )
+    bison_target( ${BASE}_parser ${_PAR_SOURCE_DIR}/${_PAR_YACC}.y ${${BASE}yy_tmp_target} COMPILE_FLAGS "${_PAR_BISON_FLAGS}" )
+  else()
+    yacc_target( ${BASE}_parser ${_PAR_SOURCE_DIR}/${_PAR_YACC}.y ${${BASE}yy_tmp_target} COMPILE_FLAGS "${_PAR_YACC_FLAGS}" )
+  endif()
+
+  if( FLEX_FOUND )
+    flex_target( ${BASE}_scanner ${_PAR_SOURCE_DIR}/${_PAR_LEX}.l ${${BASE}yl_tmp_target} COMPILE_FLAGS "${_PAR_FLEX_FLAGS}" )
+    add_flex_bison_dependency(${BASE}_scanner ${BASE}_parser)
+  else()
+    lex_target( ${BASE}_scanner ${_PAR_SOURCE_DIR}/${_PAR_LEX}.l ${${BASE}yl_tmp_target} COMPILE_FLAGS "${_PAR_LEX_FLAGS}" )
+    add_lex_yacc_dependency(${BASE}_scanner ${BASE}_parser)
+  endif()
 
-    set_source_files_properties(${${BASE}yy_tmp_target} GENERATED)
-    set_source_files_properties(${${BASE}yl_tmp_target} GENERATED)
+  set_source_files_properties(${${BASE}yy_tmp_target} GENERATED)
+  set_source_files_properties(${${BASE}yh_tmp_target} GENERATED)
+  set_source_files_properties(${${BASE}yl_tmp_target} GENERATED)
 
-    add_custom_command(OUTPUT  ${${BASE}yy_target}
-                       COMMAND ${CMAKE_COMMAND} -E copy ${${BASE}yy_tmp_target} ${${BASE}yy_target}
-                       COMMAND ${PERL_EXECUTABLE} -pi -e 's/yy/${_PAR_YYPREFIX}/g' ${${BASE}yy_target}
-                       COMMAND ${PERL_EXECUTABLE} -pi -e 's/\\.tmp\\.c/\\.c/g' ${${BASE}yy_target}
-                       DEPENDS ${${BASE}yy_tmp_target}
+  add_custom_command(OUTPUT  ${${BASE}yy_target}
+    COMMAND ${CMAKE_COMMAND} -E copy ${${BASE}yy_tmp_target} ${${BASE}yy_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/yy/${_PAR_YYPREFIX}/g' ${${BASE}yy_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/\\.tmp\\.c/\\.c/g' ${${BASE}yy_target}
+    DEPENDS ${${BASE}yy_tmp_target}
     )
 
-    add_custom_command(OUTPUT  ${${BASE}yl_target}
-                       COMMAND ${CMAKE_COMMAND} -E copy ${${BASE}yl_tmp_target} ${${BASE}yl_target}
-                       COMMAND ${PERL_EXECUTABLE} -pi -e 's/yy/${_PAR_YYPREFIX}/g' ${${BASE}yl_target}
-                       COMMAND ${PERL_EXECUTABLE} -pi -e 's/\\.tmp\\.c/\\.c/g' ${${BASE}yl_target}
-                       DEPENDS ${${BASE}yl_tmp_target}
+  add_custom_command(OUTPUT  ${${BASE}yh_target}
+    COMMAND ${CMAKE_COMMAND} -E copy ${${BASE}yh_tmp_target} ${${BASE}yh_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/yy/${_PAR_YYPREFIX}/g' ${${BASE}yh_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/\\.tmp\\.h/\\.h/g' ${${BASE}yh_target}
+    DEPENDS ${${BASE}yh_tmp_target}
     )
 
-    set_source_files_properties(${${BASE}yy_target} GENERATED)
-    set_source_files_properties(${${BASE}yl_target} GENERATED)
+  add_custom_command(OUTPUT  ${${BASE}yl_target}
+    COMMAND ${CMAKE_COMMAND} -E copy ${${BASE}yl_tmp_target} ${${BASE}yl_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/yy/${_PAR_YYPREFIX}/g' ${${BASE}yl_target}
+    COMMAND ${PERL_EXECUTABLE} -pi -e 's/\\.tmp\\.c/\\.c/g' ${${BASE}yl_target}
+    DEPENDS ${${BASE}yl_tmp_target}
+    )
+
+  set_source_files_properties(${${BASE}yy_target} GENERATED)
+  set_source_files_properties(${${BASE}yh_target} GENERATED)
+  set_source_files_properties(${${BASE}yl_target} GENERATED)
 
-    foreach( file ${_PAR_DEPENDANT} )
-        set_source_files_properties( ${file} PROPERTIES
-                                    OBJECT_DEPENDS "${${BASE}yy_target};${${BASE}yl_target}" )
-    endforeach()
+  foreach( file ${_PAR_DEPENDANT} )
+    if( NOT IS_ABSOLUTE ${file})
+      set( file ${_PAR_SOURCE_DIR}/${file} )
+    endif()
+    set_source_files_properties( ${file} PROPERTIES
+        OBJECT_DEPENDS "${${BASE}yy_target};${${BASE}yh_target};${${BASE}yl_target}" )
+  endforeach()
 
 endmacro( ecbuild_generate_yy )
diff --git a/cmake/ecbuild_get_cxx11_flags.cmake b/cmake/ecbuild_get_cxx11_flags.cmake
new file mode 100644
index 0000000..5bfed07
--- /dev/null
+++ b/cmake/ecbuild_get_cxx11_flags.cmake
@@ -0,0 +1,71 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+##############################################################################
+#.rst:
+#
+# ecbuild_get_cxx11_flags
+# =======================
+#
+# Set the CMake variable ``${CXX11_FLAGS}`` to the C++11 flags for the current
+# compiler (based on macros from https://github.com/UCL/GreatCMakeCookOff). ::
+#
+#   ecbuild_get_cxx11_flags( CXX11_FLAGS )
+#
+##############################################################################
+
+function( ecbuild_get_cxx11_flags CXX11_FLAGS )
+
+  include(CheckCXXCompilerFlag)
+
+  # On older cmake versions + newer compilers, 
+  # the given version of CheckCXXCompilerFlags does not quite work.
+  if(CMAKE_VERSION VERSION_LESS 2.8.9)
+    macro (CHECK_CXX_COMPILER_FLAG _FLAG _RESULT)
+       set(SAFE_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}")
+       set(CMAKE_REQUIRED_DEFINITIONS "${_FLAG}")
+       CHECK_CXX_SOURCE_COMPILES("int main() { return 0;}" ${_RESULT}
+         # Some compilers do not fail with a bad flag
+         FAIL_REGEX "command line option .* is valid for .* but not for C\\\\+\\\\+" # GNU
+         FAIL_REGEX "unrecognized .*option"                     # GNU
+         FAIL_REGEX "unknown .*option"                          # Clang
+         FAIL_REGEX "ignoring unknown option"                   # MSVC
+         FAIL_REGEX "warning D9002"                             # MSVC, any lang
+         FAIL_REGEX "option.*not supported"                     # Intel
+         FAIL_REGEX "invalid argument .*option"                 # Intel
+         FAIL_REGEX "ignoring option .*argument required"       # Intel
+         FAIL_REGEX "[Uu]nknown option"                         # HP
+         FAIL_REGEX "[Ww]arning: [Oo]ption"                     # SunPro
+         FAIL_REGEX "command option .* is not recognized"       # XL
+         FAIL_REGEX "not supported in this configuration; ignored"       # AIX
+         FAIL_REGEX "File with unknown suffix passed to linker" # PGI
+         FAIL_REGEX "WARNING: unknown flag:"                    # Open64
+         )
+       set (CMAKE_REQUIRED_DEFINITIONS "${SAFE_CMAKE_REQUIRED_DEFINITIONS}")
+    endmacro ()
+  endif(CMAKE_VERSION VERSION_LESS 2.8.9)
+
+  check_cxx_compiler_flag(-std=c++11 has_std_cpp11)
+  check_cxx_compiler_flag(-std=c++0x has_std_cpp0x)
+  if(MINGW) 
+    check_cxx_compiler_flag(-std=gnu++11 has_std_gnupp11)
+    check_cxx_compiler_flag(-std=gnu++0x has_std_gnupp0x)
+  endif(MINGW)
+  if(has_std_gnupp11)
+    set(${CXX11_FLAGS} "-std=gnu++11" PARENT_SCOPE)
+  elseif(has_std_gnupp0x)
+    set(${CXX11_FLAGS} "-std=gnu++0x" PARENT_SCOPE)
+  elseif(has_std_cpp11) 
+    set(${CXX11_FLAGS} "-std=c++11" PARENT_SCOPE)
+  elseif(has_std_cpp0x)
+    set(${CXX11_FLAGS} "-std=c++0x" PARENT_SCOPE)
+  else()
+    message(FATAL ERROR "Could not detect C++11 flags")
+  endif(has_std_gnupp11)
+
+endfunction()
diff --git a/cmake/ecbuild_get_date.cmake b/cmake/ecbuild_get_date.cmake
index afe3d09..8c24623 100644
--- a/cmake/ecbuild_get_date.cmake
+++ b/cmake/ecbuild_get_date.cmake
@@ -6,8 +6,18 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# get date macro
+##############################################################################
+#.rst:
+#
+# ecbuild_get_date
+# ================
+#
+# Set the CMake variable ``${DATE}`` to the current date in the form
+# YYYY.mm.DD. ::
+#
+#   ecbuild_get_date( DATE )
+#
+##############################################################################
 
 macro(ecbuild_get_date RESULT)
     if(UNIX)
@@ -18,8 +28,18 @@ macro(ecbuild_get_date RESULT)
     endif()
 endmacro(ecbuild_get_date)
 
-############################################################################################
-# get timestamp
+##############################################################################
+#.rst:
+#
+# ecbuild_get_timestamp
+# =====================
+#
+# Set the CMake variable ``${TIMESTAMP}`` to the current date and time in the
+# form YYYYmmDDHHMMSS. ::
+#
+#   ecbuild_get_timestamp( TIMESTAMP )
+#
+##############################################################################
 
 macro(ecbuild_get_timestamp RESULT)
     if(UNIX)
diff --git a/cmake/ecbuild_get_test_data.cmake b/cmake/ecbuild_get_test_data.cmake
index d50ed6c..b1cc32d 100644
--- a/cmake/ecbuild_get_test_data.cmake
+++ b/cmake/ecbuild_get_test_data.cmake
@@ -1,72 +1,121 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
-# In applying this licence, ECMWF does not waive the privileges and immunities 
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
 ##############################################################################
+
 # function for downloading test data
 
 function( _download_test_data _p_NAME _p_DIRNAME )
 
-    # TODO: make that 'at ecmwf'
-    #if(1)
-    #unset(ENV{no_proxy})
-    #unset(ENV{NO_PROXY})
-    #set(ENV{http_proxy} "http://proxy.ecmwf.int:3333")
-    #endif()
-
-    find_program( CURL_PROGRAM curl )
+  # TODO: make that 'at ecmwf'
+  #if(1)
+  #unset(ENV{no_proxy})
+  #unset(ENV{NO_PROXY})
+  #set(ENV{http_proxy} "http://proxy.ecmwf.int:3333")
+  #endif()
 
-    if( CURL_PROGRAM )
+  find_program( CURL_PROGRAM curl )
 
-		add_custom_command( OUTPUT ${_p_NAME}
-			COMMENT "(curl) downloading http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME}"
-			COMMAND ${CURL_PROGRAM} --silent --show-error --fail --output ${_p_NAME} http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME} )
+  if( CURL_PROGRAM )
 
-    else()
+    add_custom_command( OUTPUT ${_p_NAME}
+      COMMENT "(curl) downloading http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME}"
+      COMMAND ${CURL_PROGRAM} --silent --show-error --fail --output ${_p_NAME}
+              http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME} )
 
-        find_program( WGET_PROGRAM wget )
+  else()
 
-        if( WGET_PROGRAM )
+    find_program( WGET_PROGRAM wget )
 
-				 add_custom_command( OUTPUT ${_p_NAME}
-						COMMENT "(wget) downloading http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME}"
-						COMMAND ${WGET_PROGRAM} -nv -O ${_p_NAME} http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME} )
+    if( WGET_PROGRAM )
 
-				else()
+      add_custom_command( OUTPUT ${_p_NAME}
+        COMMENT "(wget) downloading http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME}"
+        COMMAND ${WGET_PROGRAM} -nv -O ${_p_NAME}
+                http://download.ecmwf.org/test-data/${_p_DIRNAME}/${_p_NAME} )
 
-					if( WARNING_CANNOT_DOWNLOAD_TEST_DATA )
-						message( WARNING "Couldn't find curl neither wget -- cannot download test data from server.\nPlease obtain the test data by other means and pleace it in the build directory." )
-						set( WARNING_CANNOT_DOWNLOAD_TEST_DATA 1 CACHE INTERNAL "Couldn't find curl neither wget -- cannot download test data from server" )
-						mark_as_advanced( WARNING_CANNOT_DOWNLOAD_TEST_DATA )
-					endif()
+    else()
 
-        endif()
+      if( WARNING_CANNOT_DOWNLOAD_TEST_DATA )
+        message( WARNING "Couldn't find curl neither wget -- cannot download test data from server.\nPlease obtain the test data by other means and pleace it in the build directory." )
+        set( WARNING_CANNOT_DOWNLOAD_TEST_DATA 1 CACHE INTERNAL "Couldn't find curl neither wget -- cannot download test data from server" )
+        mark_as_advanced( WARNING_CANNOT_DOWNLOAD_TEST_DATA )
+      endif()
 
     endif()
 
-endfunction()
+  endif()
 
+endfunction()
 
 ##############################################################################
-# function for getting test data
+#.rst:
+#
+# ecbuild_get_test_data
+# =====================
+#
+# Download a test data set at build time. ::
+#
+#   ecbuild_get_test_data( NAME <name>
+#                          [ TARGET <target> ]
+#                          [ DIRNAME <dir> ]
+#                          [ MD5 <hash> ]
+#                          [ NOCHECK ] )
+#
+# curl or wget is required (curl is preferred if available).
+#
+# Options
+# -------
+#
+# NAME : required
+#   name of the test data file
+#
+# TARGET : optional, defaults to test_data_<name>
+#   CMake target name
+#
+# DIRNAME : optional, defaults to <project>/<relative path to current dir>
+#   directory in which the test data resides
+#
+# MD5 : optional, ignored if NOCHECK is given
+#   md5 checksum of the data set to verify. If not given and NOCHECK is *not*
+#   set, download the md5 checksum and verify
+#
+# NOCHECK : optional
+#   do not verify the md5 checksum of the data file
+#
+# Usage
+# -----
+#
+# Download test data from ``http://download.ecmwf.org/test-data/<DIRNAME>/<NAME>``
+#
+# If the ``DIRNAME`` argument is not given, the project name followed by the
+# relative path from the root directory to the current directory is used.
+#
+# By default, the downloaded file is verified against an md5 checksum, either
+# given as the ``MD5`` argument or downloaded from the server otherwise. Use
+# the argument ``NOCHECK`` to disable this check.
+#
+# Examples
+# --------
 #
-# examples:
+# Do not verify the checksum: ::
 #
-## no check done
-#    ecbuild_get_test_data( NAME msl.grib NOCHECK )
+#   ecbuild_get_test_data( NAME msl.grib NOCHECK )
 #
-## checksum agains remote md5 file
-#    ecbuild_get_test_data( NAME msl.grib )
+# Checksum agains remote md5 file: ::
 #
-## checksum agains local md5
-#    ecbuild_get_test_data( NAME msl.grib MD5 f69ca0929d1122c7878d19f32401abe9 )
+#   ecbuild_get_test_data( NAME msl.grib )
 #
-## (DEPRECATED) checksum agains local sha1
-#    ecbuild_get_test_data( NAME msl.grib SHA1 5a8e8c57c510b64e31863ca47cfc3b65971089d9 )
+# Checksum agains local md5: ::
+#
+#   ecbuild_get_test_data( NAME msl.grib MD5 f69ca0929d1122c7878d19f32401abe9 )
+#
+##############################################################################
 
 function( ecbuild_get_test_data )
 
@@ -177,16 +226,69 @@ function( ecbuild_get_test_data )
 endfunction(ecbuild_get_test_data)
 
 ##############################################################################
-# function for getting test data
+#.rst:
+#
+# ecbuild_get_test_multidata
+# ==========================
+#
+# Download multiple test data sets at build time. ::
+#
+#   ecbuild_get_test_multidata( NAMES <name1> [ <name2> ... ]
+#                               TARGET <target>
+#                               [ DIRNAME <dir> ]
+#                               [ NOCHECK ] )
+#
+# curl or wget is required (curl is preferred if available).
+#
+# Options
+# -------
+#
+# NAMES : required
+#   list of names of the test data files
+#
+# TARGET : optional
+#   CMake target name
+#
+# DIRNAME : optional, defaults to <project>/<relative path to current dir>
+#   directory in which the test data resides
+#
+# NOCHECK : optional
+#   do not verify the md5 checksum of the data file
 #
-# examples:
+# Usage
+# -----
 #
-## no check done
-#    ecbuild_get_test_multidata( TARGET get_foobar_data NAMES foo.grib bar.grib DIRNAME test/data/dir NOCHECK )
+# Download test data from ``http://download.ecmwf.org/test-data/<DIRNAME>``
+# for each name given in the list of ``NAMES``. Each name may contain a
+# relative path, which is appended to ``DIRNAME`` and may be followed by an
+# md5 checksum, separated with a ``:`` (the name must not contain spaces).
 #
-## check for remote md5
-#    ecbuild_get_test_multidata( TARGET get_foobar_data NAMES foo.grib bar.grib DIRNAME test/data/dir )
+# If the ``DIRNAME`` argument is not given, the project name followed by the
+# relative path from the root directory to the current directory is used.
 #
+# By default, each downloaded file is verified against an md5 checksum, either
+# given as part of the name as described above or a remote checksum downloaded
+# from the server. Use the argument ``NOCHECK`` to disable this check.
+#
+# Examples
+# --------
+#
+# Do not verify checksums: ::
+#
+#   ecbuild_get_test_multidata( TARGET get_grib_data NAMES foo.grib bar.grib
+#                               DIRNAME test/data/dir NOCHECK )
+#
+# Checksums agains remote md5 file: ::
+#
+#   ecbuild_get_test_multidata( TARGET get_grib_data NAMES foo.grib bar.grib
+#                               DIRNAME test/data/dir )
+#
+# Checksum agains local md5: ::
+#
+#   ecbuild_get_test_multidata( TARGET get_grib_data DIRNAME test/data/dir
+#                               NAMES msl.grib:f69ca0929d1122c7878d19f32401abe9 )
+#
+##############################################################################
 
 function( ecbuild_get_test_multidata )
 
@@ -259,13 +361,19 @@ endfunction()\n\n" )
         #debug_var(_name)
         #debug_var(_md5)
 
-        ecbuild_get_test_data( TARGET __get_data_${_p_TARGET}_${_name} NAME ${_file} ${_dirname} ${_md5} ${_nocheck} )
+        ecbuild_get_test_data(
+            TARGET __get_data_${_p_TARGET}_${_name}
+            NAME ${_file} ${_dirname} ${_md5} ${_nocheck} )
 
-        file( APPEND ${_script} "exec_check( ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target __get_data_${_p_TARGET}_${_name} )\n" )
+        # The option /fast disables dependency checking on a target, see
+        # https://cmake.org/Wiki/CMake_FAQ#Is_there_a_way_to_skip_checking_of_dependent_libraries_when_compiling.3F
+        file( APPEND ${_script}
+            "exec_check( ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target __get_data_${_p_TARGET}_${_name}/fast )\n" )
 
     endforeach()
 
-    add_test(  NAME ${_p_TARGET} COMMAND ${CMAKE_COMMAND} -P ${_script} )
+    if( ENABLE_TESTS )
+      add_test(  NAME ${_p_TARGET} COMMAND ${CMAKE_COMMAND} -P ${_script} )
+    endif()
 
 endfunction(ecbuild_get_test_multidata)
-
diff --git a/cmake/ecbuild_git.cmake b/cmake/ecbuild_git.cmake
new file mode 100644
index 0000000..42124db
--- /dev/null
+++ b/cmake/ecbuild_git.cmake
@@ -0,0 +1,307 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+set( ECBUILD_GIT  ON  CACHE BOOL "Turn on/off ecbuild_git() function" )
+
+if( ECBUILD_GIT )
+
+  find_package(Git)
+
+  set( ECMWF_USER $ENV{USER} CACHE STRING "ECMWF git user" )
+  set( ECMWF_GIT  SSH        CACHE STRING "ECMWF git protocol" )
+
+  set( ECMWF_GIT_SSH   "ssh://git@software.ecmwf.int:7999"                  CACHE INTERNAL "ECMWF ssh address" )
+  set( ECMWF_GIT_HTTPS "https://${ECMWF_USER}@software.ecmwf.int/stash/scm" CACHE INTERNAL "ECMWF https address" )
+
+  if( ECMWF_GIT MATCHES "[Ss][Ss][Hh]" )
+    set( ECMWF_GIT_ADDRESS ${ECMWF_GIT_SSH} CACHE INTERNAL "" )
+  else()
+    set( ECMWF_GIT_ADDRESS ${ECMWF_GIT_HTTPS} CACHE INTERNAL "" )
+  endif()
+
+endif()
+
+##############################################################################
+#.rst:
+#
+# ecbuild_git
+# ===========
+#
+# Manages an external Git repository. ::
+#
+#   ecbuild_git( PROJECT <name>
+#                DIR <directory>
+#                URL <giturl>
+#                [ BRANCH <gitbranch> | TAG <gittag> ]
+#                [ UPDATE | NOREMOTE ] )
+#                [ MANUAL ] )
+#
+# Options
+# -------
+#
+# PROJECT : required
+#   project name for the Git repository to be managed
+#
+# DIR : required
+#   directory to clone the repository into (can be relative)
+#
+# URL : required
+#   Git URL of the remote repository to clone (see ``git help clone``)
+#
+# BRANCH : optional, cannot be combined with TAG
+#   Git branch to check out
+#
+# TAG : optional, cannot be combined with BRANCH
+#   Git tag or commit id to check out
+#
+# UPDATE : optional, requires BRANCH, cannot be combined with NOREMOTE
+#   Create a CMake target update to fetch changes from the remote repository
+#
+# NOREMOTE : optional, cannot be combined with UPDATE
+#   Do not fetch changes from the remote repository
+#
+# MANUAL : optional
+#   Do not automatically switch branches or tags
+#
+##############################################################################
+
+macro( ecbuild_git )
+
+  set( options UPDATE NOREMOTE MANUAL )
+  set( single_value_args PROJECT DIR URL TAG BRANCH )
+  set( multi_value_args )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${_FIRST_ARG} ${ARGN} )
+
+  if( DEFINED _PAR_BRANCH AND DEFINED _PAR_TAG )
+    message( FATAL_ERROR "Cannot defined both BRANCH and TAG in macro ecbuild_git" )
+  endif()
+
+  if( _PAR_UPDATE AND _PAR_NOREMOTE )
+    message( FATAL_ERROR "Cannot pass both NOREMOTE and UPDATE in macro ecbuild_git" )
+  endif()
+
+  if(_PAR_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_git(): \"${_PAR_UNPARSED_ARGUMENTS}\"")
+  endif()
+
+  if( ECBUILD_GIT )
+
+    set( _needs_switch 0 )
+
+    get_filename_component( ABS_PAR_DIR "${_PAR_DIR}" ABSOLUTE )
+    get_filename_component( PARENT_DIR  "${_PAR_DIR}/.." ABSOLUTE )
+
+    ### clone if no directory
+
+    if( NOT EXISTS "${_PAR_DIR}" )
+
+      message( STATUS "Cloning ${_PAR_PROJECT} from ${_PAR_URL} into ${_PAR_DIR}...")
+      execute_process(
+        COMMAND ${GIT_EXECUTABLE} "clone" ${_PAR_URL} ${clone_args} ${_PAR_DIR} "-q"
+        RESULT_VARIABLE nok ERROR_VARIABLE error
+        WORKING_DIRECTORY "${PARENT_DIR}")
+      if(nok)
+        message(FATAL_ERROR "${_PAR_DIR} git clone failed: ${error}\n")
+      endif()
+      message( STATUS "${_PAR_DIR} retrieved.")
+      set( _needs_switch 1 )
+
+    endif()
+
+    ### check current tag and sha1
+
+    if( IS_DIRECTORY "${_PAR_DIR}/.git" )
+
+      execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
+                       OUTPUT_VARIABLE _sha1 RESULT_VARIABLE nok ERROR_VARIABLE error
+                       OUTPUT_STRIP_TRAILING_WHITESPACE
+                       WORKING_DIRECTORY "${ABS_PAR_DIR}" )
+      if(nok)
+        message(STATUS "git rev-parse HEAD on ${_PAR_DIR} failed:\n ${error}")
+      endif()
+
+      execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
+                       OUTPUT_VARIABLE _current_branch RESULT_VARIABLE nok ERROR_VARIABLE error
+                       OUTPUT_STRIP_TRAILING_WHITESPACE
+                       WORKING_DIRECTORY "${ABS_PAR_DIR}" )
+      if( nok OR _current_branch STREQUAL "" )
+        message(STATUS "git rev-parse --abbrev-ref HEAD on ${_PAR_DIR} failed:\n ${error}")
+      endif()
+
+      #message(STATUS "git describe --exact-match --abbrev=0 @ ${ABS_PAR_DIR}")
+      execute_process( COMMAND ${GIT_EXECUTABLE} describe --exact-match --abbrev=0
+                       OUTPUT_VARIABLE _current_tag RESULT_VARIABLE nok ERROR_VARIABLE error
+                       OUTPUT_STRIP_TRAILING_WHITESPACE  ERROR_STRIP_TRAILING_WHITESPACE
+                       WORKING_DIRECTORY "${ABS_PAR_DIR}" )
+
+      if( error MATCHES "no tag exactly matches" OR error MATCHES "No names found" )
+        unset( _current_tag )
+      else()
+        if( nok )
+          message(STATUS "git describe --exact-match --abbrev=0 on ${_PAR_DIR} failed:\n ${error}")
+        endif()
+      endif()
+
+      if( NOT _current_tag ) # try nother method
+        #message(STATUS "git name-rev --tags --name-only @ ${ABS_PAR_DIR}")
+        execute_process( COMMAND ${GIT_EXECUTABLE} name-rev --tags --name-only ${_sha1}
+                         OUTPUT_VARIABLE _current_tag RESULT_VARIABLE nok ERROR_VARIABLE error
+                         OUTPUT_STRIP_TRAILING_WHITESPACE
+                         WORKING_DIRECTORY "${ABS_PAR_DIR}" )
+        if( nok OR _current_tag STREQUAL "" )
+          message(STATUS "git name-rev --tags --name-only on ${_PAR_DIR} failed:\n ${error}")
+        endif()
+      endif()
+
+    endif()
+
+    if( NOT _PAR_MANUAL AND DEFINED _PAR_BRANCH AND NOT "${_current_branch}" STREQUAL "${_PAR_BRANCH}" )
+      set( _needs_switch 1 )
+    endif()
+
+    if( NOT _PAR_MANUAL AND DEFINED _PAR_TAG AND NOT "${_current_tag}" STREQUAL "${_PAR_TAG}" )
+      set( _needs_switch 1 )
+    endif()
+
+    if( DEFINED _PAR_BRANCH AND _PAR_UPDATE AND NOT _PAR_NOREMOTE )
+
+      add_custom_target( git_update_${_PAR_PROJECT}
+                         COMMAND "${GIT_EXECUTABLE}" pull -q
+                         WORKING_DIRECTORY "${ABS_PAR_DIR}"
+                         COMMENT "git pull of branch ${_PAR_BRANCH} on ${_PAR_DIR}" )
+
+      set( git_update_targets "git_update_${_PAR_PROJECT};${git_update_targets}" )
+
+    endif()
+
+    ### updates
+
+    if( _needs_switch AND IS_DIRECTORY "${_PAR_DIR}/.git" )
+
+      # debug_here( ABS_PAR_DIR )
+      # debug_here( _sha1 )
+      # debug_here( _current_branch )
+      # debug_here( _current_tag )
+      # debug_here( _PAR_TAG )
+      # debug_here( _PAR_BRANCH )
+      # debug_here( _needs_switch )
+      # debug_here( _PAR_UPDATE )
+
+      if( DEFINED _PAR_BRANCH )
+        set ( _gitref ${_PAR_BRANCH} )
+        message(STATUS "Updating ${_PAR_PROJECT} to head of BRANCH ${_PAR_BRANCH}...")
+      else()
+        message(STATUS "Updating ${_PAR_PROJECT} to TAG ${_PAR_TAG}...")
+        set ( _gitref ${_PAR_TAG} )
+      endif()
+
+      # fetching latest tags and branches
+
+      if( NOT _PAR_NOREMOTE )
+
+        message(STATUS "git fetch --all @ ${ABS_PAR_DIR}")
+        execute_process( COMMAND "${GIT_EXECUTABLE}" fetch --all -q
+                         RESULT_VARIABLE nok ERROR_VARIABLE error
+                         WORKING_DIRECTORY "${ABS_PAR_DIR}")
+        if(nok)
+          message(STATUS "git fetch --all in ${_PAR_DIR} failed:\n ${error}")
+        endif()
+
+        message(STATUS "git fetch --all --tags @ ${ABS_PAR_DIR}")
+        execute_process( COMMAND "${GIT_EXECUTABLE}" fetch --all --tags -q
+                         RESULT_VARIABLE nok ERROR_VARIABLE error
+                         WORKING_DIRECTORY "${ABS_PAR_DIR}")
+        if(nok)
+          message(STATUS "git fetch --all --tags in ${_PAR_DIR} failed:\n ${error}")
+        endif()
+
+      else()
+        message(STATUS "${_PAR_DIR} marked NOREMOTE : Skipping git fetch")
+      endif()
+
+      # checking out gitref
+
+      message(STATUS "git checkout ${_gitref} @ ${ABS_PAR_DIR}")
+      execute_process( COMMAND "${GIT_EXECUTABLE}" checkout -q "${_gitref}"
+                       RESULT_VARIABLE nok ERROR_VARIABLE error
+                       WORKING_DIRECTORY "${ABS_PAR_DIR}")
+      if(nok)
+        message(FATAL_ERROR "git checkout ${_gitref} on ${_PAR_DIR} failed:\n ${error}")
+      endif()
+
+      if( DEFINED _PAR_BRANCH AND _PAR_UPDATE ) #############################################################################
+
+        execute_process( COMMAND "${GIT_EXECUTABLE}" pull -q
+                         RESULT_VARIABLE nok ERROR_VARIABLE error
+                         WORKING_DIRECTORY "${ABS_PAR_DIR}")
+        if(nok)
+          message(STATUS "git pull of branch ${_PAR_BRANCH} on ${_PAR_DIR} failed:\n ${error}")
+        endif()
+
+      endif() ####################################################################################
+
+    endif( _needs_switch AND IS_DIRECTORY "${_PAR_DIR}/.git" )
+
+  endif( ECBUILD_GIT )
+
+endmacro()
+
+##############################################################################
+#.rst:
+#
+# ecbuild_stash
+# =============
+#
+# Manages an external Git repository on ECMWF Stash. ::
+#
+#   ecbuild_stash( PROJECT <name>
+#                  DIR <directory>
+#                  STASH <repository>
+#                  [ BRANCH <gitbranch> | TAG <gittag> ]
+#                  [ UPDATE | NOREMOTE ] )
+#                  [ MANUAL ] )
+#
+# Options
+# -------
+#
+# PROJECT : required
+#   project name for the Git repository to be managed
+#
+# DIR : required
+#   directory to clone the repository into (can be relative)
+#
+# STASH : required
+#   Stash repository in the form <project>/<repository>
+#
+# BRANCH : optional, cannot be combined with TAG
+#   Git branch to check out
+#
+# TAG : optional, cannot be combined with BRANCH
+#   Git tag or commit id to check out
+#
+# UPDATE : optional, requires BRANCH, cannot be combined with NOREMOTE
+#   Create a CMake target update to fetch changes from the remote repository
+#
+# NOREMOTE : optional, cannot be combined with UPDATE
+#   Do not fetch changes from the remote repository
+#
+# MANUAL : optional
+#   Do not automatically switch branches or tags
+#
+##############################################################################
+
+macro( ecmwf_stash )
+
+  set( options )
+  set( single_value_args STASH )
+  set( multi_value_args )
+  cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${_FIRST_ARG} ${ARGN} )
+
+  ecbuild_git( URL "${ECMWF_GIT_ADDRESS}/${_PAR_STASH}.git" ${_PAR_UNPARSED_ARGUMENTS} )
+
+endmacro()
diff --git a/cmake/ecbuild_install_package.cmake b/cmake/ecbuild_install_project.cmake
similarity index 69%
rename from cmake/ecbuild_install_package.cmake
rename to cmake/ecbuild_install_project.cmake
index dec046f..fa4d26d 100644
--- a/cmake/ecbuild_install_package.cmake
+++ b/cmake/ecbuild_install_project.cmake
@@ -1,15 +1,77 @@
 # (C) Copyright 1996-2014 ECMWF.
-# 
+#
 # This software is licensed under the terms of the Apache Licence Version 2.0
-# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
-# In applying this licence, ECMWF does not waive the privileges and immunities 
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-###############################################################################
+##############################################################################
+#.rst:
+#
+# ecbuild_install_project
+# =======================
+#
+# Set up packaging and export configuration. ::
+#
+#   ecbuild_install_project( NAME <name> [ DESCRIPTION <description> ] )
+#
+# Options
+# -------
+#
+# NAME : required
+#   project name used for packaging
+#
+# DESCRIPTION : optional
+#   project description used for packaging
+#
+# Usage
+# -----
+#
+# ``ecbuild_install_project`` should be called at the very end of any ecBuild
+# project (only followed by ``ecbuild_print_summary``), sets up packaging of
+# the project with cpack and exports the configuration and targets for other
+# projects to use.
+#
+# In a top-level project, the following files are generated:
+#
+# :<project>-config.cmake:         default project configuration
+# :<project>-config-version.cmake: project version number
+# :<project>-import.cmake:         extra project configuration (optional)
+# :<project>-config.cmake.tpls:    3rd party project configurations
+# :<project>-targets.cmake:        exported targets
+#
+# For ``<project>-import.cmake`` to be exported to build and install tree,
+# ``<project>-import.cmake`` or ``<project>-import.cmake.in`` must exist in
+# the source tree. ``<project>-config.cmake.in`` and
+# ``<project>-config-version.cmake.in`` can be provided in the source tree to
+# override the default templates used to generate ``<project>-config.cmake``
+# and ``<project>-config-version.cmake``.
+#
+# In DEVELOPER_MODE, the build tree location is also added to the CMake user
+# package registry.
+#
+# If the project is added as a subdirectory, the following CMake variables
+# are set in the parent scope:
+#
+# :<PROJECT>_FOUND:            set to ``TRUE``
+# :<project>_FOUND:            set to ``TRUE``
+# :<PROJECT>_VERSION:          version string
+# :<project>_VERSION:          version string
+# :<PROJECT>_INCLUDE_DIRS:     list of include directories
+# :<PROJECT>_LIBRARIES:        list of libraries
+# :<PROJECT>_DEFINITIONS:      list of compiler definitions
+# :<PROJECT>_TPLS:             list of 3rd party dependencies
+# :<PROJECT>_TPL_LIBRARIES:    libraries of 3rd party dependencies
+# :<PROJECT>_TPL_DEFINITIONS:  compiler definitions of 3rd party dependencies
+# :<PROJECT>_TPL_INCLUDE_DIRS: include directories of 3rd party dependencies
+# :<PROJECT>_FEATURES:         list of enabled features
+# :<PROJECT>_HAVE_<FEATURE>:   set to 1 for each enabled features
+#
+##############################################################################
 
-macro( ecbuild_install_project )
 
+macro( ecbuild_install_project )
 
     set( options )
     set( single_value_args NAME DESCRIPTION )
@@ -27,9 +89,9 @@ macro( ecbuild_install_project )
 
     ### PACKAGING ########################################################
 
-    string( TOUPPER ${PROJECT_NAME} PNAME )
-    string( TOLOWER ${PROJECT_NAME} LNAME )
-    
+    set( PNAME ${PROJECT_NAME_CAPS} )
+    set( LNAME ${PROJECT_NAME_LOWCASE} )
+
     # components
 
     #    if( DEFINED _PAR_COMPONENTS )
@@ -37,7 +99,7 @@ macro( ecbuild_install_project )
     #    else()
     #        set(CPACK_COMPONENTS_ALL   "${PROJECT_NAME}")
     #    endif()
-    
+
     # name, version, etc ...
 
     set(CPACK_PACKAGE_NAME      "${_PAR_NAME}")
@@ -68,17 +130,17 @@ macro( ecbuild_install_project )
     if( EXISTS ${PROJECT_SOURCE_DIR}/INSTALL )
         set(CPACK_PACKAGE_DESCRIPTION_FILE "${PROJECT_SOURCE_DIR}/INSTALL")
     endif()
-	if( EXISTS ${PROJECT_SOURCE_DIR}/LICENSE )
+    if( EXISTS ${PROJECT_SOURCE_DIR}/LICENSE )
         set(CPACK_RESOURCE_FILE_LICENSE    "${PROJECT_SOURCE_DIR}/LICENSE")
     endif()
 
     # set(CPACK_PACKAGE_EXECUTABLES ${ECBUILD_ALL_EXES})
 
-	list( APPEND CPACK_SOURCE_INSTALLED_DIRECTORIES
-	   "${PROJECT_SOURCE_DIR}" "."
-	   "${ECBUILD_MACROS_DIR}" "cmake/" )
+    list( APPEND CPACK_SOURCE_INSTALLED_DIRECTORIES
+          "${PROJECT_SOURCE_DIR}" "."
+          "${ECBUILD_MACROS_DIR}" "cmake/" )
 
-	# what to pack and not
+    # what to pack and not
 
     set(CPACK_SOURCE_IGNORE_FILES
         /build/
@@ -100,7 +162,13 @@ macro( ecbuild_install_project )
     include( CPack )
 
     ### EXPORTS ########################################################
- 
+
+    ecbuild_enabled_features( ${PROJECT_NAME_CAPS}_FEATURES )
+    foreach( _f ${${PNAME}_FEATURES} )
+        set( ${PNAME}_HAVE_${_f} 1 )
+    endforeach()
+
+    message( STATUS "${PROJECT_NAME_CAPS}_TPLS: ${${PROJECT_NAME_CAPS}_TPLS}" )
 
     foreach( _tpl ${${PNAME}_TPLS} )
         string( TOUPPER ${_tpl} _TPL )
@@ -136,31 +204,33 @@ macro( ecbuild_install_project )
 
     if( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
 
-        # exports the package for use from the build-tree -- inserts <package> into the CMake user package registry
-    
-        export( PACKAGE ${PROJECT_NAME} )
-         
+        # exports the package for use from the build-tree but only in DEVELOPER_MODE
+        # inserts <package> into the CMake user package registry
+
+        if( DEVELOPER_MODE )
+            export( PACKAGE ${PROJECT_NAME} )
+        endif()
+
         set( _template_config "${ECBUILD_MACROS_DIR}/project-config.cmake.in" )
         if( EXISTS ${LNAME}-config.cmake.in )
             set( _template_config "${LNAME}-config.cmake.in" )
         endif()
-    
+
         set( _template_config_version "${ECBUILD_MACROS_DIR}/project-config-version.cmake.in" )
         if( EXISTS ${LNAME}-config-version.cmake.in )
             set( _template_config_version "${LNAME}-config-version.cmake.in" )
         endif()
-    
+
         # project-config-version.cmake -- format ([0-9]+).([0-9]+).([0-9]+)
-    
-        set( PACKAGE_VERSION "${${PNAME}_VERSION}" ) 
-        
+
+        set( PACKAGE_VERSION "${${PNAME}_VERSION}" )
+
         configure_file( "${_template_config_version}" "${PROJECT_BINARY_DIR}/${LNAME}-config-version.cmake" @ONLY )
 
         install( FILES "${PROJECT_BINARY_DIR}/${LNAME}-config-version.cmake" DESTINATION "${INSTALL_CMAKE_DIR}" )
 
         # prepare imutable variables (don't depend on install path)
 
-        set( CONF_FEATURES "" )
         if( ${PNAME}_FEATURES )
           set( CONF_FEATURES ${${PNAME}_FEATURES} )
         endif()
@@ -169,7 +239,7 @@ macro( ecbuild_install_project )
         if( ${PNAME}_LIBRARIES )
             set( CONF_LIBRARIES ${${PNAME}_LIBRARIES} )
         endif()
-                    
+
         set( CONF_DEFINITIONS "" )
         if( ${PNAME}_DEFINITIONS )
            set( CONF_DEFINITIONS ${${PNAME}_DEFINITIONS} )
@@ -205,11 +275,20 @@ macro( ecbuild_install_project )
 
         set( CONF_IMPORT_FILE "${LNAME}-import.cmake" )
 
+        # If <project>-import.cmake.in exist in source tree, configure it to
+        # the build tree and install the configured version
         if( EXISTS "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}.in" )
-            configure_file( "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}.in"
-                            "${PROJECT_BINARY_DIR}/${CONF_IMPORT_FILE}" @ONLY )
-            install( FILES "${PROJECT_BINARY_DIR}/${CONF_IMPORT_FILE}"
-                     DESTINATION "${INSTALL_CMAKE_DIR}" )
+          configure_file( "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}.in"
+                          "${PROJECT_BINARY_DIR}/${CONF_IMPORT_FILE}" @ONLY )
+          install( FILES "${PROJECT_BINARY_DIR}/${CONF_IMPORT_FILE}"
+                   DESTINATION "${INSTALL_CMAKE_DIR}" )
+        # Otherwise, if <project>-import.cmake exist in source tree, copy it to
+        # the build tree and install it
+        elseif( EXISTS "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}" )
+          configure_file( "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}"
+                          "${PROJECT_BINARY_DIR}/${CONF_IMPORT_FILE}" COPYONLY )
+          install( FILES "${PROJECT_SOURCE_DIR}/${CONF_IMPORT_FILE}"
+                   DESTINATION "${INSTALL_CMAKE_DIR}" )
         endif()
 
         set( _lname_config "${PROJECT_BINARY_DIR}/${LNAME}-config.cmake")
@@ -235,7 +314,7 @@ macro( ecbuild_install_project )
         endif()
 
         # project-config.cmake @ install tree
-        
+
         file( RELATIVE_PATH REL_INCLUDE_DIR "${${PNAME}_FULL_INSTALL_CMAKE_DIR}" "${${PNAME}_FULL_INSTALL_INCLUDE_DIR}" )
         set( CONF_INCLUDE_DIRS "\${${PNAME}_CMAKE_DIR}/${REL_INCLUDE_DIR}" )
 
@@ -255,17 +334,17 @@ macro( ecbuild_install_project )
                 list( APPEND CONF_TPL_INCLUDE_DIRS ${${TPL}_INCLUDE_DIR} )
             endif()
         endforeach()
-        
+
         set( _is_build_dir_export OFF )
         configure_file( "${_template_config}" "${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${LNAME}-config.cmake" @ONLY )
         install( FILES "${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${LNAME}-config.cmake" DESTINATION "${INSTALL_CMAKE_DIR}" )
-     
+
         # install the export
-    
+
         if( ${PROJECT_NAME}_ALL_EXES OR ${PROJECT_NAME}_ALL_LIBS )
             install( EXPORT ${CMAKE_PROJECT_NAME}-targets DESTINATION "${INSTALL_CMAKE_DIR}" )
         endif()
-    
+
     else()
 
         set( ${PNAME}_FOUND             TRUE                          PARENT_SCOPE )
@@ -280,7 +359,10 @@ macro( ecbuild_install_project )
         set( ${PNAME}_TPL_LIBRARIES     ${${PNAME}_TPL_LIBRARIES}     PARENT_SCOPE )
         set( ${PNAME}_TPL_DEFINITIONS   ${${PNAME}_TPL_DEFINITIONS}   PARENT_SCOPE )
         set( ${PNAME}_TPL_INCLUDE_DIRS  ${${PNAME}_TPL_INCLUDE_DIRS}  PARENT_SCOPE )
-
-    endif()
+        set( ${PNAME}_FEATURES          ${${PNAME}_FEATURES}          PARENT_SCOPE )
+        foreach( _f ${${PNAME}_FEATURES} )
+            set( ${PNAME}_HAVE_${_f} ${${PNAME}_HAVE_${_f}} PARENT_SCOPE )
+        endforeach()
+     endif()
 
 endmacro( ecbuild_install_project )
diff --git a/cmake/ecbuild_list_extra_search_paths.cmake b/cmake/ecbuild_list_extra_search_paths.cmake
index 7373486..719b1e7 100644
--- a/cmake/ecbuild_list_extra_search_paths.cmake
+++ b/cmake/ecbuild_list_extra_search_paths.cmake
@@ -8,13 +8,15 @@
 
 ############################################################################################
 #
-# macro for adding search paths to CMAKE_PREFIX_PATH
-# for example the ECMWF /usr/local/apps paths
+# macro for adding search paths for a package to a given CMake variable
 #
 # usage: ecbuild_list_extra_search_paths( netcdf4 VARIABLE )
 
 function( ecbuild_list_extra_search_paths pkg var )
 
+  message( DEPRECATION " ecbuild_list_extra_search_paths should no longer be"
+           " used and is going to be removed in a future version of ecBuild." )
+
 	# debug_var( pkg )
 	# debug_var( var )
 
@@ -23,75 +25,45 @@ function( ecbuild_list_extra_search_paths pkg var )
 	# PKG_PATH (upper case)
 
 	if( DEFINED ${_PKG}_PATH AND EXISTS ${${_PKG}_PATH} )
-		message( "${_PKG}_PATH ${${_PKG}_PATH} exists " )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending ${_PKG}_PATH = ${${_PKG}_PATH} to ${var}")
 		list( APPEND ${var} ${${_PKG}_PATH} )
 	endif()
 
 	# ENV PKG_PATH (upper case)
 
 	if( DEFINED ENV{${_PKG}_PATH} AND EXISTS $ENV{${_PKG}_PATH}  )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending \$${_PKG}_PATH = $ENV{${_PKG}_PATH} to ${var}")
 		list( APPEND ${var} $ENV{${_PKG}_PATH} )
 	endif()
 
 	# pkg_PATH (lower case)
 
 	if( DEFINED ${pkg}_PATH AND EXISTS ${${pkg}_PATH} )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending ${pkg}_PATH = ${${pkg}_PATH} to ${var}")
 		list( APPEND ${var} ${${pkg}_PATH} )
 	endif()
 
 	# ENV pkg_PATH (lower case)
 
-	if( DEFINED ${pkg}_PATH AND EXISTS ${${pkg}_PATH} )
-		list( APPEND ${var} ${${pkg}_PATH} )
+  if( DEFINED ${pkg}_PATH AND EXISTS $ENV{${pkg}_PATH} )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending \$${pkg}_PATH = $ENV{${pkg}_PATH} to ${var}")
+    list( APPEND ${var} $ENV{${pkg}_PATH} )
 	endif()
 
 	# ENV PKG_DIR (upper case)
 
 	if( DEFINED ENV{${_PKG}_DIR} AND EXISTS $ENV{${_PKG}_DIR}  )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending \$${_PKG}_DIR = $ENV{${_PKG}_DIR} to ${var}")
 		list( APPEND ${var} $ENV{${_PKG}_DIR} )
 	endif()
 
 	# ENV pkg_DIR (lower case)
 
 	if( DEFINED ENV{${pkg}_DIR} AND EXISTS $ENV{${pkg}_DIR} )
+    ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): appending \$${pkg}_DIR = $ENV{${pkg}_DIR} to ${var}")
 		list( APPEND ${var} $ENV{${pkg}_DIR} )
 	endif()
 
-	# directories under /usr/local/apps/${pkg}
-
-	if( SEARCH_ECMWF_PATHS )
-
-		foreach( _apps /usr/local/apps/${pkg} /usr/local/lib/metaps/lib/${pkg} )
-
-			if( EXISTS ${_apps} )
-
-				 file( GLOB ps ${_apps}/[0-9]* )
-				 list( SORT ps )
-				 list( REVERSE ps ) # reversing will give us the newest versions first
-				 foreach( p ${ps} )
-					 if( IS_DIRECTORY ${p} )
-						  list( APPEND ${var}  ${p} )
-						  if( EXISTS ${p}/LP64 )
-							  list( APPEND ${var} ${p}/LP64 )
-						  endif()
-					 endif()
-				 endforeach()
-
-				 foreach( p ${_apps} ${_apps}/current ${_apps}/stable ${_apps}/new ${_apps}/next ${_apps}/prev )
-				   if( EXISTS ${p} )
-					   list( APPEND ${var} ${p} )
-				   endif()
-				   if( EXISTS ${p}/LP64 )
-					   list( APPEND ${var} ${p}/LP64 )
-				   endif()
-				 endforeach()
-
-			endif()
-
-		endforeach()
-
-	endif( SEARCH_ECMWF_PATHS )
-
 	# sanitize the list
 
 	if( ${var} )
@@ -100,6 +72,7 @@ function( ecbuild_list_extra_search_paths pkg var )
 
 	# define it out of the function
 
+  ecbuild_debug("ecbuild_list_extra_search_paths(${pkg}): setting ${var} to ${${var}}")
 	set( ${var} ${${var}} PARENT_SCOPE )
 
 # debug_var( ${var} )
diff --git a/cmake/ecbuild_list_macros.cmake b/cmake/ecbuild_list_macros.cmake
index 5c10dd2..fcfc815 100644
--- a/cmake/ecbuild_list_macros.cmake
+++ b/cmake/ecbuild_list_macros.cmake
@@ -55,3 +55,36 @@ endfunction(MAP_INSERT)
 function( MAP_GET _map _key _var )
 	set( ${_var} "${_${_map}_${_key}}" PARENT_SCOPE )
 endfunction(MAP_GET)
+
+##############################################################################
+# function to remove items from a list that match a list of patterns
+#
+# examples:
+#
+#   ecbuild_list_remove_pattern( mylist "foo;bar" VAR )
+#
+
+function(ecbuild_list_remove_pattern _list _patterns _var)
+
+#debug_var(  _list )
+#debug_var(  _patterns )
+#debug_var(  _var )
+
+    foreach( _elem ${_list} )
+        set( _keep TRUE)
+        foreach( _pat ${_patterns} )
+            if( ${_elem} MATCHES ${_pat} )
+                set( _keep FALSE)
+            endif()
+        endforeach()
+        if( _keep )
+            list( APPEND _result ${_elem} )
+        endif()
+
+    endforeach()
+
+#debug_var(  _result )
+
+    set( ${_var} "${_result}" PARENT_SCOPE )
+
+endfunction(ecbuild_list_remove_pattern)
diff --git a/cmake/ecbuild_log.cmake b/cmake/ecbuild_log.cmake
new file mode 100644
index 0000000..fbb2349
--- /dev/null
+++ b/cmake/ecbuild_log.cmake
@@ -0,0 +1,129 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+##############################################################################
+#.rst:
+#
+# Logging
+# =======
+#
+# ecBuild provides macros for logging based on a log level set by the user,
+# similar to the Python logging module:
+#
+# :ecbuild_debug:    logs a ``STATUS`` message if log level <= ``DEBUG``
+# :ecbuild_info:     logs a ``STATUS`` message if log level <= ``INFO``
+# :ecbuild_warn:     logs a ``WARNING`` message if log level <= ``WARN``
+# :ecbuild_error:    logs a ``SEND_ERROR`` message if log level <= ``ERROR``
+# :ecbuild_critical: logs a ``FATAL_ERROR`` message if log level <= ``CRITICAL``
+#
+# Input variables
+# ---------------
+#
+# CMake variables controlling logging behaviour:
+#
+# ECBUILD_LOG_LEVEL : string, one of DEBUG, INFO, WARN, ERROR, CRITICAL, OFF
+#   set the desired log level, OFF to disable logging altogether
+#
+# ECBUILD_NO_COLOUR : bool
+#   if set, does not colour log output (by default log output is coloured)
+#
+# Usage
+# -----
+#
+# The macros ``ecbuild_debug`` and ``ecbuild_info`` can be used to output
+# messages which are not printed by default. Many ecBuild macros use this
+# facility to log debugging hints. When debugging a CMake run, users can use
+# ``-DECBUILD_LOG_LEVEL=DEBUG`` to get detailed diagnostics.
+#
+##############################################################################
+
+# Define colour escape sequences (https://stackoverflow.com/a/19578320/396967)
+if(NOT (WIN32 OR ECBUILD_NO_COLOUR))
+  string(ASCII 27 Esc)
+  set(ColourReset "${Esc}[m")
+  set(ColourBold  "${Esc}[1m")
+  set(Red         "${Esc}[31m")
+  set(Green       "${Esc}[32m")
+  set(Yellow      "${Esc}[33m")
+  set(Blue        "${Esc}[34m")
+  set(Magenta     "${Esc}[35m")
+  set(Cyan        "${Esc}[36m")
+  set(White       "${Esc}[37m")
+  set(BoldRed     "${Esc}[1;31m")
+  set(BoldGreen   "${Esc}[1;32m")
+  set(BoldYellow  "${Esc}[1;33m")
+  set(BoldBlue    "${Esc}[1;34m")
+  set(BoldMagenta "${Esc}[1;35m")
+  set(BoldCyan    "${Esc}[1;36m")
+  set(BoldWhite   "${Esc}[1;37m")
+endif()
+
+set(ECBUILD_DEBUG    10)
+set(ECBUILD_INFO     20)
+set(ECBUILD_WARN     30)
+set(ECBUILD_ERROR    40)
+set(ECBUILD_CRITICAL 50)
+
+if( NOT DEFINED ECBUILD_LOG_LEVEL )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_WARN})
+elseif( NOT ECBUILD_LOG_LEVEL )
+  set(ECBUILD_LOG_LEVEL 60)
+elseif( ECBUILD_LOG_LEVEL STREQUAL "DEBUG" )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_DEBUG})
+elseif( ECBUILD_LOG_LEVEL STREQUAL "INFO" )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_INFO})
+elseif( ECBUILD_LOG_LEVEL STREQUAL "WARN" )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_WARN})
+elseif( ECBUILD_LOG_LEVEL STREQUAL "ERROR" )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_ERROR})
+elseif( ECBUILD_LOG_LEVEL STREQUAL "CRITICAL" )
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_CRITICAL})
+else()
+  message(WARNING "Unknown log level ${ECBUILD_LOG_LEVEL} (valid are DEBUG, INFO, WARN, ERROR, CRITICAL) - using WARN")
+  set(ECBUILD_LOG_LEVEL ${ECBUILD_WARN})
+endif()
+
+##############################################################################
+
+macro( ecbuild_debug MSG )
+  if( ECBUILD_LOG_LEVEL LESS 11)
+    message(STATUS "${Blue}DEBUG - ${MSG}${ColourReset}")
+  endif()
+endmacro( ecbuild_debug )
+
+##############################################################################
+
+macro( ecbuild_info MSG )
+  if( ECBUILD_LOG_LEVEL LESS 21)
+    message(STATUS "${Green}INFO - ${MSG}${ColourReset}")
+  endif()
+endmacro( ecbuild_info )
+
+##############################################################################
+
+macro( ecbuild_warn MSG )
+  if( ECBUILD_LOG_LEVEL LESS 31)
+    message(WARNING "${Yellow}WARN - ${MSG}${ColourReset}")
+  endif()
+endmacro( ecbuild_warn )
+
+##############################################################################
+
+macro( ecbuild_error MSG )
+  if( ECBUILD_LOG_LEVEL LESS 41)
+    message(SEND_ERROR "${BoldRed}ERROR - ${MSG}${ColourReset}")
+  endif()
+endmacro( ecbuild_error )
+
+##############################################################################
+
+macro( ecbuild_critical MSG )
+  if( ECBUILD_LOG_LEVEL LESS 51)
+    message(FATAL_ERROR "${BoldMagenta}CRITICAL - ${MSG}${ColourReset}")
+  endif()
+endmacro( ecbuild_critical )
diff --git a/cmake/ecbuild_pkgconfig.cmake b/cmake/ecbuild_pkgconfig.cmake
index 8549d46..4f82e40 100644
--- a/cmake/ecbuild_pkgconfig.cmake
+++ b/cmake/ecbuild_pkgconfig.cmake
@@ -6,52 +6,10 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-#############################################################################################
-#
-# MACRO ecbuild_pkgconfig
-#
-# This macro creates a pkg-config file for the current project
-#
-# It takes following optional arguments:
-#
-#  - FILENAME <filename>
-#       The file that will be generated. Default value is the lowercase
-#       name of the project with suffix ".pc" is used
-#
-#  - NAME <name>
-#       The name to be given to the package. Default value is the lowercase
-#       name of the project
-#
-#  - TEMPLATE <template>
-#       The template configuration file to use. This is useful to create more
-#       custom pkg-config files. Default is ${ECBUILD_CMAKE_DIR}/pkg-config.pc.in
-#
-#  - URL <url>
-#       The url of the package. Default is ${UPPERCASE_PROJECT_NAME}_URL
-#
-#  - DESCRIPTION <description>
-#       The description of the package. Default is ${UPPERCASE_PROJECT_NAME}_DESCRIPTION
-#
-#  - LIBRARIES <libraries>
-#       The package libraries. Default is ${UPPERCASE_PROJECT_NAME}_LIBRARIES
-#       This is e.g. of the form "eckit;eckit_geometry"
-#
-#  - IGNORE_INCLUDE_DIRS <include_dirs>
-#       Ignore specified include directories
-#
-#  - IGNORE_LIBRARIES <libraries>
-#       Ignore specified libraries
-#
-#  - LANGUAGES <languages>
-#       List of languages used. If none given, all CMake_<lang>_COMPILER_LOAED languages
-#       are added. Accepted languages: C CXX Fortran
-#
-#  - NO_PRIVATE_INCLUDE_DIRS
-#       Don't add include dirs of dependencies to Cflags. This is mainly useful
-#       for Fortran only packages, when only the modules need to be added to Cflags
-#
-#############################################################################################
+##############################################################################
 
+# Write transitive list of library dependencies of each library in ${libraries}
+# to CMake variable ${dependencies}
 function( ecbuild_library_dependencies dependencies libraries )
 
   set( _libraries ${${libraries}} )
@@ -105,8 +63,10 @@ function( ecbuild_library_dependencies dependencies libraries )
 
 endfunction(ecbuild_library_dependencies)
 
-#############################################################################################
+##############################################################################
 
+# Write list of include directories of each library in ${libraries}
+# to CMake variable ${dependencies}
 function( ecbuild_include_dependencies dependencies libraries )
 
   set( _libraries ${${libraries}} )
@@ -129,8 +89,10 @@ function( ecbuild_include_dependencies dependencies libraries )
 
 endfunction(ecbuild_include_dependencies)
 
-#############################################################################################
+##############################################################################
 
+# Transform list of libraries in ${libraries}, ignoring any in ${ignore_libs},
+# and write pkg-config compatible string to CMake variable ${pkgconfig_libs}
 function( ecbuild_pkgconfig_libs pkgconfig_libs libraries ignore_libs )
 
   set( _libraries ${${libraries}} )
@@ -203,10 +165,11 @@ function( ecbuild_pkgconfig_libs pkgconfig_libs libraries ignore_libs )
 
 endfunction(ecbuild_pkgconfig_libs)
 
+##############################################################################
 
-#############################################################################################
-
-
+# Transform list of include directories in ${INCLUDE_DIRS}, ignoring any in
+# ${ignore_includes} and ${${PNAME}_INCLUDE_DIRS}, and write pkg-config
+# compatible string to CMake variable ${INCLUDE}
 function( ecbuild_pkgconfig_include INCLUDE INCLUDE_DIRS ignore_includes )
 
   string( TOUPPER ${PROJECT_NAME} PNAME )
@@ -241,13 +204,100 @@ function( ecbuild_pkgconfig_include INCLUDE INCLUDE_DIRS ignore_includes )
 
 endfunction(ecbuild_pkgconfig_include)
 
-
-#############################################################################################
+##############################################################################
+#.rst:
+#
+# ecbuild_pkgconfig
+# =================
+#
+# Create a pkg-config file for the current project. ::
+#
+#   ecbuild_pkgconfig( [ NAME <name> ]
+#                      [ FILENAME <filename> ]
+#                      [ TEMPLATE <template> ]
+#                      [ URL <url> ]
+#                      [ DESCRIPTION <description> ]
+#                      [ LIBRARIES <lib1> [ <lib2> ... ] ]
+#                      [ IGNORE_INCLUDE_DIRS <dir1> [ <dir2> ... ] ]
+#                      [ IGNORE_LIBRARIES <lib1> [ <lib2> ... ] ]
+#                      [ LANGUAGES <language1> [ <language2> ... ] ]
+#                      [ VARIABLES <variable1> [ <variable2> ... ] ]
+#                      [ NO_PRIVATE_INCLUDE_DIRS ] )
+#
+# Options
+# -------
+#
+# NAME : optional, defaults to lower case name of the project
+#   name to be given to the package
+#
+# FILENAME : optional, defaults to ``<NAME>.pc``
+#   file to be generated, including .pc extension
+#
+# TEMPLATE : optional, defaults to ``${ECBUILD_CMAKE_DIR}/pkg-config.pc.in``
+#   template configuration file to use
+#
+#   This is useful to create customised pkg-config files.
+#
+# URL : optional, defaults to ``${UPPERCASE_PROJECT_NAME}_URL``
+#   url of the package
+#
+# DESCRIPTION : optional, defaults to ``${UPPERCASE_PROJECT_NAME}_DESCRIPTION``
+#   description of the package
+#
+# LIBRARIES : optional, defaults to ``${UPPERCASE_PROJECT_NAME}_LIBRARIES``
+#   list of package libraries
+#
+# IGNORE_INCLUDE_DIRS : optional
+#   list of include directories to ignore
+#
+# IGNORE_LIBRARIES : optional
+#   list of libraries to ignore i.e. those are removed from ``LIBRARIES``
+#
+# VARIABLES : optional
+#   list of additional CMake variables to export to the pkg-config file
+#
+# LANGUAGES : optional, defaults to all loaded languages
+#   list of languages to use. Accepted languages: C CXX Fortran
+#
+# NO_PRIVATE_INCLUDE_DIRS
+#   do not add include directories of dependencies to Cflags
+#
+#   This is mainly useful for Fortran only packages, when only modules need
+#   to be added to Cflags.
+#
+# Input variables
+# ---------------
+#
+# The following CMake variables are used as default values for some of the
+# options listed above, where ``PNAME`` is the project name in upper case: ::
+#
+# :<PNAME>_LIBRARIES:    list of libraries to export
+# :<PNAME>_DESCRIPTION:  package description
+# :<PNAME>_URL:          package URL
+# :<PNAME>_VERSION:      package version
+# :<PNAME>_GIT_SHA1:     Git revision
+#
+# Usage
+# -----
+#
+# It is good practice to provide a separate pkg-config file for each library a
+# package exports. This can be achieved as follows: ::
+#
+#   foreach( _lib ${${PNAME}_LIBRARIES} )
+#     if( TARGET ${_lib} )
+#       ecbuild_pkgconfig( NAME ${_lib}
+#                          DESCRIPTION "..."
+#                          URL "..."
+#                          LIBRARIES ${_lib} )
+#     endif()
+#   endforeach()
+#
+##############################################################################
 
 function( ecbuild_pkgconfig )
 
   set( options REQUIRES NO_PRIVATE_INCLUDE_DIRS )
-  set( single_value_args FILEPATH NAME TEMPLATE URL DESCRIPTION )
+  set( single_value_args FILENAME NAME TEMPLATE URL DESCRIPTION )
   set( multi_value_args LIBRARIES IGNORE_INCLUDE_DIRS IGNORE_LIBRARIES VARIABLES LANGUAGES )
 
   cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
@@ -331,8 +381,8 @@ function( ecbuild_pkgconfig )
     set( PKGCONFIG_NAME ${_PAR_NAME} )
   endif()
 
-  if( NOT _PAR_FILEPATH )
-    set( _PAR_FILEPATH "${PKGCONFIG_NAME}.pc" )
+  if( NOT _PAR_FILENAME )
+    set( _PAR_FILENAME "${PKGCONFIG_NAME}.pc" )
   endif()
 
   set( PKGCONFIG_DESCRIPTION ${${PNAME}_DESCRIPTION} )
@@ -355,11 +405,11 @@ function( ecbuild_pkgconfig )
     endforeach()
   endif()
 
-  configure_file( ${_PAR_TEMPLATE} "${CMAKE_BINARY_DIR}/${_PAR_FILEPATH}" @ONLY )
-  message( STATUS "pkg-config file created: ${_PAR_FILEPATH}" )
+  configure_file( ${_PAR_TEMPLATE} "${CMAKE_BINARY_DIR}/${_PAR_FILENAME}" @ONLY )
+  message( STATUS "pkg-config file created: ${_PAR_FILENAME}" )
 
-  install( FILES ${CMAKE_BINARY_DIR}/${_PAR_FILEPATH}
-           DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig/
+  install( FILES ${CMAKE_BINARY_DIR}/${_PAR_FILENAME}
+           DESTINATION ${CMAKE_INSTALL_PREFIX}/${INSTALL_LIB_DIR}/pkgconfig/
            COMPONENT utilities )
 
 endfunction(ecbuild_pkgconfig)
diff --git a/cmake/ecbuild_policies.cmake b/cmake/ecbuild_policies.cmake
new file mode 100644
index 0000000..06f856b
--- /dev/null
+++ b/cmake/ecbuild_policies.cmake
@@ -0,0 +1,63 @@
+# (C) Copyright 1996-2015 ECMWF.
+#
+# This software is licensed under the terms of the Apache Licence Version 2.0
+# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
+# In applying this licence, ECMWF does not waive the privileges and immunities
+# granted to it by virtue of its status as an intergovernmental organisation
+# nor does it submit to any jurisdiction.
+
+###############################################################################
+# define cmake policies
+#
+# NOTE: This file needs to be included with NO_POLICY_SCOPE or it will have no
+#       effect!
+# NOTE: Policies 1 through 17 will be set to NEW by requiring CMake 2.8.4 i.e.
+#       calling cmake_minimum_required( VERSION 2.8.4 FATAL_ERROR )
+
+# allow for empty spaces around library names 
+if( POLICY CMP0004 )
+    cmake_policy( SET CMP0004 OLD )
+endif()
+
+# Allow use of the LOCATION target property.
+if( POLICY CMP0026 )
+    cmake_policy( SET CMP0026 OLD )
+endif()
+
+# for macosx use @rpath in a target’s install name
+if( POLICY CMP0042 )
+    cmake_policy( SET CMP0042 NEW )
+    set( CMAKE_MACOSX_RPATH ON )
+endif()
+
+# Error on non-existent target in get_target_property
+if( POLICY CMP0045 )
+    cmake_policy( SET CMP0045 NEW )
+endif()
+
+# Error on non-existent dependency in add_dependencies
+if( POLICY CMP0046 )
+    cmake_policy( SET CMP0046 NEW )
+endif()
+
+# Do not manage VERSION variables in project command
+if( POLICY CMP0048 )
+  cmake_policy( SET CMP0048 OLD )
+endif()
+
+# Disallow add_custom_command SOURCE signatures
+if( POLICY CMP0050 )
+    cmake_policy( SET CMP0050 NEW )
+endif()
+
+# Reject source and build dirs in installed INTERFACE_INCLUDE_DIRECTORIES
+if( POLICY CMP0052 )
+    cmake_policy( SET CMP0052 NEW )
+endif()
+
+# inside if() don't dereference variables if they are quoted
+# e.g. "VAR" is not dereferenced
+#      "${VAR}" is dereference only once
+if( POLICY CMP0054 )
+    cmake_policy( SET CMP0054 NEW )
+endif()
diff --git a/cmake/ecbuild_print_summary.cmake b/cmake/ecbuild_print_summary.cmake
index 193bf1f..b3cddf0 100644
--- a/cmake/ecbuild_print_summary.cmake
+++ b/cmake/ecbuild_print_summary.cmake
@@ -6,110 +6,101 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
+##############################################################################
+#.rst:
+#
+# ecbuild_print_summary
+# =====================
+#
+# Print a summary of the project, build environment and enabled features. ::
+#
+#   ecbuild_print_summary()
+#
+# If ``project_summary.cmake`` exist in the source root directory, a project
+# summary is printed by including this file.
+#
+# For a top level project, a summary of the build environment and a feature
+# summary are also printed.
+#
+##############################################################################
+
 macro( ecbuild_print_summary )
 
-    if( EXISTS ${PROJECT_SOURCE_DIR}/project_summary.cmake )
+  if( EXISTS ${PROJECT_SOURCE_DIR}/project_summary.cmake )
+
+    message( STATUS "---------------------------------------------------------" )
+    message( STATUS "Project ${PROJECT_NAME} summary" )
+    message( STATUS "---------------------------------------------------------" )
+
+    include( ${PROJECT_SOURCE_DIR}/project_summary.cmake )
+
+  endif()
+
+  if( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
+
+    ecbuild_define_links_target()
 
-		message( STATUS "---------------------------------------------------------" )
-		message( STATUS "Project ${PROJECT_NAME} summary" )
-		message( STATUS "---------------------------------------------------------" )
+    get_property( langs GLOBAL PROPERTY ENABLED_LANGUAGES )
 
-		include( ${PROJECT_SOURCE_DIR}/project_summary.cmake )
+    message( STATUS "---------------------------------------------------------" )
+    if( NOT ${DEVELOPER_MODE} )
+      message( STATUS "Build summary" )
+    else()
+      message( STATUS "Build summary -- ( DEVELOPER_MODE )" )
+    endif()
+    message( STATUS "---------------------------------------------------------" )
 
+    message( STATUS "system : [${BUILD_SITE}] [${CMAKE_SYSTEM}] [${EC_OS_NAME}.${EC_OS_BITS}]" )
+    message( STATUS "processor        : [${CMAKE_SYSTEM_PROCESSOR}]" )
+    if( EC_BIG_ENDIAN )
+      message( STATUS "endiness         : Big Endian -- IEEE [${IEEE_BE}]" )
+    endif()
+    if( EC_LITTLE_ENDIAN )
+      message( STATUS "endiness         : Little Endian -- IEEE [${IEEE_LE}]" )
+    endif()
+    message( STATUS "build type       : [${CMAKE_BUILD_TYPE}]" )
+    message( STATUS "timestamp        : [${EC_BUILD_TIMESTAMP}]" )
+    message( STATUS "install prefix   : [${CMAKE_INSTALL_PREFIX}]" )
+    if( EC_LINK_DIR )
+      message( STATUS "links prefix     : [${EC_LINK_DIR}]" )
     endif()
+    message( STATUS "---------------------------------------------------------" )
 
-    if( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
-	
-        ecbuild_define_links_target()
-
-        get_property( langs GLOBAL PROPERTY ENABLED_LANGUAGES )
-
-		message( STATUS "---------------------------------------------------------" )
-		if( NOT ${DEVELOPER_MODE} )
-			message( STATUS "Build summary" )
-		else()
-			message( STATUS "Build summary -- ( DEVELOPER_MODE )" )
-		endif()
-		message( STATUS "---------------------------------------------------------" )
-
-		message( STATUS "system : [${BUILD_SITE}] [${CMAKE_SYSTEM}] [${EC_OS_NAME}.${EC_OS_BITS}]" )
-		message( STATUS "processor        : [${CMAKE_SYSTEM_PROCESSOR}]" )
-		if( EC_BIG_ENDIAN )
-			message( STATUS "endiness         : Big Endian -- IEEE [${IEEE_BE}]" )
-		endif()
-		if( EC_LITTLE_ENDIAN )
-			message( STATUS "endiness         : Little Endian -- IEEE [${IEEE_LE}]" )
-		endif()
-		message( STATUS "build type       : [${CMAKE_BUILD_TYPE}]" )
-		message( STATUS "timestamp        : [${EC_BUILD_TIMESTAMP}]" )
-		message( STATUS "install prefix   : [${CMAKE_INSTALL_PREFIX}]" )
-		if( EC_LINK_DIR )
-			message( STATUS "links prefix     : [${EC_LINK_DIR}]" )
-		endif()
-        message( STATUS "---------------------------------------------------------" )
-
-        foreach( lang ${langs} )
-		  message( STATUS "${lang} -- ${CMAKE_${lang}_COMPILER_ID} ${CMAKE_${lang}_COMPILER_VERSION}"  )
-		  message( STATUS "    compiler   : ${CMAKE_${lang}_COMPILER} ${CMAKE_${lang}_FLAGS} ${CMAKE_${lang}_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}" )
-		  message( STATUS "    link flags : ${CMAKE_${lang}_LINK_FLAGS}" )
-		endforeach()
-
-	message( STATUS "linker : ${CMAKE_LINKER}")
-	message( STATUS "ar     : ${CMAKE_AR}")
-	message( STATUS "ranlib : ${CMAKE_RANLIB}")
-	message( STATUS "link flags" )
-	message( STATUS "    executable [${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_EXEC_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
-	message( STATUS "    shared lib [${CMAKE_SHARED_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
-	message( STATUS "    static lib [${CMAKE_MODULE_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
-	message( STATUS "install rpath  : ${CMAKE_INSTALL_RPATH}" )
-
-	get_directory_property( defs COMPILE_DEFINITIONS )
-
-	message( STATUS "common definitions: ${defs}" )
-
-	message( STATUS "---------------------------------------------------------" )
-
-	### FEATURE SUMMARY
-
-	  # debug_var( CMAKE_VERSION )
-	  if( ${CMAKE_VERSION} VERSION_LESS "2.8.6" )
-		feature_summary( WHAT ALL )
-	  else()
-		feature_summary( WHAT ALL INCLUDE_QUIET_PACKAGES )
-	  endif()
-
-	### WARNINGS
+    foreach( lang ${langs} )
+      message( STATUS "${lang} -- ${CMAKE_${lang}_COMPILER_ID} ${CMAKE_${lang}_COMPILER_VERSION}"  )
+      message( STATUS "    compiler   : ${CMAKE_${lang}_COMPILER} ${CMAKE_${lang}_FLAGS} ${CMAKE_${lang}_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}" )
+      message( STATUS "    link flags : ${CMAKE_${lang}_LINK_FLAGS}" )
+    endforeach()
 
-    # issue warnings / errors in case there are unused project files
-    ecbuild_warn_unused_files()
+    message( STATUS "linker : ${CMAKE_LINKER}")
+    message( STATUS "ar     : ${CMAKE_AR}")
+    message( STATUS "ranlib : ${CMAKE_RANLIB}")
+    message( STATUS "link flags" )
+    message( STATUS "    executable [${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
+    message( STATUS "    shared lib [${CMAKE_SHARED_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
+    message( STATUS "    static lib [${CMAKE_MODULE_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS_${CMAKE_BUILD_TYPE_CAPS}}]" )
+    message( STATUS "install rpath  : ${CMAKE_INSTALL_RPATH}" )
+
+    get_directory_property( defs COMPILE_DEFINITIONS )
 
-    # issue a warning that 'make install' mighty be broken for old cmakes
-    if( ${CMAKE_VERSION} VERSION_LESS "2.8.3" )
-
-        message( STATUS " +++ WARNING +++ WARNING +++ WARNING +++" )
-        message( STATUS " +++ " )
-		message( STATUS " +++ This CMake version [${CMAKE_VERSION}] is rather OLD !!" )
-        message( STATUS " +++ " )
-        message( STATUS " +++ We work hard to keep CMake backward compatibility (support >= 2.6.4)" )
-        message( STATUS " +++ but there are some limits inherent to older versions." )
-        message( STATUS " +++ " )
-        message( STATUS " +++ You will be able to build the software... " )
-        message( STATUS " +++ " )
-        message( STATUS " +++ But: " )
-        message( STATUS " +++     * the 'make install' target most likely will NOT WORK" )
-        message( STATUS " +++     * if you want to install these binaries you might need to copy them by yourself" )
-        message( STATUS " +++     * the binaries are in '${CMAKE_BINARY_DIR}' /lib and /bin" )
-        message( STATUS " +++     * copying headers will take substantially more work, and you might end up copying files that won't be needed" )
-        message( STATUS " +++ " )
-        message( STATUS " +++ Therefore, we recommend that you:  " )
-        message( STATUS " +++     * upgrade to a newer CMake with version at least >= 2.8.3" )
-        message( STATUS " +++     * remove this build directory '${CMAKE_BINARY_DIR}'" )
-        message( STATUS " +++     * rerun a newer cmake on an new empty build directory" )
-        message( STATUS " +++ " )
-        message( STATUS " +++ WARNING +++ WARNING +++ WARNING +++" )
+    message( STATUS "common definitions: ${defs}" )
 
+    message( STATUS "---------------------------------------------------------" )
+
+    ### FEATURE SUMMARY
+
+    # debug_var( CMAKE_VERSION )
+    if( ${CMAKE_VERSION} VERSION_LESS "2.8.6" )
+      feature_summary( WHAT ALL )
+    else()
+      feature_summary( WHAT ALL INCLUDE_QUIET_PACKAGES )
     endif()
 
-    endif( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
+    ### WARNINGS
+
+    # issue warnings / errors in case there are unused project files
+    ecbuild_warn_unused_files()
+
+  endif( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
 
 endmacro( ecbuild_print_summary )
diff --git a/cmake/ecbuild_project_files.cmake b/cmake/ecbuild_project_files.cmake
index f304772..162a625 100644
--- a/cmake/ecbuild_project_files.cmake
+++ b/cmake/ecbuild_project_files.cmake
@@ -16,30 +16,29 @@ macro( ecbuild_find_files_recursive aFileList )
 
 list( APPEND ecbuild_project_extensions c cc cpp cxx ) # for the moment skip ( h hh )
 
-# first find all the files in the directory
 foreach( aExt ${ecbuild_project_extensions} )
-
-    file( GLOB_RECURSE listFilesWithExt *.${aExt})
-
-    list( LENGTH  listFilesWithExt sizeFilesWithExt )
-    if( sizeFilesWithExt GREATER 0 )
-      set( ${aFileList} ${${aFileList}} ${listFilesWithExt} )
-    endif()
-
+  set( globPatterns ${globPatterns} *.${aExt} )
 endforeach()
 
+# This globs for only one pattern at a time
+# Shell extglob patterns are unfortunately not supported.
+file( GLOB_RECURSE ${aFileList} ${globPatterns} )
+
 endmacro()
 
 ##############################################################################
 # finds the unused files on all the project
 function( ecbuild_find_project_files )
 
-  ecbuild_find_files_recursive( cwdFiles )
+  # Only do this if we actually care to warn about unused files
+  if( CHECK_UNUSED_FILES )
+    ecbuild_find_files_recursive( cwdFiles )
 
-  # this list will be kept
-  set( EC_PROJECT_FILES ${EC_PROJECT_FILES} ${cwdFiles} CACHE INTERNAL "" )
-  # this list will be progressevely emptied
-  set( EC_UNUSED_FILES  ${EC_UNUSED_FILES}  ${cwdFiles} CACHE INTERNAL "" )
+    # this list will be kept
+    set( EC_PROJECT_FILES ${EC_PROJECT_FILES} ${cwdFiles} CACHE INTERNAL "" )
+    # this list will be progressevely emptied
+    set( EC_UNUSED_FILES  ${EC_UNUSED_FILES}  ${cwdFiles} CACHE INTERNAL "" )
+  endif()
 
 endfunction()
 
@@ -47,27 +46,30 @@ endfunction()
 # removed used files from unused list
 macro( ecbuild_declare_project_files )
 
-  foreach( _afile ${ARGV} )
+  # Only do this if we actually care to warn about unused files
+  if( CHECK_UNUSED_FILES )
+    foreach( _afile ${ARGV} )
 
-    # debug_var( _afile )
+      # debug_var( _afile )
 
-    get_property( _src_gen SOURCE ${_afile} PROPERTY GENERATED )
+      get_property( _src_gen SOURCE ${_afile} PROPERTY GENERATED )
 
-    if( NOT _src_gen )
+      if( NOT _src_gen )
 
-    	get_filename_component( _abspath ${_afile} ABSOLUTE )
+        get_filename_component( _abspath ${_afile} ABSOLUTE )
 
-    	# check for existance of all declared files
-	    if( EXISTS ${_abspath} )
-    	    list( REMOVE_ITEM EC_UNUSED_FILES ${_abspath} )
-	    else()
-			message( FATAL_ERROR "In directory ${CMAKE_CURRENT_SOURCE_DIR} file ${_afile} was declared in CMakeLists.txt but not found" )
-    	endif()
-    endif()
+        # check for existance of all declared files
+        if( EXISTS ${_abspath} )
+            list( REMOVE_ITEM EC_UNUSED_FILES ${_abspath} )
+        else()
+        message( FATAL_ERROR "In directory ${CMAKE_CURRENT_SOURCE_DIR} file ${_afile} was declared in CMakeLists.txt but not found" )
+        endif()
+      endif()
 
-  endforeach()
+    endforeach()
 
-  # rewrite the unused file list in cache
-  set( EC_UNUSED_FILES ${EC_UNUSED_FILES} CACHE INTERNAL "unused files" )
+    # rewrite the unused file list in cache
+    set( EC_UNUSED_FILES ${EC_UNUSED_FILES} CACHE INTERNAL "unused files" )
+  endif()
 
 endmacro()
diff --git a/cmake/ecbuild_requires_macro_version.cmake b/cmake/ecbuild_requires_macro_version.cmake
index dbdcc05..6c73fe7 100644
--- a/cmake/ecbuild_requires_macro_version.cmake
+++ b/cmake/ecbuild_requires_macro_version.cmake
@@ -6,6 +6,18 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
+##############################################################################
+#.rst:
+#
+# ecbuild_requires_macro_version
+# ==============================
+#
+# Check that the ecBuild version satisfied a given minimum version or fail. ::
+#
+#   ecbuild_requires_macro_version( <minimum-version> )
+#
+##############################################################################
+
 macro( ecbuild_requires_macro_version req_vrs )
 
 	if( ECBUILD_MACRO_VERSION VERSION_LESS ${req_vrs} )
diff --git a/cmake/ecbuild_separate_sources.cmake b/cmake/ecbuild_separate_sources.cmake
index 71d56b3..94aa182 100644
--- a/cmake/ecbuild_separate_sources.cmake
+++ b/cmake/ecbuild_separate_sources.cmake
@@ -7,7 +7,36 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# macro for separating sources sccording to language
+#.rst:
+#
+# ecbuild_separate_sources
+# ========================
+#
+# Separate a given list of sources according to language. ::
+#
+#   ecbuild_separate_sources( TARGET <name>
+#                             SOURCES <source1> [ <source2> ... ] )
+#
+# Options
+# -------
+#
+# TARGET : required
+#   base name for the CMake output variables to set
+#
+# SOURCES : required
+#   list of source files to separate
+#
+# Output variables
+# ----------------
+#
+# If any file of the following group of extensions is present in the list of
+# sources, the corresponding CMake variable is set:
+#
+# :<target>_h_srcs:   list of sources with extension .h, .hxx, .hh, .hpp, .H
+# :<target>_c_srcs:   list of sources with extension .c
+# :<target>_cxx_srcs: list of sources with extension .cc, .cxx, .cpp, .C
+# :<target>_f_srcs:   list of sources with extension .f, .F, .for, f77, .f90, .f95
+#
 ##############################################################################
 
 macro( ecbuild_separate_sources )
@@ -60,4 +89,3 @@ macro( ecbuild_separate_sources )
 #    debug_var( ${_PAR_TARGET}_f_srcs )
 
 endmacro( ecbuild_separate_sources  )
-
diff --git a/cmake/ecbuild_setup_test_framework.cmake b/cmake/ecbuild_setup_test_framework.cmake
index 86f026e..538a433 100644
--- a/cmake/ecbuild_setup_test_framework.cmake
+++ b/cmake/ecbuild_setup_test_framework.cmake
@@ -1,42 +1,41 @@
 ecbuild_add_option( FEATURE TESTS
-					DEFAULT ON
-					DESCRIPTION "Enable the unit tests" )
+                    DEFAULT ON
+                    DESCRIPTION "Enable the unit tests" )
 
 if( ENABLE_TESTS )
 
-	# Try to find compiled boost
+  # Try to find compiled boost
 
-	if( BOOST_ROOT OR BOOSTROOT OR DEFINED ENV{BOOST_ROOT} OR DEFINED ENV{BOOSTROOT} )
-		set( CMAKE_PREFIX_PATH ${BOOST_ROOT} ${BOOSTROOT} $ENV{BOOST_ROOT} $ENV{BOOSTROOT} ${CMAKE_PREFIX_PATH} )
-	endif()
+  # BOOST_ROOT or BOOSTROOT should take precedence on the search for location
+  if( BOOST_ROOT OR BOOSTROOT OR DEFINED ENV{BOOST_ROOT} OR DEFINED ENV{BOOSTROOT} )
+    set( CMAKE_PREFIX_PATH ${BOOST_ROOT} ${BOOSTROOT} $ENV{BOOST_ROOT} $ENV{BOOSTROOT} ${CMAKE_PREFIX_PATH} )
+  endif()
 
-	ecbuild_add_extra_search_paths( boost ) # also respects BOOST_ROOT
+  set( Boost_USE_MULTITHREADED  ON )
+  #   set( Boost_DEBUG              ON )
 
-	set( Boost_USE_MULTITHREADED  ON )
-#   set( Boost_DEBUG              ON )
+  find_package( Boost 1.47.0 COMPONENTS unit_test_framework )
 
-	find_package( Boost 1.47.0 COMPONENTS unit_test_framework )
+  set( ECBUILD_BOOST_HEADER_DIRS "${CMAKE_CURRENT_LIST_DIR}/include" )
 
-	set( ECBUILD_BOOST_HEADER_DIRS "${CMAKE_CURRENT_LIST_DIR}/include" )
+  if( Boost_FOUND AND Boost_UNIT_TEST_FRAMEWORK_LIBRARY )
 
-	if( Boost_FOUND AND Boost_UNIT_TEST_FRAMEWORK_LIBRARY )
+    set( HAVE_BOOST_UNIT_TEST 1 )
+    set( BOOST_UNIT_TEST_FRAMEWORK_LINKED 1 )
 
-		set( HAVE_BOOST_UNIT_TEST 1 )
-		set( BOOST_UNIT_TEST_FRAMEWORK_LINKED 1 )
+    message( STATUS "Using Boost for unit tests:\n    INC [${Boost_INCLUDE_DIRS}]\n    LIB [${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}]" )
 
-		# message( STATUS "Boost unit test framework -- FOUND [${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}]" )
+  else()
 
-	else()
+    message( STATUS "Boost unit test framework -- NOT FOUND" )
 
-		message( STATUS "Boost unit test framework -- NOT FOUND" )
+    set( HAVE_BOOST_UNIT_TEST 0 )
 
-		set( HAVE_BOOST_UNIT_TEST 0 )
+    # set( BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY 1 )
+    # comment out this when ecbuild packs boost unit test inside...
+    # list( APPEND ECBUILD_BOOST_HEADER_DIRS "${CMAKE_CURRENT_LIST_DIR}/contrib/boost-1.55/include" )
+    # set( HAVE_BOOST_UNIT_TEST 1 )
 
-		# set( BOOST_UNIT_TEST_FRAMEWORK_HEADER_ONLY 1 )
-		# comment out this when ecbuild packs boost unit test inside...
-		# list( APPEND ECBUILD_BOOST_HEADER_DIRS "${CMAKE_CURRENT_LIST_DIR}/contrib/boost-1.55/include" )
-		# set( HAVE_BOOST_UNIT_TEST 1 )
-
-	endif()
+  endif()
 
 endif()
diff --git a/cmake/ecbuild_system.cmake b/cmake/ecbuild_system.cmake
index 939d92e..c9fe7f8 100644
--- a/cmake/ecbuild_system.cmake
+++ b/cmake/ecbuild_system.cmake
@@ -10,19 +10,19 @@
 # disallow in-source build
 
 if( EXISTS ${CMAKE_SOURCE_DIR}/CMakeCache.txt ) # check for failed attempts to build within the source tree
-   message( FATAL_ERROR "Project ${PROJECT_NAME} contains a CMakeCache.txt inside source tree [${CMAKE_SOURCE_DIR}/CMakeCache.txt].\n Please remove it and
-   make sure that source tree is prestine and clean of unintended files, before retrying." )
+    message( FATAL_ERROR "Project ${PROJECT_NAME} contains a CMakeCache.txt inside source tree [${CMAKE_SOURCE_DIR}/CMakeCache.txt].\n Please remove it and
+    make sure that source tree is prestine and clean of unintended files, before retrying." )
 endif()
 
 get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
 get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH)
 
 if(${srcdir} STREQUAL ${bindir})
-  message("######################################################")
-  message("You are attempting to build in your source directory (${srcdir}).")
-  message("You must run cmake from a different build directory.")
-  message("######################################################")
-  message( FATAL_ERROR "${PROJECT_NAME} requires an out of source build.\n Please create a separate build directory and run 'cmake path/to/project [options]' from there.")
+    message("######################################################")
+    message("You are attempting to build in your source directory (${srcdir}).")
+    message("You must run cmake from a different build directory.")
+    message("######################################################")
+    message( FATAL_ERROR "${PROJECT_NAME} requires an out of source build.\n Please create a separate build directory and run 'cmake path/to/project [options]' from there.")
 endif()
 
 ########################################################################################################
@@ -30,7 +30,7 @@ endif()
 
 set( ECBUILD_CMAKE_MINIMUM "2.8.4" )
 if( ${CMAKE_VERSION} VERSION_LESS ${ECBUILD_CMAKE_MINIMUM} )
-  message(FATAL_ERROR "${PROJECT_NAME} requires at least CMake ${ECBUILD_CMAKE_MINIMUM} -- you are using ${CMAKE_COMMAND} [${CMAKE_VERSION}]\n Please, get a newer version of CMake @ www.cmake.org" )
+    message(FATAL_ERROR "${PROJECT_NAME} requires at least CMake ${ECBUILD_CMAKE_MINIMUM} -- you are using ${CMAKE_COMMAND} [${CMAKE_VERSION}]\n Please, get a newer version of CMake @ www.cmake.org" )
 endif()
 
 set( ECBUILD_MACROS_DIR "${CMAKE_CURRENT_LIST_DIR}" CACHE INTERNAL "where ecbuild system is" )
@@ -39,243 +39,206 @@ include( "${ECBUILD_MACROS_DIR}/VERSION.cmake" )
 
 set( ecbuild_VERSION_STR "${ECBUILD_VERSION_STR}" )
 
-########################################################################################################
-# define cmake policies
-
-# Included scripts don't automatic cmake_policy PUSH and POP
-
-if( POLICY CMP0011 )
-	cmake_policy( SET CMP0011 OLD )
-endif()
-
-# Allow use of the LOCATION target property.
-
-if( POLICY CMP0026 )
-	cmake_policy( SET CMP0026 OLD )
-endif()
-
-# for macosx use @rpath in a target’s install name
-
-if( POLICY CMP0042 )
-	cmake_policy( SET CMP0042 NEW )
-	set( CMAKE_MACOSX_RPATH ON )
-endif()
-
-# Error on non-existent target in get_target_property
+# Set policies
+include( ecbuild_policies NO_POLICY_SCOPE )
 
-if( POLICY CMP0045 )
-	cmake_policy( SET CMP0045 NEW )
-endif()
+# set capitalised project name
 
-# Error on non-existent target in get_target_property
-
-if( POLICY CMP0046 )
-	cmake_policy( SET CMP0046 NEW )
-endif()
-
-# Error on non-existent dependency in add_dependencies
-
-if( POLICY CMP0046 )
-	cmake_policy( SET CMP0050 NEW )
-endif()
-
-# Reject source and build dirs in installed INTERFACE_INCLUDE_DIRECTORIES
-
-if( POLICY CMP0052 )
-	cmake_policy( SET CMP0052 NEW )
-endif()
-
-# inside if() don't dereference variables if they are quoted 
-# e.g. "VAR" is not dereferenced 
-#      "${VAR}" is dereference only once
-
-if( POLICY CMP0054 )
-	cmake_policy( SET CMP0054 NEW )
-endif()
+string( TOUPPER ${PROJECT_NAME} PROJECT_NAME_CAPS )
+string( TOLOWER ${PROJECT_NAME} PROJECT_NAME_LOWCASE )
 
 ########################################################################################################
 # include our cmake macros, but only do so if this is the top project
 if( PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
 
-	# hostname of where we build
+    # hostname of where we build
 
-	site_name( BUILD_SITE )
-	mark_as_advanced( BUILD_SITE )
-	mark_as_advanced( BUILD_TESTING )
+    site_name( BUILD_SITE )
+    mark_as_advanced( BUILD_SITE )
+    mark_as_advanced( BUILD_TESTING )
 
-	set( ECBUILD_PROJECTS  "" CACHE INTERNAL "list of ecbuild (sub)projects that use ecbuild" )
+    set( ECBUILD_PROJECTS  "" CACHE INTERNAL "list of ecbuild (sub)projects that use ecbuild" )
 
-	message( STATUS "ecbuild   ${ecbuild_VERSION_STR}\t${ECBUILD_MACROS_DIR}" )
-	message( STATUS "cmake     ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION}\t${CMAKE_COMMAND}" )
+    message( STATUS "ecbuild   ${ecbuild_VERSION_STR}\t${ECBUILD_MACROS_DIR}" )
+    message( STATUS "cmake     ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION}\t${CMAKE_COMMAND}" )
 
-	if( CMAKE_TOOLCHAIN_FILE )
-		message( STATUS "toolchain ${CMAKE_TOOLCHAIN_FILE}" )
-	endif()
+    if( CMAKE_TOOLCHAIN_FILE )
+    message( STATUS "toolchain ${CMAKE_TOOLCHAIN_FILE}" )
+    endif()
 
-	if( ECBUILD_CACHE )
-		include( ${ECBUILD_CACHE} )
+    if( ECBUILD_CACHE )
+    include( ${ECBUILD_CACHE} )
       message( STATUS "cache     ${ECBUILD_CACHE}" )
-	endif()
+    endif()
 
-	message( STATUS "---------------------------------------------------------" )
+    message( STATUS "---------------------------------------------------------" )
 
-	# clear the build dir exported targets file (only on the top project)
+    # clear the build dir exported targets file (only on the top project)
 
-	set( TOP_PROJECT_TARGETS_FILE "${PROJECT_BINARY_DIR}/${CMAKE_PROJECT_NAME}-targets.cmake" CACHE INTERNAL "" )
-	file( REMOVE ${TOP_PROJECT_TARGETS_FILE} )
+    set( TOP_PROJECT_TARGETS_FILE "${PROJECT_BINARY_DIR}/${CMAKE_PROJECT_NAME}-targets.cmake" CACHE INTERNAL "" )
+    file( REMOVE ${TOP_PROJECT_TARGETS_FILE} )
 
-	# add backport support for versions up too 2.8.4
-	if( ${CMAKE_VERSION} VERSION_LESS "2.8" )
-		set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/2.8" ${CMAKE_MODULE_PATH} )
-	endif()
+    # add backport support for versions up too 2.8.4
+    if( ${CMAKE_VERSION} VERSION_LESS "2.8" )
+    set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/2.8" ${CMAKE_MODULE_PATH} )
+    endif()
 
-	# add extra macros from external contributions
-	set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/contrib" )
+    # add extra macros from external contributions
+    set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/contrib" )
 
-	# would bring FindEigen in, so for the moment keep it out
-	# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/contrib/GreatCMakeCookOff" )
+    # would bring FindEigen in, so for the moment keep it out
+    # set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/contrib/GreatCMakeCookOff" )
 
-	include(CTest)                 # add cmake testing support
-	enable_testing()
+    include(CTest)                 # add cmake testing support
+    enable_testing()
 
-	# keep this until we modify the meaning to 'check' if installation worked
-	add_custom_target( check COMMAND ${CMAKE_CTEST_COMMAND} -V )
+    # keep this until we modify the meaning to 'check' if installation worked
+    add_custom_target( check COMMAND ${CMAKE_CTEST_COMMAND} -V )
 
-	############################################################################################
-	# define valid build types
+    ############################################################################################
+    # define valid build types
 
-	include(ecbuild_define_build_types)
+    include(ecbuild_define_build_types)
 
-	############################################################################################
-	# add cmake macros
+    ############################################################################################
+    # add cmake macros
 
-	include(AddFileDependencies)
+    include(AddFileDependencies)
 
-	include(CheckTypeSize)
-	include(CheckIncludeFile)
-	include(CheckIncludeFiles)
+    include(CheckTypeSize)
+    include(CheckIncludeFile)
+    include(CheckIncludeFiles)
 
-	include(CheckFunctionExists)
-	include(CheckSymbolExists)
+    include(CheckFunctionExists)
+    include(CheckSymbolExists)
 
-	include(CheckCCompilerFlag)
-	include(CheckCSourceCompiles)
-	include(CheckCSourceRuns)
+    include(CheckCCompilerFlag)
+    include(CheckCSourceCompiles)
+    include(CheckCSourceRuns)
 
-	include(CMakeParseArguments)
+    include(CMakeParseArguments)
 
-	# include(CMakePrintSystemInformation) # available in cmake 2.8.4
+    # include(CMakePrintSystemInformation) # available in cmake 2.8.4
 
-	if( CMAKE_CXX_COMPILER_LOADED )
-		include(CheckIncludeFileCXX)
-		include(CheckCXXCompilerFlag)
-		include(CheckCXXSourceCompiles)
-		include(CheckCXXSourceRuns)
-	endif()
+    if( CMAKE_CXX_COMPILER_LOADED )
+    include(CheckIncludeFileCXX)
+    include(CheckCXXCompilerFlag)
+    include(CheckCXXSourceCompiles)
+    include(CheckCXXSourceRuns)
+    endif()
 
-	if( CMAKE_Fortran_COMPILER_LOADED )
+    if( CMAKE_Fortran_COMPILER_LOADED )
         set( CMAKE_Fortran_MODULE_DIRECTORY  ${CMAKE_BINARY_DIR}/module CACHE PATH "directory for all fortran modules." )
-		include(CheckFortranFunctionExists)
-		if( CMAKE_C_COMPILER_LOADED AND ENABLE_FORTRAN_C_INTERFACE )
-			include(FortranCInterface)
-		endif()
-		set( EC_HAVE_FORTRAN 1 )
-	endif()
-
-	include(FeatureSummary) # support features in cmake
-
-	include(TestBigEndian)
-
-	############################################################################################
-	# backport of cmake > 2.8.4 functions
-
-	if( "${CMAKE_VERSION}" VERSION_LESS "2.8.6" )
-		include( ${CMAKE_CURRENT_LIST_DIR}/2.8/CMakePushCheckState.cmake )
-	else()
-		include(CMakePushCheckState)
-	endif()
-
-	############################################################################################
-	# add our macros
-
-	include( ecbuild_debug_var )
-	include( ecbuild_list_macros )
-
-	include( ecbuild_check_c_source )
-
-	if( CMAKE_CXX_COMPILER_LOADED )
-		include( ecbuild_check_cxx_source )
-		include( ecbuild_check_cxx11 )
-	endif()
-
-	if( CMAKE_Fortran_COMPILER_LOADED )
-		include( ecbuild_check_fortran_source )
-	endif()
-
-	include( ecbuild_requires_macro_version )
-	include( ecbuild_get_date )
-	include( ecbuild_add_persistent )
-	include( ecbuild_generate_config_headers )
-	include( ecbuild_generate_rpc )
-	include( ecbuild_generate_yy )
-	include( ecbuild_echo_targets )
-	include( ecbuild_add_option )
-	include( ecbuild_add_library )
-	include( ecbuild_add_executable )
-	include( ecbuild_append_to_rpath )
-	include( ecbuild_get_test_data )
-	include( ecbuild_add_cxx11_flags )
-	include( ecbuild_add_test )
-	include( ecbuild_add_resources )
-	include( ecbuild_get_resources )
-	include( ecbuild_project_files )
-	include( ecbuild_declare_project )
-	include( ecbuild_install_package )
-	include( ecbuild_separate_sources )
-	include( ecbuild_find_package )
-	include( ecbuild_use_package )
-	include( ecbuild_list_extra_search_paths )
-	include( ecbuild_add_extra_search_paths )
-	include( ecbuild_print_summary )
-	include( ecbuild_warn_unused_files )
-	include( ecbuild_find_mpi )
-	include( ecbuild_find_omp )
-	include( ecbuild_find_perl )
-	include( ecbuild_find_python )
-	include( ecbuild_find_lexyacc )
-	include( ecbuild_find_fortranlibs )
-	include( ecbuild_enable_fortran )
-	include( ecbuild_check_c_source )
-	include( ecbuild_check_cxx_source )
-	include( ecbuild_check_fortran_source )
-	include( ecbuild_bundle )
-	include( ecbuild_pkgconfig )
-	include( ecbuild_cache )
-
-	include( ${CMAKE_CURRENT_LIST_DIR}/contrib/GetGitRevisionDescription.cmake )
-
-	############################################################################################
-	# kickstart the build system
-
-  	ecbuild_prepare_cache()
-	include( ecbuild_define_options )               # define build options
-	include( ecbuild_check_compiler )               # check for compiler characteristics
-	include( ecbuild_check_os )                     # check for os characteristics
-	include( ecbuild_check_functions )              # check for available functions
-	include( ecbuild_define_paths )                 # define installation paths
-	include( ecbuild_links_target )                 # define the links target
-	include( ecbuild_setup_test_framework )         # setup test framework
- 	ecbuild_flush_cache()
-
-	############################################################################################
-	# define the build timestamp
-
-	if( NOT DEFINED EC_BUILD_TIMESTAMP )
-		ecbuild_get_timestamp( EC_BUILD_TIMESTAMP )
-		set( EC_BUILD_TIMESTAMP  "${EC_BUILD_TIMESTAMP}" CACHE INTERNAL "Build timestamp" )
-	endif()
-
-	message( STATUS "---------------------------------------------------------" )
+    include(CheckFortranFunctionExists)
+    if( CMAKE_C_COMPILER_LOADED AND ENABLE_FORTRAN_C_INTERFACE )
+    include(FortranCInterface)
+    endif()
+    set( EC_HAVE_FORTRAN 1 )
+    endif()
+
+    include(FeatureSummary) # support features in cmake
+
+    include(TestBigEndian)
+
+    ############################################################################################
+    # backport of cmake > 2.8.4 functions
+
+    if( "${CMAKE_VERSION}" VERSION_LESS "2.8.6" )
+    include( ${CMAKE_CURRENT_LIST_DIR}/2.8/CMakePushCheckState.cmake )
+    else()
+    include(CMakePushCheckState)
+    endif()
+
+    ############################################################################################
+    # add our macros
+
+    include( ecbuild_debug_var )
+    include( ecbuild_log )
+    include( ecbuild_list_macros )
+
+    include( ecbuild_check_c_source )
+
+    if( CMAKE_CXX_COMPILER_LOADED )
+    include( ecbuild_check_cxx_source )
+    include( ecbuild_check_cxx11 )
+    endif()
+
+    if( CMAKE_Fortran_COMPILER_LOADED )
+    include( ecbuild_check_fortran_source )
+    endif()
+
+    include( ecbuild_requires_macro_version )
+    include( ecbuild_get_date )
+    include( ecbuild_add_persistent )
+    include( ecbuild_generate_config_headers )
+    include( ecbuild_generate_rpc )
+    include( ecbuild_generate_yy )
+    include( ecbuild_echo_targets )
+    include( ecbuild_features )
+    include( ecbuild_add_option )
+    include( ecbuild_add_library )
+    include( ecbuild_add_executable )
+    include( ecbuild_append_to_rpath )
+    include( ecbuild_download_resource )
+    include( ecbuild_get_test_data )
+    include( ecbuild_add_cxx11_flags )
+    include( ecbuild_get_cxx11_flags )
+    include( ecbuild_add_test )
+    include( ecbuild_add_resources )
+    include( ecbuild_get_resources )
+    include( ecbuild_dont_pack )
+    include( ecbuild_project_files )
+    include( ecbuild_declare_project )
+    include( ecbuild_install_project )
+    include( ecbuild_separate_sources )
+    include( ecbuild_find_package )
+    include( ecbuild_use_package )
+    include( ecbuild_list_extra_search_paths )
+    include( ecbuild_add_extra_search_paths )
+    include( ecbuild_print_summary )
+    include( ecbuild_warn_unused_files )
+    include( ecbuild_find_mpi )
+    include( ecbuild_find_omp )
+    include( ecbuild_find_perl )
+    include( ecbuild_find_python )
+    include( ecbuild_find_lexyacc )
+    include( ecbuild_find_fortranlibs )
+    include( ecbuild_git )
+    include( ecbuild_enable_fortran )
+    include( ecbuild_check_c_source )
+    include( ecbuild_check_cxx_source )
+    include( ecbuild_check_fortran_source )
+    include( ecbuild_bundle )
+    include( ecbuild_pkgconfig )
+    include( ecbuild_cache )
+
+    include( ${CMAKE_CURRENT_LIST_DIR}/contrib/GetGitRevisionDescription.cmake )
+
+    ############################################################################################
+    # kickstart the build system
+
+      ecbuild_prepare_cache()
+
+    include( ecbuild_define_options )               # define build options
+    include( ecbuild_check_compiler )               # check for compiler characteristics
+    include( ecbuild_check_os )                     # check for os characteristics
+    include( ecbuild_check_functions )              # check for available functions
+    include( ecbuild_define_paths )                 # define installation paths
+    include( ecbuild_links_target )                 # define the links target
+    include( ecbuild_setup_test_framework )         # setup test framework
+    include( ecbuild_define_uninstall )             # define uninstall target
+
+    ecbuild_flush_cache()
+
+    ############################################################################################
+    # define the build timestamp
+
+    if( NOT DEFINED EC_BUILD_TIMESTAMP )
+        ecbuild_get_timestamp( EC_BUILD_TIMESTAMP )
+        set( EC_BUILD_TIMESTAMP  "${EC_BUILD_TIMESTAMP}" CACHE INTERNAL "Build timestamp" )
+    endif()
+
+    message( STATUS "---------------------------------------------------------" )
 
 endif()
 
diff --git a/cmake/ecbuild_uninstall.cmake.in b/cmake/ecbuild_uninstall.cmake.in
new file mode 100644
index 0000000..2037e36
--- /dev/null
+++ b/cmake/ecbuild_uninstall.cmake.in
@@ -0,0 +1,21 @@
+if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+  message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+
+file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
+string(REGEX REPLACE "\n" ";" files "${files}")
+foreach(file ${files})
+  message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
+  if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+    exec_program(
+      "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
+      OUTPUT_VARIABLE rm_out
+      RETURN_VALUE rm_retval
+      )
+    if(NOT "${rm_retval}" STREQUAL 0)
+      message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
+    endif(NOT "${rm_retval}" STREQUAL 0)
+  else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+    message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
+  endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+endforeach(file)
diff --git a/cmake/ecbuild_use_package.cmake b/cmake/ecbuild_use_package.cmake
index 1c44894..1746cd1 100644
--- a/cmake/ecbuild_use_package.cmake
+++ b/cmake/ecbuild_use_package.cmake
@@ -7,203 +7,280 @@
 # does it submit to any jurisdiction.
 
 ##############################################################################
-# function for adding a subproject directory
+#.rst:
+#
+# ecbuild_use_package
+# ===================
+#
+# Add a project from a source directory, a subdirectory or search for it. ::
+#
+#   ecbuild_use_package( PROJECT <name>
+#                        [ VERSION <version> [ EXACT ] ]
+#                        [ REQUIRED ]
+#                        [ QUIET ] )
+#
+# Options
+# -------
+#
+# NAME : required
+#   package name (used as ``Find<name>.cmake`` and ``<name>-config.cmake``)
+#
+# VERSION : optional
+#   minimum required package version
+#
+# EXACT : optional, requires VERSION
+#   require the exact version rather than a minimum version
+#
+# REQUIRED : optional
+#   fail if package cannot be found
+#
+# QUIET : optional
+#   do not output package information if found
+#
+# Input variables
+# ---------------
+#
+# The following CMake variables influence the behaviour if set (``<name>``
+# is the package name as given, ``<NAME>`` is the capitalised version):
+#
+# :<NAME>_SOURCE:    path to source directory for package
+# :SUBPROJECT_DIRS:  list of additional paths to search for package source
+#
+# See also ``ecbuild_find_package`` for additional CMake variables relevant
+# when search for the package (step 6 below).
+#
+# Usage
+# -----
+#
+# Use another CMake project as a dependency by either building it from source
+# i.e. adding its source directory as a subdirectory or searching for it. This
+# transparently deals with the case where the project has already been included
+# e.g. because multiple projects with shared dependencies are built together.
+#
+# The search proceeds as follows:
+#
+# 1.  If ``SUBPROJECT_DIRS`` is set, each directory in the list is searched
+#     for a subdirectory <name> and ``<NAME>_SOURCE`` is set to the first one
+#     found (if any).
+#
+# 2.  If ``<NAME>_SOURCE`` is set, check if this directory is a CMake project
+#     (contains ``CMakeLists.txt`` and fail if not.
+#
+# 3.  Otherwise, check if the current directory has a ``<name>`` subdirectory.
+#
+# 4.  If the project has not been previously marked as found or added as a
+#     subdirectory and a project source directory has been found in steps 1-3
+#     add this subdirectory.
+#
+# 5.  If the project has been marked as found, check the version.
+#
+# 6.  Otherwise, search for the project using ``ecbuild_find_package``.
+#
 ##############################################################################
 
 macro( ecbuild_use_package )
 
-    set( options            REQUIRED QUIET EXACT )
-    set( single_value_args  PROJECT VERSION )
-    set( multi_value_args )
-
-	cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
+  set( options            REQUIRED QUIET EXACT )
+  set( single_value_args  PROJECT VERSION )
+  set( multi_value_args )
 
-	if(_p_UNPARSED_ARGUMENTS)
-	  message(FATAL_ERROR "Unknown keywords given to ecbuild_use_package(): \"${_p_UNPARSED_ARGUMENTS}\"")
-    endif()
+  cmake_parse_arguments( _p "${options}" "${single_value_args}" "${multi_value_args}"  ${_FIRST_ARG} ${ARGN} )
 
-	if( NOT _p_PROJECT  )
-      message(FATAL_ERROR "The call to ecbuild_use_package() doesn't specify the PROJECT.")
-    endif()
+  if(_p_UNPARSED_ARGUMENTS)
+    message(FATAL_ERROR "Unknown keywords given to ecbuild_use_package(): \"${_p_UNPARSED_ARGUMENTS}\"")
+  endif()
 
-	if( _p_EXACT AND NOT _p_VERSION )
-      message(FATAL_ERROR "Call to ecbuild_use_package() requests EXACT but doesn't specify VERSION.")
-    endif()
+  if( NOT _p_PROJECT  )
+    message(FATAL_ERROR "The call to ecbuild_use_package() doesn't specify the PROJECT.")
+  endif()
 
-    # try to find the package as a subproject and build it
+  if( _p_EXACT AND NOT _p_VERSION )
+    message(FATAL_ERROR "Call to ecbuild_use_package() requests EXACT but doesn't specify VERSION.")
+  endif()
 
-	string( TOUPPER ${_p_PROJECT} PNAME )
+  # try to find the package as a subproject and build it
 
-    # user defined dir with subprojects
+  string( TOUPPER ${_p_PROJECT} PNAME )
 
-    if( NOT DEFINED ${PNAME}_SOURCE AND DEFINED SUBPROJECT_DIRS )
-        foreach( dir ${SUBPROJECT_DIRS} )
-			if( EXISTS ${dir}/${_p_PROJECT} AND EXISTS ${dir}/${_p_PROJECT}/CMakeLists.txt )
-				set( ${PNAME}_SOURCE "${dir}/${_p_PROJECT}" )
-            endif()
-        endforeach()
-    endif()
+  # user defined dir with subprojects
 
-    # user defined path to subproject
+  if( NOT DEFINED ${PNAME}_SOURCE AND DEFINED SUBPROJECT_DIRS )
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): scanning subproject directories ${SUBPROJECT_DIRS}")
+    foreach( dir ${SUBPROJECT_DIRS} )
+      if( EXISTS ${dir}/${_p_PROJECT} AND EXISTS ${dir}/${_p_PROJECT}/CMakeLists.txt )
+        ecbuild_debug("ecbuild_use_package(${_p_PROJECT}):   setting ${PNAME}_SOURCE to ${dir}/${_p_PROJECT}")
+        set( ${PNAME}_SOURCE "${dir}/${_p_PROJECT}" )
+      endif()
+    endforeach()
+  endif()
 
-    if( DEFINED ${PNAME}_SOURCE )
+  # user defined path to subproject
 
-        if( NOT EXISTS ${${PNAME}_SOURCE} OR NOT EXISTS ${${PNAME}_SOURCE}/CMakeLists.txt )
-			message( FATAL_ERROR "User defined source directory '${${PNAME}_SOURCE}' for project '${_p_PROJECT}' does not exist or does not contain a CMakeLists.txt file." )
-        endif()
+  if( DEFINED ${PNAME}_SOURCE )
 
-		set( ${PNAME}_subproj_dir_ "${${PNAME}_SOURCE}" )
+    if( NOT EXISTS ${${PNAME}_SOURCE} OR NOT EXISTS ${${PNAME}_SOURCE}/CMakeLists.txt )
+      message( FATAL_ERROR "User defined source directory '${${PNAME}_SOURCE}' for project '${_p_PROJECT}' does not exist or does not contain a CMakeLists.txt file." )
+    endif()
 
-    else() # default is 'dropped in' subdirectory named as project
+    set( ${PNAME}_subproj_dir_ "${${PNAME}_SOURCE}" )
 
-		if( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT} AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT}/CMakeLists.txt )
-			set( ${PNAME}_subproj_dir_ "${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT}" )
-        endif()
+  else() # default is 'dropped in' subdirectory named as project
 
+    if( EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT} AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT}/CMakeLists.txt )
+      ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): found ${_p_PROJECT} in subdirectory ${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT}")
+      set( ${PNAME}_subproj_dir_ "${CMAKE_CURRENT_SOURCE_DIR}/${_p_PROJECT}" )
     endif()
 
-    # check if was already added as subproject ...
+  endif()
 
-    set( _just_added 0 )
-    set( _do_version_check 0 )
-    set( _source_description "" )
+  # check if was already added as subproject ...
 
-	list( FIND ECBUILD_PROJECTS ${_p_PROJECT} _ecbuild_project_${PNAME} )
+  set( _just_added 0 )
+  set( _do_version_check 0 )
+  set( _source_description "" )
 
-    if( NOT _ecbuild_project_${PNAME} EQUAL "-1" )
-		set( ${PNAME}_previous_subproj_ 1 )
-    else()
-		set( ${PNAME}_previous_subproj_ 0 )
-    endif()
+  list( FIND ECBUILD_PROJECTS ${_p_PROJECT} _ecbuild_project_${PNAME} )
 
-    # solve capitalization issues
-    
-	if( ${_p_PROJECT}_FOUND AND NOT ${PNAME}_FOUND )
-        set( ${PNAME}_FOUND 1 ) 
-    endif()
-	if( ${PNAME}_FOUND AND NOT ${_p_PROJECT}_FOUND )
-		set( ${_p_PROJECT}_FOUND 1 )
-    endif()
+  if( NOT _ecbuild_project_${PNAME} EQUAL "-1" )
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): ${_p_PROJECT} was previously added as a subproject")
+    set( ${PNAME}_previous_subproj_ 1 )
+  else()
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): ${_p_PROJECT} was not previously added as a subproject")
+    set( ${PNAME}_previous_subproj_ 0 )
+  endif()
 
-    # Case 1) project was NOT added as subproject and is NOT FOUND
+  # solve capitalization issues
 
-	if( NOT ${PNAME}_FOUND AND NOT ${PNAME}_previous_subproj_ )
+  if( ${_p_PROJECT}_FOUND AND NOT ${PNAME}_FOUND )
+    set( ${PNAME}_FOUND 1 )
+  endif()
+  if( ${PNAME}_FOUND AND NOT ${_p_PROJECT}_FOUND )
+    set( ${_p_PROJECT}_FOUND 1 )
+  endif()
 
-            # check if SUBPROJDIR is set
+  # Case 1) project was NOT previously added as subproject and is NOT already FOUND
 
-			if( DEFINED ${PNAME}_subproj_dir_ )
+  if( NOT ${PNAME}_FOUND AND NOT ${PNAME}_previous_subproj_ )
 
-                # check version is acceptable
-                set( _just_added 1 )
-                set( _do_version_check 1 )
-				set( _source_description "sub-project ${_p_PROJECT} (sources)" )
+    # check if SUBPROJDIR is set
 
-                # add as a subproject
+    if( DEFINED ${PNAME}_subproj_dir_ )
 
-				set( ${PNAME}_subproj_dir_ ${${PNAME}_subproj_dir_} CACHE PATH "Path to ${_p_PROJECT} source directory" )
+      ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): 1) project was NOT previously added as subproject and is NOT already FOUND")
 
-				set( ECBUILD_PROJECTS ${ECBUILD_PROJECTS} ${_p_PROJECT} CACHE INTERNAL "" )
+      # check version is acceptable
+      set( _just_added 1 )
+      set( _do_version_check 1 )
+      set( _source_description "sub-project ${_p_PROJECT} (sources)" )
 
-				add_subdirectory( ${${PNAME}_subproj_dir_} ${_p_PROJECT} )
+      # add as a subproject
 
-				set( ${_p_PROJECT}_BASE_DIR ${CMAKE_BINARY_DIR} )
+      set( ${PNAME}_subproj_dir_ ${${PNAME}_subproj_dir_} CACHE PATH "Path to ${_p_PROJECT} source directory" )
 
-				set( ${PNAME}_FOUND 1 )
-				set( ${_p_PROJECT}_VERSION ${${PNAME}_VERSION} )
+      set( ECBUILD_PROJECTS ${ECBUILD_PROJECTS} ${_p_PROJECT} CACHE INTERNAL "" )
 
-            endif()
+      ecbuild_debug("ecbuild_use_package(${_p_PROJECT}):    ${_p_PROJECT} found in subdirectory ${${PNAME}_subproj_dir_}")
+      add_subdirectory( ${${PNAME}_subproj_dir_} ${_p_PROJECT} )
+
+      set( ${_p_PROJECT}_BASE_DIR ${CMAKE_BINARY_DIR} )
+
+      set( ${PNAME}_FOUND 1 )
+      set( ${_p_PROJECT}_VERSION ${${PNAME}_VERSION} )
 
     endif()
 
-    # Case 2) project was already added as subproject, so is already FOUND -- BUT must check version acceptable
+  endif()
 
-	if( ${PNAME}_previous_subproj_ )
+  # Case 2) project was already added as subproject, so is already FOUND -- BUT must check version acceptable
 
-        if( NOT ${PNAME}_FOUND )
-			message( FATAL_ERROR "${_p_PROJECT} was already included as sub-project but ${PNAME}_FOUND isn't set -- this is likely a BUG in ecbuild" )
-        endif()
+  if( ${PNAME}_previous_subproj_ )
 
-        # check version is acceptable
-        set( _do_version_check 1 )
-		set( _source_description "already existing sub-project ${_p_PROJECT} (sources)" )
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): 2) project was already added as subproject, check version is acceptable")
 
+    if( NOT ${PNAME}_FOUND )
+      message( FATAL_ERROR "${_p_PROJECT} was already included as sub-project but ${PNAME}_FOUND isn't set -- this is likely a BUG in ecbuild" )
     endif()
 
-    # Case 3) project was NOT added as subproject, but is FOUND -- so it was previously found as a binary ( either build or install tree )
+    # check version is acceptable
+    set( _do_version_check 1 )
+    set( _source_description "already existing sub-project ${_p_PROJECT} (sources)" )
 
-	if( ${PNAME}_FOUND AND NOT ${PNAME}_previous_subproj_ AND NOT _just_added )
+  endif()
 
-        # check version is acceptable
-        set( _do_version_check 1 )
-		set( _source_description "previously found package ${_p_PROJECT} (binaries)" )
+  # Case 3) project was NOT added as subproject, but is FOUND -- so it was previously found as a binary ( either build or install tree )
 
-    endif()
+  if( ${PNAME}_FOUND AND NOT ${PNAME}_previous_subproj_ AND NOT _just_added )
 
-    # test version for Cases 1,2,3
-
-# debug_var( _p_PROJECT )
-# debug_var( _p_VERSION )
-# debug_var( ${PNAME}_VERSION )
-# debug_var( ${_p_PROJECT}_VERSION )
-# debug_var( _just_added )
-# debug_var( _do_version_check )
-# debug_var( _source_description )
-# debug_var( ${PNAME}_FOUND )
-# debug_var( ${PNAME}_previous_subproj_ )
-
-	if( _p_VERSION AND _do_version_check )
-			if( _p_EXACT )
-				if( NOT ${_p_PROJECT}_VERSION VERSION_EQUAL _p_VERSION )
-					message( FATAL_ERROR "${PROJECT_NAME} requires (exactly) ${_p_PROJECT} = ${_p_VERSION} -- detected as ${_source_description} ${${_p_PROJECT}_VERSION}" )
-                endif()
-            else()
-				if( _p_VERSION VERSION_LESS ${_p_PROJECT}_VERSION OR _p_VERSION VERSION_EQUAL ${_p_PROJECT}_VERSION )
-					message( STATUS "${PROJECT_NAME} requires ${_p_PROJECT} >= ${_p_VERSION} -- detected as ${_source_description} ${${_p_PROJECT}_VERSION}" )
-				else()
-					message( FATAL_ERROR "${PROJECT_NAME} requires ${_p_PROJECT} >= ${_p_VERSION} -- detected only ${_source_description} ${${_p_PROJECT}_VERSION}" )
-                endif()
-            endif()
-    endif()
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): 3) project was NOT previously added as subproject, but is FOUND")
 
-    # Case 4) is NOT FOUND so far, NOT as sub-project (now or before), and NOT as binary neither 
-    #         so try to find precompiled binaries or a build tree
+    # check version is acceptable
+    set( _do_version_check 1 )
+    set( _source_description "previously found package ${_p_PROJECT} (binaries)" )
 
-    if( NOT ${PNAME}_FOUND )
+  endif()
 
-        set( _opts )
-		if( _p_VERSION )
-			list( APPEND _opts VERSION ${_p_VERSION} )
-        endif()
-		if( _p_EXACT )
-            list( APPEND _opts EXACT )
-        endif()
-		if( _p_REQUIRED )
-            list( APPEND _opts REQUIRED )
-        endif()
-    
-		ecbuild_find_package( NAME ${_p_PROJECT} ${_opts} )
+  # test version for Cases 1,2,3
+
+  # debug_var( _p_PROJECT )
+  # debug_var( _p_VERSION )
+  # debug_var( ${PNAME}_VERSION )
+  # debug_var( ${_p_PROJECT}_VERSION )
+  # debug_var( _just_added )
+  # debug_var( _do_version_check )
+  # debug_var( _source_description )
+  # debug_var( ${PNAME}_FOUND )
+  # debug_var( ${PNAME}_previous_subproj_ )
+
+  if( _p_VERSION AND _do_version_check )
+    if( _p_EXACT )
+      if( NOT ${_p_PROJECT}_VERSION VERSION_EQUAL _p_VERSION )
+        message( FATAL_ERROR "${PROJECT_NAME} requires (exactly) ${_p_PROJECT} = ${_p_VERSION} -- detected as ${_source_description} ${${_p_PROJECT}_VERSION}" )
+      endif()
+    else()
+      if( _p_VERSION VERSION_LESS ${_p_PROJECT}_VERSION OR _p_VERSION VERSION_EQUAL ${_p_PROJECT}_VERSION )
+        message( STATUS "${PROJECT_NAME} requires ${_p_PROJECT} >= ${_p_VERSION} -- detected as ${_source_description} ${${_p_PROJECT}_VERSION}" )
+      else()
+        message( FATAL_ERROR "${PROJECT_NAME} requires ${_p_PROJECT} >= ${_p_VERSION} -- detected only ${_source_description} ${${_p_PROJECT}_VERSION}" )
+      endif()
+    endif()
+  endif()
 
-		if( ${_p_PROJECT}_FOUND )
+  # Case 4) is NOT FOUND so far, NOT as sub-project (now or before), and NOT as binary neither
+  #         so try to find precompiled binaries or a build tree
 
-			set( ${PNAME}_FOUND ${${_p_PROJECT}_FOUND} )
+  if( NOT ${PNAME}_FOUND )
 
-			message( STATUS "[${_p_PROJECT}] (${${_p_PROJECT}_VERSION})" )
+    ecbuild_debug("ecbuild_use_package(${_p_PROJECT}): 4) project has NOT been added as a subproject and is NOT already FOUND")
 
-            message( STATUS "   ${PNAME}_INCLUDE_DIRS : [${${PNAME}_INCLUDE_DIRS}]" )
-            if( ${PNAME}_DEFINITIONS )
-                message( STATUS "   ${PNAME}_DEFINITIONS : [${${PNAME}_DEFINITIONS}]" )
-            endif()
-            message( STATUS "   ${PNAME}_LIBRARIES : [${${PNAME}_LIBRARIES}]" )
+    set( _opts )
+    if( _p_VERSION )
+      list( APPEND _opts VERSION ${_p_VERSION} )
+    endif()
+    if( _p_EXACT )
+      list( APPEND _opts EXACT )
+    endif()
+    if( _p_REQUIRED )
+      list( APPEND _opts REQUIRED )
+    endif()
 
-        endif()
+    ecbuild_find_package( NAME ${_p_PROJECT} ${_opts} )
 
+    if( ${_p_PROJECT}_FOUND )
+      set( ${PNAME}_FOUND ${${_p_PROJECT}_FOUND} )
     endif()
 
-### for when we change this macro to a function()
-#	set_parent_scope( ${PNAME}_FOUND )
-#	set_parent_scope( ${_p_PROJECT}_FOUND )
-#	set_parent_scope( ${PNAME}_VERSION )
-#	set_parent_scope( ${_p_PROJECT}_VERSION )
-# set_parent_scope( ${_p_PROJECT}_BINARY_DIR )
+  endif()
+
+  if( ${PNAME}_FOUND )
+    list( APPEND ${PROJECT_NAME_CAPS}_TPLS ${_p_PROJECT} )
+    list( REMOVE_DUPLICATES ${PROJECT_NAME_CAPS}_TPLS )
+  endif()
+
+  ### for when we change this macro to a function()
+  # set_parent_scope( ${PNAME}_FOUND )
+  # set_parent_scope( ${_p_PROJECT}_FOUND )
+  # set_parent_scope( ${PNAME}_VERSION )
+  # set_parent_scope( ${_p_PROJECT}_VERSION )
+  # set_parent_scope( ${_p_PROJECT}_BINARY_DIR )
 
 endmacro()
diff --git a/cmake/ecbuild_warn_unused_files.cmake b/cmake/ecbuild_warn_unused_files.cmake
index c3aa7d5..c33b213 100644
--- a/cmake/ecbuild_warn_unused_files.cmake
+++ b/cmake/ecbuild_warn_unused_files.cmake
@@ -6,8 +6,28 @@
 # granted to it by virtue of its status as an intergovernmental organisation nor
 # does it submit to any jurisdiction.
 
-############################################################################################
-# print warnings about unused files
+##############################################################################
+#.rst:
+#
+# ecbuild_warn_unused_files
+# =========================
+#
+# Print warnings about unused source files in the project. ::
+#
+#   ecbuild_warn_unused_files()
+#
+# If the CMake variable ``CHECK_UNUSED_FILES`` is set, ecBuild will keep track
+# of any source files (.c, .cc, .cpp, .cxx) which are not part of a CMake
+# target. If set, this macro reports unused files if any have been found. This
+# is considered a fatal error unless ``UNUSED_FILES_LEVEL`` is set to a value
+# different from ``ERROR``.
+#
+# .. note ::
+#
+#   Enabling ``CHECK_UNUSED_FILES`` can slow down the CMake configure time
+#   considerably!
+#
+##############################################################################
 
 macro( ecbuild_warn_unused_files )
 
@@ -26,15 +46,14 @@ macro( ecbuild_warn_unused_files )
           endif()
     
           # if unused files where found, put the list on the file
-          list( LENGTH MARS_UNUSED_FILES MARS_LENGTH_UNUSED_FILES )
-          if( MARS_LENGTH_UNUSED_FILES )
+          if( EC_UNUSED_FILES )
     
             message( STATUS "")
             message( STATUS " !!!--- ${UNUSED_FILES_LEVEL} ---!!! ")
             message( STATUS " !!!--- ${UNUSED_FILES_LEVEL} ---!!! ")
             message( STATUS "")
             message( STATUS " Unused source files found:")
-            foreach( AFILE ${MARS_UNUSED_FILES} )
+            foreach( AFILE ${EC_UNUSED_FILES} )
               message( STATUS "     ${AFILE}")
               file( APPEND ${UNUSED_FILE} "${AFILE}\n" )
             endforeach()
diff --git a/cmake/pkg-config.pc.in b/cmake/pkg-config.pc.in
index 86031db..e6d903d 100644
--- a/cmake/pkg-config.pc.in
+++ b/cmake/pkg-config.pc.in
@@ -5,10 +5,10 @@ git_tag=@PKGCONFIG_GIT_TAG@
 
 prefix=@CMAKE_INSTALL_PREFIX@
 exec_prefix=${prefix}
-libdir=${prefix}/lib
-includedir=${prefix}/include
-bindir=${prefix}/bin
-fmoddir=${prefix}/include
+libdir=${prefix}/@INSTALL_LIB_DIR@
+includedir=${prefix}/@INSTALL_INCLUDE_DIR@
+bindir=${prefix}/@INSTALL_BIN_DIR@
+fmoddir=${prefix}/@INSTALL_INCLUDE_DIR@
 
 CC=@CMAKE_C_COMPILER@
 CXX=@CMAKE_CXX_COMPILER@
diff --git a/cmake/project-config.cmake.in b/cmake/project-config.cmake.in
index 9c1bdcb..03f875b 100644
--- a/cmake/project-config.cmake.in
+++ b/cmake/project-config.cmake.in
@@ -47,9 +47,12 @@ set( @PNAME at _LIBRARIES        ${@PNAME at _SELF_LIBRARIES}   ${@PNAME at _TPL_LIBRARIE
 
 set( @PNAME at _FEATURES    "@CONF_FEATURES@" )
 foreach( _f ${@PNAME at _FEATURES} )
-	set( ${_f} 1 )
+	set( @PNAME at _HAVE_${_f} 1 )
 endforeach()
 
+# Has this configuration been exported from a build tree?
+set( @PNAME at _IS_BUILD_DIR_EXPORT @_is_build_dir_export@ )
+
 if( EXISTS ${@PNAME at _CMAKE_DIR}/@CONF_IMPORT_FILE@ )
   set( @PNAME at _IMPORT_FILE "${@PNAME at _CMAKE_DIR}/@CONF_IMPORT_FILE@" )
   include( ${@PNAME at _IMPORT_FILE} )
@@ -59,9 +62,7 @@ endif()
 
 if( NOT @PROJECT_NAME at _BINARY_DIR )
 
-	set( IS_BUILD_DIR_EXPORT @_is_build_dir_export@ )
-
-	if( IS_BUILD_DIR_EXPORT )
+  if( @PNAME at _IS_BUILD_DIR_EXPORT )
 		include( "@TOP_PROJECT_TARGETS_FILE@" OPTIONAL )
 	else()
 		include( "${@PNAME at _CMAKE_DIR}/@CMAKE_PROJECT_NAME at -targets.cmake" )
@@ -81,7 +82,7 @@ mark_as_advanced( @PNAME at _IMPORT_FILE )
 # set @PROJECT_NAME at _BASE_DIR for final installations or build directories
 
 if( NOT @PROJECT_NAME@ )
-	if( @_is_build_dir_export@ )
+	if( @PNAME at _IS_BUILD_DIR_EXPORT )
 		set( @PROJECT_NAME at _BASE_DIR @CMAKE_BINARY_DIR@ )
 	else()
 		set( @PROJECT_NAME at _BASE_DIR @CMAKE_INSTALL_PREFIX@ )
diff --git a/cmake/pymain.c b/cmake/pymain.c
new file mode 100644
index 0000000..823d57d
--- /dev/null
+++ b/cmake/pymain.c
@@ -0,0 +1,5 @@
+#include <Python.h>
+
+int main() {
+  return 0;
+}
diff --git a/scripts/CMakeLists.txt b/scripts/CMakeLists.txt
index e5ab3b5..626f8d0 100644
--- a/scripts/CMakeLists.txt
+++ b/scripts/CMakeLists.txt
@@ -36,10 +36,9 @@ metview_script_files(SCRIPT_FILES ${scripts})
 #
 # generate the 'compile' script for inline C/Fortran in Macro
 
-# only use the first library returned in EMOS_LIBRARIES
-# - this is because it can also return a list of shared libraries used by
-# the PGI compiler which can then not be found at run-time.
-list(GET EMOS_LIBRARIES 0 EMOS_FIRST_LIB)
+
+# find the actual path to the emoslib library
+get_property(EMOS_LIB_PATH TARGET emos PROPERTY LOCATION)
 
 
 # for GRIB_API, we *might* get something like
@@ -48,13 +47,16 @@ list(GET EMOS_LIBRARIES 0 EMOS_FIRST_LIB)
 # and for the Fortran libraries.
 
 set(GRIB_API_LIBRARIES_STR " ${GRIB_API_LIBRARIES}") # add a space to the beginning
+list(REMOVE_ITEM GRIB_API_LIBRARIES_STR "debug")     # remove non-compiler items from the string
+list(REMOVE_ITEM GRIB_API_LIBRARIES_STR "optimized") # remove non-compiler items from the string
 
 string (REPLACE ";"         " "           GRIB_API_LIBRARIES_STR    "${GRIB_API_LIBRARIES_STR}")
 string (REPLACE " grib_api" " -lgrib_api" GRIB_API_LIBRARIES_STR    "${GRIB_API_LIBRARIES_STR}")
-string (REPLACE ";"         " "           EMOS_LIBRARIES_STR        "${EMOS_FIRST_LIB}")
+string (REPLACE ";"         " "           EMOS_LIBRARIES_STR        "${EMOS_LIB_PATH}")
 
 
 set(GRIB_API_LIBRARIES_STR "${GRIB_API_LIBRARIES_STR} ${PTHREAD_LIB}") # add pthread in case needed
+set(GRIB_API_LIBRARIES_STR_ORIGINAL "${GRIB_API_LIBRARIES_STR}")       # keep a backup for later
 
 # if we are linking with shared GRIB_API libraries, then in order to be able
 # to run compiled inline Fortran/C/Macro programs, we will need to set
@@ -62,14 +64,24 @@ set(GRIB_API_LIBRARIES_STR "${GRIB_API_LIBRARIES_STR} ${PTHREAD_LIB}") # add pth
 # needed if GRIB_API was installed in a non-default location).
 # GRIB_API_LIB_DIR will be added to METVIEW_LD_PATHS and used in compile.in.
 
-# first, if CMAKE_PREFIX_PATH is defined and GRIB_API_PATH is not, then
-# GRIB_API might be installed in CMAKE_PREFIX_PATH
-if(CMAKE_PREFIX_PATH)
-    if(NOT GRIB_API_PATH)
-        set(GRIB_API_PATH ${CMAKE_PREFIX_PATH})
+# first, if GRIB_API_PATH is not defined, then we need to compute the path
+if(NOT GRIB_API_PATH)
+    get_property(GRIB_LIB_PATH TARGET grib_api PROPERTY LIBRARY_OUTPUT_DIRECTORY)
+    if(GRIB_LIB_PATH)
+        set(GRIB_API_PATH ${GRIB_LIB_PATH}/..)
+    else()
+        if (grib_api_BASE_DIR)
+            set(GRIB_API_PATH ${grib_api_BASE_DIR})
+        else()
+            if(CMAKE_PREFIX_PATH)
+                set(GRIB_API_PATH ${CMAKE_PREFIX_PATH})
+            endif()
+        endif()
     endif()
+    message(STATUS "Computed GRIB_PATH: ${GRIB_API_PATH}")
 endif()
 
+
 if(GRIB_API_PATH)
     if(EXISTS "${GRIB_API_PATH}/lib")
         set(GRIB_API_LIB_DIR "${GRIB_API_PATH}/lib")
@@ -83,14 +95,41 @@ if(GRIB_API_PATH)
     set(GRIB_API_LIBRARIES_STR "-L${GRIB_API_PATH}/lib -L${GRIB_API_PATH}/lib64 ${GRIB_API_LIBRARIES_STR}")
 endif()
 
+
 foreach (inc ${GRIB_API_INCLUDE_DIRS})
     set(GRIB_API_INCLUDE_DIRS_STR "${GRIB_API_INCLUDE_DIRS_STR} -I${inc}")
 endforeach()
 
 
+
+list(APPEND METVIEW_INLINE_DEFINITIONS ${GRIB_API_DEFINITIONS})
+
+
+
 configure_file(compile.in ${CMAKE_BINARY_DIR}/bin/compile @ONLY)
-install( FILES ${CMAKE_BINARY_DIR}/bin/compile  
+
+
+
+# in the case of a bundle, the GRIB_API and emoslib locations will have been
+# set to their build directories, which is correct when running from 
+# the build directory, but not once installed, so we have to change these
+# to the location where they will be installed, and create another 'compile'
+# script which is the one that will actually be installed. In the case where
+# we're not building a bundle, these two compile scripts will be identical.
+
+if(DEFINED METVIEW_BUNDLE)
+    set(GRIB_API_LIBRARIES_STR    "-L${CMAKE_INSTALL_PREFIX}/lib ${GRIB_API_LIBRARIES_STR_ORIGINAL}")
+    set(GRIB_API_INCLUDE_DIRS_STR "-I${CMAKE_INSTALL_PREFIX}/include")
+    string(REPLACE "${CMAKE_BINARY_DIR}/lib"  "${CMAKE_INSTALL_PREFIX}/lib"    EMOS_LIBRARIES_STR  "${EMOS_LIBRARIES_STR}")
+endif()
+
+configure_file(compile.in ${CMAKE_BINARY_DIR}/bin/compile_install @ONLY)
+
+
+
+install( FILES ${CMAKE_BINARY_DIR}/bin/compile_install  
          DESTINATION ${MV_BIN_DIR}
+         RENAME      compile
          PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
 
 
@@ -106,6 +145,15 @@ else()
     set(NETCDF_BIN "")
 endif()
 
+if(DEFINED METVIEW_BUNDLE)
+    set(METVIEW_BUNDLE_SRC ${CMAKE_SOURCE_DIR})
+endif()
+
+if(DEFINED METVIEW_BUNDLE_MAGICS)
+    set(MV_BUNDLE_MAGICS_SRC ${CMAKE_SOURCE_DIR}/magics)
+endif()
+
+
 
 ecbuild_get_date(TODAYS_DATE)
 
@@ -122,23 +170,14 @@ set(METVIEW_LD_PATHS "")
 
 foreach(LIBPATH ${MAGICS_LIB_DIR} ${ODB_API_LIB_DIR} ${GRIB_API_LIB_DIR})
     list(FIND SYS_LIBDIRS ${LIBPATH} IND)
-    #message(STATUS "IS ${LIBPATH} ${IND}")
     if(IND EQUAL -1)  # path not in the list of system paths
         set(METVIEW_LD_PATHS "${LIBPATH}:${METVIEW_LD_PATHS}")
     endif()
 endforeach()
 
 
-configure_file(CONFIG.site.in  CONFIG.site @ONLY)
-
-
-# concatenate CONFIG.site and metview_base into the Metview startup script
-
-add_custom_command( 
-    OUTPUT  ${FULL_STARTUP_SCRIPT_PATH}
-    COMMAND cat  ${CMAKE_CURRENT_BINARY_DIR}/CONFIG.site > ${FULL_STARTUP_SCRIPT_PATH} \; cat ${CMAKE_CURRENT_SOURCE_DIR}/metview_base >> ${FULL_STARTUP_SCRIPT_PATH} \; chmod uga+x ${FULL_STARTUP_SCRIPT_PATH}
-    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/CONFIG.site ${CMAKE_CURRENT_SOURCE_DIR}/metview_base
-)
+# create the Metview startup script
+configure_file(metview_base.in ${FULL_STARTUP_SCRIPT_PATH} @ONLY)
 
 
 # create a 'production' version of this - just the same, but with
diff --git a/scripts/CONFIG.site.in b/scripts/CONFIG.site.in
deleted file mode 100644
index ef3a1d6..0000000
--- a/scripts/CONFIG.site.in
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/bin/ksh
-#
-# DO NOT EDIT! SCRIPT PRODUCED BY make IN DIR ./scripts!
-#
-set -ea
-#
-# THIS FILE IS GENERATED BY configure on @TODAYS_DATE@
-#
-WMO_SITE_NR=@SITE_WMO_CODE@
-##QT_DIR_LIB=/usr/local/apps/qt/4.6.2-64/lib
-PATH=@NETCDF_BIN@:@ODB_API_BIN_DIR@:${PATH}
-INSTALLDIR=@CMAKE_INSTALL_PREFIX@
-METVIEW_SCRIPT=@METVIEW_SCRIPT@
-MV_MARS_ACCESS=@MARS_ACCESS@
-MARS_HOME=@MARS_HOME@
-METVIEW_DIR_DEV=@metview_BINARY_DIR@
-METVIEW_TITLE_PROD="Production @EXTRA_TITLE@"
-METVIEW_TITLE_DEV="Development @EXTRA_TITLE@"
-MV_ENVIRON=@MV_ENVIRON@
-MV_USAGE_LOG=@ENABLE_USAGE_LOG@
-MV_LOG_DIR=@LOG_DIR@
-##OS=linux
-##MAJOR_VERSION=2
-SHELL=/bin/sh
-#MAGPLUS_HOME=@MAGICS_PATH@
-GRIBAPI_DIR=@GRIB_API_PATH@
-##MV_PYTHON_COMMAND=/usr/local/bin/python
-MV_ODB1_VERSION=@MV_ODB1_VERSION@
- at ODB1_LOAD_ENV@
-##MV_ODB1_BIN=/usr/local/apps/odb/CY37R3.001/pgf90/LP64/bin
-##MV_ODB1_USE_SCRIPT=/usr/local/share/ecmwf/use/sh.odb
-METVIEW_RELEASE=@METVIEW_VERSION_STR@
-METVIEW_VERSION_TITLE="Metview @METVIEW_VERSION_STR@ @EXTRA_TITLE@ (@TODAYS_DATE@)"
-LD_LIBRARY_PATH="@METVIEW_LD_PATHS@:${LD_LIBRARY_PATH}"
-METVIEW_GUI_BUILT=@METVIEW_GUI_BUILT@
- at MV_FLEXTRA_PATH_SET@
-MV_WEATHER_ROOM_BUILT=@MV_WEATHER_ROOM_BUILT@
-unset MAGPLUS_HOME
diff --git a/scripts/compile.in b/scripts/compile.in
index 820f388..ab988fc 100755
--- a/scripts/compile.in
+++ b/scripts/compile.in
@@ -27,9 +27,9 @@
 
 set -e
 CC=@CMAKE_C_COMPILER@
-CC_FLAGS="@COMPILE_DEFINITIONS@ @METVIEW_EXTRA_DEFINITIONS@ @CXX_DEFINES@ @CMAKE_C_FLAGS@"
+CC_FLAGS="@METVIEW_INLINE_DEFINITIONS@ @CXX_DEFINES@ @CMAKE_C_FLAGS@"
 CXX=@CMAKE_CXX_COMPILER@
-CXX_FLAGS="@COMPILE_DEFINITIONS@ @METVIEW_EXTRA_DEFINITIONS@ @CMAKE_CXX_FLAGS@"
+CXX_FLAGS="@METVIEW_INLINE_DEFINITIONS@ @CMAKE_CXX_FLAGS@"
 F77=@CMAKE_Fortran_COMPILER@
 F77_FLAGS="@CMAKE_Fortran_FLAGS@"
 F90=@CMAKE_Fortran_COMPILER@
diff --git a/scripts/generate_icon_fun_help.mv b/scripts/generate_icon_fun_help.mv
index 9def8e0..7f163f8 100644
--- a/scripts/generate_icon_fun_help.mv
+++ b/scripts/generate_icon_fun_help.mv
@@ -42,7 +42,8 @@
 
 args = arguments()
 print ('running with args: ', args)
-strParamFile = args[1]
+strDictFile  = args[1]
+strParamFile = args[2]
 
 
 # Open the params file for writing
@@ -63,7 +64,7 @@ write (fileOut, strXMLHeader, newline)
 # Step 1 - read the input file in one gulp
 # ----------------------------------------
 
-listDescribes = read ('dict.txt')
+listDescribes = read (strDictFile)
 
 
 
diff --git a/scripts/metview_base b/scripts/metview_base.in
similarity index 88%
rename from scripts/metview_base
rename to scripts/metview_base.in
index 08741bb..cfe7c56 100755
--- a/scripts/metview_base
+++ b/scripts/metview_base.in
@@ -1,21 +1,60 @@
+#!/bin/ksh
 
 # **************************** LICENSE START ***********************************
 #
-# Copyright 2014 ECMWF and INPE. This software is distributed under the terms
+# Copyright 2015 ECMWF and INPE. This software is distributed under the terms
 # of the Apache License version 2.0. In applying this license, ECMWF does not
 # waive the privileges and immunities granted to it by virtue of its status as
 # an Intergovernmental Organization or submit itself to any jurisdiction.
 #
 # ***************************** LICENSE END ************************************
 
-#----------------- start of file ./scripts/metview_base
 #
-# Metview scripts are build automatically by 'make'.
+# DO NOT EDIT! SCRIPT PRODUCED BY make IN DIR ./scripts!
+#
+set -ea
+#
+# THIS FILE IS GENERATED BY cmake on @TODAYS_DATE@
+#
+WMO_SITE_NR=@SITE_WMO_CODE@
+##QT_DIR_LIB=/usr/local/apps/qt/4.6.2-64/lib
+PATH=@NETCDF_BIN@:@ODB_API_BIN_DIR@:${PATH}
+INSTALLDIR=@CMAKE_INSTALL_PREFIX@
+METVIEW_SCRIPT=@METVIEW_SCRIPT@
+MV_MARS_ACCESS=@MARS_ACCESS@
+MARS_HOME=@MARS_HOME@
+METVIEW_DIR_DEV=@CMAKE_BINARY_DIR@
+METVIEW_TITLE_PROD="Production @EXTRA_TITLE@"
+METVIEW_TITLE_DEV="Development @EXTRA_TITLE@"
+MV_ENVIRON=@MV_ENVIRON@
+MV_USAGE_LOG=@ENABLE_USAGE_LOG@
+MV_LOG_DIR=@LOG_DIR@
+##OS=linux
+##MAJOR_VERSION=2
+SHELL=/bin/sh
+#MAGPLUS_HOME=@MAGICS_PATH@
+GRIBAPI_DIR=@GRIB_API_PATH@
+##MV_PYTHON_COMMAND=/usr/local/bin/python
+MV_ODB1_VERSION=@MV_ODB1_VERSION@
+ at ODB1_LOAD_ENV@
+##MV_ODB1_BIN=/usr/local/apps/odb/CY37R3.001/pgf90/LP64/bin
+##MV_ODB1_USE_SCRIPT=/usr/local/share/ecmwf/use/sh.odb
+METVIEW_RELEASE=@METVIEW_VERSION_STR@
+METVIEW_VERSION_TITLE="Metview @METVIEW_VERSION_STR@ @EXTRA_TITLE@ (@TODAYS_DATE@)"
+LD_LIBRARY_PATH="@METVIEW_LD_PATHS@:${LD_LIBRARY_PATH}"
+METVIEW_GUI_BUILT=@METVIEW_GUI_BUILT@
+ at MV_FLEXTRA_PATH_SET@
+MV_WEATHER_ROOM_BUILT=@MV_WEATHER_ROOM_BUILT@
+MV_BUNDLE_SRC=@METVIEW_BUNDLE_SRC@
+METVIEW_QT5=@METVIEW_QT5@
+unset MAGPLUS_HOME
+
+#
+# Metview scripts are built automatically by 'make'.
 #
 # NOTE: two external files for customising, they are executed
-#       only if they exist ($MV_ENVIRON from config/CONFIG.site):
+#       only if they exist ($MV_ENVIRON):
 #   - 'metview_local.$MV_ENVIRON' (for pre-stuff i.e. to set site dep values)
-#   - 'metview_patches' (NO LONGER USED - 2014)
 #   - 'metview_stat' collects usage statistics (for ECMWF)
 #   - 'metview_local2.$MV_ENVIRON' (after flags process, e.g. batch/interactive)
 #-----------------------------------------------------------
@@ -408,12 +447,35 @@ case $METVIEW_VERSION in
 	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin}
 	METV_DEV=yes
 	MV_DEBUG_PRINT=${MV_DEBUG_PRINT:=1}
+    LD_LIBRARY_PATH="${METVIEW_DIR}/lib:${LD_LIBRARY_PATH}"
+
+    # if building as part of a bundle, and running from the build directory,
+    # then make sure we pick up the resource files from the other packages
+    # in the build directory
+    if [ "x$MV_BUNDLE_SRC" != "x" ]
+    then
+        METVIEW_EXTRA_GRIB_DEFINITION_PATH="${METVIEW_DIR_DEV}/share/grib_api/definitions:${METVIEW_EXTRA_GRIB_DEFINITION_PATH}"
+        METVIEW_EXTRA_GRIB_SAMPLES_PATH="${METVIEW_DIR_DEV}/share/grib_api/samples"
+        MAGPLUS_HOME=${MV_BUNDLE_SRC}/magics
+        BUFR_TABLES=${MV_BUNDLE_SRC}/bufrdc_tables
+        MARS_LSM_PATH=${MV_BUNDLE_SRC}/libemos/tables/interpol
+        GRIBAPI_DIR=${METVIEW_DIR_DEV}
+        #FDB_CONFIG_FILE=/tmp/cgi/git/metview-bundle/fdb/etc/Config  # has no effect
+        #FDB_CONF_FILE=/tmp/cgi/git/metview-bundle/fdb/etc/Config    # has no effect
+    fi
+
+    if [ "x at MV_BUNDLE_MAGICS_SRC@" != "x" ]
+    then
+        MAGPLUS_HOME=@MV_BUNDLE_MAGICS_SRC@
+    fi
+
+
 	;;
 
  prod)
 	METVIEW_DIR=$INSTALLDIR
 	METVIEW_DIR_SHARE=${METVIEW_DIR}/share/metview
-	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin/metview_bin}
+	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/@MV_BIN_DIR@}
 	METV_DEV=no
 	;;
 esac
@@ -552,6 +614,11 @@ if [ "x$METVIEW_EXTRA_GRIB_DEFINITION_PATH" != x -a "x$GRIBAPI_DIR" != x ] ; the
   export GRIB_DEFINITION_PATH="${METVIEW_EXTRA_GRIB_DEFINITION_PATH}:${GRIBAPI_DIR}/share/grib_api/definitions"
 fi
 
+METVIEW_EXTRA_GRIB_SAMPLES_PATH=${METVIEW_EXTRA_GRIB_SAMPLES_PATH:=""}
+if [ "x$METVIEW_EXTRA_GRIB_SAMPLES_PATH" != x -a "x$GRIBAPI_DIR" != x ] ; then
+  export GRIB_SAMPLES_PATH="${METVIEW_EXTRA_GRIB_SAMPLES_PATH}:${GRIBAPI_DIR}/share/grib_api/samples"
+fi
+
 # =============================================================
 # extra stuff (e.g. local DataAccess objects)
 #
@@ -602,7 +669,12 @@ then
 	METVIEW_GRAPHICS_SYSTEM="raster"
 fi
 
-METVIEW_QT_APPLICATION_FLAGS="-style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss -graphicssystem $METVIEW_GRAPHICS_SYSTEM"
+if [ "$METVIEW_QT5" = "true" ]
+then
+ METVIEW_QT_APPLICATION_FLAGS="-style fusion -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss -graphicssystem $METVIEW_GRAPHICS_SYSTEM"
+else
+ METVIEW_QT_APPLICATION_FLAGS="-style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss -graphicssystem $METVIEW_GRAPHICS_SYSTEM"
+fi
 
 # =============================================================
 # Add metview bin to path
@@ -720,6 +792,7 @@ then
       METVIEW_TIFF_VIEWER=${METVIEW_TIFF_VIEWER:=open}
       METVIEW_RASTER_EDITOR=${METVIEW_RASTER_EDITOR:=open}
       METVIEW_GRAPHICS_SYSTEM=${METVIEW_GRAPHICS_SYSTEM:="native"}
+      MV_VAPOR_BIN=${MV_VAPOR_BIN:="/Applications/VAPOR/VAPOR.app/Contents/MacOS/"}
     else
       METVIEW_PS_VIEWER=${METVIEW_PS_VIEWER:=gv}
       METVIEW_PDF_VIEWER=${METVIEW_PDF_VIEWER:=xpdf}
diff --git a/share/metview/app-defaults/CMakeLists.txt b/share/metview/app-defaults/CMakeLists.txt
index a925f81..a853c19 100644
--- a/share/metview/app-defaults/CMakeLists.txt
+++ b/share/metview/app-defaults/CMakeLists.txt
@@ -29,14 +29,14 @@ execute_process(COMMAND           date +%d-%B-%Y
                 OUTPUT_VARIABLE   THIS_VERBOSE_DATE
                 OUTPUT_STRIP_TRAILING_WHITESPACE)
 
-configure_file(MvVersion.in         MvVersion @ONLY)
-configure_file(MvVersionDetails.in  MvVersionDetails @ONLY)
+configure_file(MvVersion.in         ${CMAKE_BINARY_DIR}/share/metview/app-defaults/MvVersion @ONLY)
+configure_file(MvVersionDetails.in  ${CMAKE_BINARY_DIR}/share/metview/app-defaults/MvVersionDetails @ONLY)
 
 
 foreach( f ${files} )
 
     # copy to the build 'bin' directory
-    configure_file(${f} . COPYONLY)
+    configure_file(${f} ${CMAKE_BINARY_DIR}/share/metview/app-defaults/ COPYONLY)
 
 endforeach()
 
@@ -44,7 +44,7 @@ endforeach()
 foreach( f ${files} MvVersion MvVersionDetails)
 
     # ensure file is installed at install time
-    install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${f}
+    install( FILES ${CMAKE_BINARY_DIR}/share/metview/app-defaults/${f}
              DESTINATION share/metview/app-defaults
              PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
 
@@ -62,10 +62,10 @@ set(dirs CommonMacroFuncs Drawers Templates)
 
 foreach( dir ${dirs})
 
-    execute_process(COMMAND ${CMAKE_COMMAND} -E remove ${CMAKE_CURRENT_BINARY_DIR}/${dir})
+    execute_process(COMMAND ${CMAKE_COMMAND} -E remove ${CMAKE_BINARY_DIR}/share/metview/app-defaults/${dir})
 
     execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_CURRENT_SOURCE_DIR}/${dir}
-                                                               ${CMAKE_CURRENT_BINARY_DIR}/${dir}
+                                                               ${CMAKE_BINARY_DIR}/share/metview/app-defaults/${dir}
                     RESULT_VARIABLE res
                     OUTPUT_VARIABLE outv
                     ERROR_VARIABLE  errv)
diff --git a/share/metview/etc/CMakeLists.txt b/share/metview/etc/CMakeLists.txt
index 02edfb6..aaf4cb9 100644
--- a/share/metview/etc/CMakeLists.txt
+++ b/share/metview/etc/CMakeLists.txt
@@ -147,16 +147,17 @@ set(extra_install_files macro_built_in_functions)
 
 ADD_CUSTOM_COMMAND(
     OUTPUT  ${CMAKE_BINARY_DIR}/share/metview/etc/macro_built_in_functions.txt
-    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_SOURCE_DIR}/scripts/generate_list_of_macro_functions.mv macro_built_in_functions.txt
+    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_CURRENT_SOURCE_DIR}/../../../scripts/generate_list_of_macro_functions.mv ${CMAKE_BINARY_DIR}/share/metview/etc/macro_built_in_functions.txt
     DEPENDS ${FULL_STARTUP_SCRIPT_PATH} ${metview_core_targets}
 )
 
 #ADD_CUSTOM_TARGET(macro_built_in_functions ALL DEPENDS ${CMAKE_BINARY_DIR}/share/metview/etc/macro_built_in_functions.txt)
 
+set (dict_file "${CMAKE_BINARY_DIR}/share/metview/etc/dict.txt")
 
 ADD_CUSTOM_COMMAND(
-    OUTPUT  ${CMAKE_BINARY_DIR}/share/metview/etc/dict.txt
-    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_SOURCE_DIR}/scripts/generate_dictionary.mv dict.txt
+    OUTPUT  ${dict_file}
+    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_CURRENT_SOURCE_DIR}/../../../scripts/generate_dictionary.mv ${dict_file}
     DEPENDS ${FULL_STARTUP_SCRIPT_PATH} ${metview_core_targets}
 )
 
@@ -169,8 +170,8 @@ ADD_CUSTOM_COMMAND(
 
 ADD_CUSTOM_COMMAND(
     OUTPUT  ${CMAKE_BINARY_DIR}/share/metview/etc/macro_icon_function_help.xml
-    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_SOURCE_DIR}/scripts/generate_icon_fun_help.mv macro_icon_function_help.xml
-    DEPENDS ${FULL_STARTUP_SCRIPT_PATH} dict.txt ${metview_core_targets}
+    COMMAND ${FULL_STARTUP_SCRIPT_PATH} -b ${CMAKE_CURRENT_SOURCE_DIR}/../../../scripts/generate_icon_fun_help.mv ${dict_file} ${CMAKE_BINARY_DIR}/share/metview/etc/macro_icon_function_help.xml
+    DEPENDS ${FULL_STARTUP_SCRIPT_PATH} ${dict_file} ${metview_core_targets}
 )
 
 ADD_CUSTOM_TARGET(macro_built_in_functions ALL DEPENDS ${CMAKE_BINARY_DIR}/share/metview/etc/macro_built_in_functions.txt
@@ -196,13 +197,13 @@ macro(generate_def_file
       generated_file source_file verb_extension)
 
     add_custom_command(
-        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${generated_file}
-	    COMMAND cat ${CMAKE_CURRENT_SOURCE_DIR}/${source_file} | sed 's/RETRIEVE[^D]/RETRIEVE${verb_extension} /g' | sed 's/READ /READ${verb_extension} /g' > ${CMAKE_CURRENT_BINARY_DIR}/${generated_file}
+        OUTPUT ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/${generated_file}
+	    COMMAND cat ${CMAKE_CURRENT_SOURCE_DIR}/${source_file} | sed 's/RETRIEVE[^D]/RETRIEVE${verb_extension} /g' | sed 's/READ /READ${verb_extension} /g' > ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/${generated_file}
         DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${source_file})
-    add_custom_target(${generated_file} DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${generated_file})
+    add_custom_target(${generated_file} DEPENDS ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/${generated_file})
 
     list(APPEND generated_files ${generated_file})
-    list(APPEND dependencies  ${CMAKE_CURRENT_BINARY_DIR}/${generated_file})
+    list(APPEND dependencies  ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/${generated_file})
 
 endmacro(generate_def_file)
 
@@ -226,7 +227,7 @@ endif()
 
 
 # Set up ConfigDef to have the network proxy settings given to CMake
-configure_file(ConfigDef.in ${CMAKE_CURRENT_BINARY_DIR}/ConfigDef @ONLY)
+configure_file(ConfigDef.in ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ConfigDef @ONLY)
 
 list(APPEND generated_files ConfigDef)
 
@@ -235,7 +236,7 @@ list(APPEND generated_files ConfigDef)
 # at configure time we can just copy most of the files across to the build directory
 foreach( f ${files} )
     # copy to the build directory
-    configure_file(${f} ${CMAKE_BINARY_DIR}/share/metview/etc/ COPYONLY)
+    configure_file(${f} ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ COPYONLY)
 endforeach()
 
 
@@ -243,7 +244,7 @@ endforeach()
 # add all these to the list of files to be installed
 foreach( f ${files} ${generated_files})
     # ensure file is installed at install time
-    install( FILES ${CMAKE_CURRENT_BINARY_DIR}/${f}  
+    install( FILES ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/${f}  
              DESTINATION share/metview/etc
              PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
 endforeach()
@@ -255,17 +256,22 @@ endforeach()
 # add "cat <<@ " as the first line, and "@" as the last
 #message(STATUS "ModuleObjectSpecFiles: ${ModuleObjectSpecFiles}")
 
-set(ObjectListAllComponents Services ObjectList uPlotTable ${ModuleObjectSpecFiles})
+set(ObjectListAllComponents
+       ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/Services
+       ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectList
+       ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/uPlotTable
+       ${ModuleObjectSpecFiles})
+
 
 add_custom_command(
-    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ObjectListAll
-	COMMAND cat ${MARS_ACCESS} > ObjectListAll.temp \; echo 'cat <<\@'   >> ObjectListAll.temp \; cat ${ObjectListAllComponents} >> ObjectListAll.temp \; echo '\@'          >> ObjectListAll.temp \; grep -v "^#" ObjectListAll.temp > ObjectListAll \; rm -f ObjectListAll.temp
+    OUTPUT ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectListAll
+	COMMAND cat ${CMAKE_CURRENT_SOURCE_DIR}/${MARS_ACCESS} > ObjectListAll.temp \; echo 'cat <<\@'   >> ObjectListAll.temp \; cat ${ObjectListAllComponents} >> ObjectListAll.temp \; echo '\@'          >> ObjectListAll.temp \; grep -v "^#" ObjectListAll.temp > ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectListAll \; rm -f ObjectListAll.temp
 #	COMMAND cat $(MARS_ACCESS) > ObjectListAll.temp \; echo "cat <<@ "   >> ObjectListAll.temp \; cat Services ObjectList uPlotTable >> ObjectListAll.temp \; cat `ls  ObjectSpec.* | grep -v \~`  >> ObjectListAll.temp \; echo "@"          >> ObjectListAll.temp \; grep -v '^#' ObjectListAll.temp > ObjectListAll
     DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/ObjectList ${ObjectListAllComponents})
-add_custom_target(ObjectListAll DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ObjectListAll)
+add_custom_target(ObjectListAll DEPENDS ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectListAll)
 
 
-install( FILES ${CMAKE_CURRENT_BINARY_DIR}/ObjectListAll
+install( FILES ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectListAll
          DESTINATION share/metview/etc
          PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
 
@@ -274,7 +280,7 @@ install( FILES ${CMAKE_CURRENT_BINARY_DIR}/ObjectListAll
 add_custom_command( 
     OUTPUT  defs_created.txt
     COMMAND touch defs_created.txt
-    DEPENDS ${dependencies} ${CMAKE_CURRENT_BINARY_DIR}/ObjectListAll
+    DEPENDS ${dependencies} ${CMAKE_BINARY_DIR}/share/${PROJECT_NAME}/etc/ObjectListAll
     )
 
 add_custom_target( all_defs ALL DEPENDS defs_created.txt )
diff --git a/share/metview/etc/EPSOutputDef b/share/metview/etc/EPSOutputDef
index 5633d7a..4c7ee57 100644
--- a/share/metview/etc/EPSOutputDef
+++ b/share/metview/etc/EPSOutputDef
@@ -64,8 +64,14 @@ EPSOUTPUT; Magics; Automatically generated
 
 	OUTPUT_PS_COLOUR_MODEL
 	{
-		@
+		RGB; RGB
+        CMYK; CMYK
+        MONOCHROME; MONOCHROME
+        GRAY; GRAY
+        CMYK_MONOCHROME; CMYK_MONOCHROME
+        CMYK_GRAY; CMYK_GRAY
 	} = RGB
+
 	OUTPUT_PS_SCALE
 	{
 		*
diff --git a/share/metview/etc/MCOASTDef b/share/metview/etc/MCOASTDef
index 30ffa86..80db4b4 100644
--- a/share/metview/etc/MCOASTDef
+++ b/share/metview/etc/MCOASTDef
@@ -377,12 +377,32 @@ MCOAST; Magics; Automatically generated
 	} = ON
 
 	MAP_LABEL_QUALITY
+	[ visible = false ]
 	{
 		HIGH;HIGH
 		MEDIUM;MEDIUM
 		LOW;LOW
 	} = MEDIUM
 
+	MAP_LABEL_FONT
+	{
+		ARIAL; ARIAL
+		COURIER; COURIER
+		HELVETICA; HELVETICA
+		TIMES; TIMES
+		SERIF; SERIF
+		SANSSERIF; SANSSERIF
+		SYMBOL; SYMBOL
+	} = SANSSERIF
+
+	MAP_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
 	MAP_LABEL_COLOUR [ help = help_colour,interface = colour ]
 	{ 
 		&PARAMSHARE&COLOUR
@@ -393,6 +413,12 @@ MCOAST; Magics; Automatically generated
 		*
 	} = 0.25
 
+	MAP_LABEL_BLANKING
+	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
 	MAP_LABEL_LATITUDE_FREQUENCY
 	{
 		*
diff --git a/share/metview/etc/MCOASTRules b/share/metview/etc/MCOASTRules
index 2a9a492..280b6bf 100644
--- a/share/metview/etc/MCOASTRules
+++ b/share/metview/etc/MCOASTRules
@@ -44,9 +44,12 @@
 	%unset MAP_LABEL_TOP
 	%unset MAP_LABEL_LATITUDE_FREQUENCY
 	%unset MAP_LABEL_QUALITY
+	%unset MAP_LABEL_FONT
+	%unset MAP_LABEL_FONT_STYLE
 	%unset MAP_LABEL_COLOUR
 	%unset MAP_LABEL_LONGITUDE_FREQUENCY
 	%unset MAP_LABEL_HEIGHT
+	%unset MAP_LABEL_BLANKING
 	%unset MAP_LABEL_BOTTOM
 	%unset MAP_LABEL_LEFT
 	%unset MAP_LABEL_RIGHT
diff --git a/share/metview/etc/MSYMBRules b/share/metview/etc/MSYMBRules
index 7203b0e..167afd5 100644
--- a/share/metview/etc/MSYMBRules
+++ b/share/metview/etc/MSYMBRules
@@ -18,7 +18,7 @@
 %if LEGEND <> ON %or SYMBOL_TABLE_MODE <> OFF %then
 	%unset LEGEND_USER_TEXT
 
-%if SYMBOL_TABLE_MODE <> OFF %or SYMBOL_TYPE <> NUMBER %and SYMBOL_TYPE <> TEXT %then
+%if SYMBOL_TYPE <> NUMBER %and SYMBOL_TYPE <> TEXT %then
 	%unset SYMBOL_TEXT_BLANKING
 
 %if SYMBOL_ADVANCED_TABLE_SELECTION_TYPE <> INTERVAL %or SYMBOL_TABLE_MODE <> ADVANCED %then
diff --git a/share/metview/etc/PDFOutputDef b/share/metview/etc/PDFOutputDef
index 9b26dc1..798b0ac 100644
--- a/share/metview/etc/PDFOutputDef
+++ b/share/metview/etc/PDFOutputDef
@@ -68,11 +68,13 @@ PDFOUTPUT; Magics; Automatically generated
 
 	OUTPUT_CAIRO_TRANSPARENT_BACKGROUND
 	{
-		@
+		ON;  ON
+		OFF; OFF
 	} = OFF
 	OUTPUT_CAIRO_ANTIALIAS
 	{
-		@
+		ON;  ON
+		OFF; OFF
 	} = ON
 
     CLASS [visible=false]
diff --git a/share/metview/etc/PNGOutputDef b/share/metview/etc/PNGOutputDef
index 54d7470..7eab30a 100644
--- a/share/metview/etc/PNGOutputDef
+++ b/share/metview/etc/PNGOutputDef
@@ -68,11 +68,13 @@ PNGOUTPUT; Magics; Automatically generated
 
 	OUTPUT_CAIRO_TRANSPARENT_BACKGROUND
 	{
-		@
+		ON;  ON
+		OFF; OFF
 	} = OFF
 	OUTPUT_CAIRO_ANTIALIAS
 	{
-		@
+		ON;  ON
+		OFF; OFF
 	} = ON
 
     CLASS [visible=false]
diff --git a/share/metview/etc/PSOutputDef b/share/metview/etc/PSOutputDef
index 12e242e..47b3d89 100644
--- a/share/metview/etc/PSOutputDef
+++ b/share/metview/etc/PSOutputDef
@@ -64,8 +64,14 @@ PSOUTPUT; Magics; Automatically generated
 
 	OUTPUT_PS_COLOUR_MODEL
 	{
-		@
+		RGB; RGB
+        CMYK; CMYK
+        MONOCHROME; MONOCHROME
+        GRAY; GRAY
+        CMYK_MONOCHROME; CMYK_MONOCHROME
+        CMYK_GRAY; CMYK_GRAY
 	} = RGB
+
 	OUTPUT_PS_SCALE
 	{
 		*
diff --git a/share/metview/etc/ecmwf.def b/share/metview/etc/ecmwf.def
index 3ebf2cc..b813f28 100755
--- a/share/metview/etc/ecmwf.def
+++ b/share/metview/etc/ecmwf.def
@@ -107,6 +107,7 @@ CONVECTIVE CLOUD COVER                        ;  CCC   ;  185
 CONVECTIVE INHIBITION                         ;  CIN   ;  228001
 CONVECTIVE PRECIPITATION                      ;  CP    ;  143
 CONVECTIVE SNOW-FALL                          ;  CSF   ;  239
+CONVECTIVE RAIN RATE                          ;  CRR   ;  228218
 CONVECTIVE TENDENCY OF MERIDIONAL WIND        ;  CTMW  ;  223
 CONVECTIVE TENDENCY OF ZONAL WIND             ;  CTZW  ;  222
 DEEP SOIL TEMPERATURE                         ;  DST   ;  170
@@ -149,10 +150,10 @@ HUNDRED METRE U WIND COMPONENT                ;  100U  ;  U100 ; 228246  ;  246.
 HUNDRED METRE V WIND COMPONENT                ;  100V  ;  V100 ; 228247  ;  247.228
 HUNDRED METRE WIND SPEED                      ;  100SI ;  228249  ;  249.228
 ICE AGE                                       ;  ICE   ;  250
-ICE SURFACE TEMPERATURE LAYER 1               ;  ISTL1 ;  035
-ICE SURFACE TEMPERATURE LAYER 2               ;  ISTL2 ;  036
-ICE SURFACE TEMPERATURE LAYER 3               ;  ISTL3 ;  037
-ICE SURFACE TEMPERATURE LAYER 4               ;  ISTL4 ;  038
+ICE SURFACE TEMPERATURE LAYER 1               ;  IST1  ; ISTL1 ;  035
+ICE SURFACE TEMPERATURE LAYER 2               ;  IST2  ; ISTL2 ;  036
+ICE SURFACE TEMPERATURE LAYER 3               ;  IST3  ; ISTL3 ;  037
+ICE SURFACE TEMPERATURE LAYER 4               ;  IST4  ; ISTL4 ;  038
 INSTANT MOISTURE FLUX                         ;  IE    ;  232
 INSTANTANEOUS EASTWARD TURBULENT SURFACE STRESS   ;  IEWS  ; 229
 INSTANTANEOUS NORTHWARD TURBULENT SURFACE STRESS   ;  INSS  ; 230
@@ -171,6 +172,7 @@ LAND SEA MASK                                 ;  LSM   ;  172
 LARGE SCALE PRECIPITATION                     ;  LSP   ;  142
 LARGE SCALE PRECIPITATION FRACTION            ;  LSPF  ;  050
 LARGE SCALE SNOW-FALL                         ;  LSF   ;  240
+LARGE SCALE SNOWFALL RATE WATER EQUIVALENT    ;  LSSFR ;  228221
 LEAF AREA INDEX LOW VEGETATION                ;  LAILV ;   66
 LEAF AREA INDEX HIGH VEGETATION               ;  LAIHV ;   67
 LN SURFACE PRESSURE                           ;  LNSP  ;  152
@@ -181,10 +183,13 @@ LOW VEGETATION COVER                          ;  CVL   ;  027
 MAGNITUDE OF SURFACE STRESS                   ;  MAGSS ;  048
 MAXIMUM TEMPERATURE AT 2M                     ;  MX2T  ;  201
 MAXIMUM TEMPERATURE AT 2M ANOMALY             ;  MX2TA  ;  201.171
+MAXIMUM TEMPERATURE AT 2M INDEX               ;  MX2TI ;  201.132
 MAXIMUM TEMPERATURE AT 2M IN THE LAST 6 HOURS ANOMALY  ;  MX2T6A  ;  121.171
 MAXIMUM TEMPERATURE AT 2M IN THE LAST 6 HOURS  ;  MX2T6 ;  121.128
 MAXIMUM TEMPERATURE AT 2M IN THE LAST 3 HOURS  ;  MX2T3 ;  228026 ; 026.228
 MAXIMUM TEMPERATURE AT 2M IN THE LAST 24 HOURS ;  MX2T24 ;  51
+MAXIMUM TOTAL PRECIPITATION RATE IN THE LAST 3 HOURS  ; MXTPR3  ; 228222
+MAXIMUM TOTAL PRECIPITATION RATE IN THE LAST 6 HOURS  ; MXTPR6  ; 228224
 MAXIMUM INDIVIDUAL WAVE HEIGHT                           ;  HMAX  ;  218
 MAXIMUM OF SIGNIFICANT WAVE HEIGHT            ;  MAXSWH ; 200
 MEAN 2 METRE TEMPERATURE PAST 24 HOURS        ;  MEAN2T24;  055
@@ -206,6 +211,12 @@ MEAN SQUARE SLOPE OF WAVES                    ;  MSQS  ;  244
 MEAN VERTICAL GRADIENT OF REFRACTIVITY INSIDE TRAPPING LAYER ; DNDZA ;  228016  ; 016.228
 MEAN VERTICAL VELOCITY                        ;  MVV   ;  232
 MEAN WAVE DIRECTION                           ;  MWD   ;  230
+MEAN WAVE DIRECTION OF FIRST SWELL PARTITION     ;  MWD1 ;    122 
+MEAN WAVE DIRECTION OF SECOND SWELL PARTITION    ;  MWD2 ;    125 
+MEAN WAVE DIRECTION OF SWELL THIRD PARTITION     ;  MWD3 ;    128 
+MEAN WAVE PERIOD OF FIRST SWELL PARTITION        ;  MWP1 ;    123 
+MEAN WAVE PERIOD OF SECOND SWELL PARTITION       ;  MWP2 ;    126 
+MEAN WAVE PERIOD OF SWELL THIRD PARTITION        ;  MWP3 ;    129 
 MEAN WAVE PERIOD                              ;  MWP   ;  232
 MEAN WAVE PERIOD PROBABILITY                  ;  MWPP  ;  232
 MEAN WAVE PERIOD BASED ON FIRST MOMENT                 ; MP1   ; 220
@@ -218,12 +229,19 @@ MEAN WIND DIRECTION                           ;  MDWI  ;  242
 MEDIUM CLOUD COVER                            ;  MCC   ;  187
 MINIMUM TEMPERATURE AT 2M                     ;  MN2T  ;  202
 MINIMUM TEMPERATURE AT 2M ANOMALY             ;  MN2TA  ;  202.171
+MINIMUM TEMPERATURE AT 2M INDEX               ;  MN2TI ;  202.132 
 MINIMUM TEMPERATURE AT 2M IN THE LAST 6 HOURS ANOMALY  ;  MN2T6A  ;  122.171
 MINIMUM TEMPERATURE AT 2M IN THE LAST 6 HOURS  ;  MN2T6 ;  122.128
 MINIMUM TEMPERATURE AT 2M IN THE LAST 3 HOURS  ;  MN2T3 ;  228027 ; 027.228
 MINIMUM TEMPERATURE AT 2M IN THE LAST 24 HOURS ;  MN2T24 ;  52
+MINIMUM TOTAL PRECIPITATION RATE IN THE LAST 3 HOURS  ; MNTPR3  ; 228223
+MINIMUM TOTAL PRECIPITATION RATE IN THE LAST 6 HOURS  ; MNTPR6  ; 228225
 MINIMUM VERTICAL GRADIENT OF REFRACTIVITY INSIDE TRAPPING LAYER ; DNDZN ; 228015 ; 015.228
+MODEL BATHYMETRY                              ;  WMB   ;  219
 MONTGOMERY POTENTIAL                          ;  MONT  ;  053
+NORMALIZED ENERGY FLUX INTO WAVES             ;  PHIAW ;  211
+NORMALIZED ENERGY FLUX INTO OCEAN             ;  PHIOC ;  212
+NORMALIZED STRESS INTO OCEAN                  ;  TAUOC ;  214
 NORTHWARD GRAVITY WAVE SURFACE STRESS         ;  MGWS  ;  196
 NORTHWARD TURBULENT SURFACE STRESS            ;  NSSS  ;  181
 N-S OROGRAPHIC VARIANCE                       ;  NSOV  ;  191
@@ -253,6 +271,7 @@ CLIMATOLOGICAL PROBABILITY OF A TROPICAL DEPRESION  ; CPTD  ; 94.131
 PROBABILITY ANOMALY OF A TROPICAL STORM             ; PATS  ; 95.131
 PROBABILITY ANOMALY OF A HURRICANE                  ; PAH   ; 96.131
 PROBABILITY ANOMALY OF A TROPICAL DEPRESION         ; PATD  ; 97.131
+POTENTIAL EVAPORATION                         ;  PEV   ;  228251
 POTENTIAL TEMPERATURE                         ;  PT    ;  003
 POTENTIAL TEMPERATURE INCREMENT               ;  PTI   ;  178
 POTENTIAL TEMPERATURE ANALYSIS ERROR          ;  PTAE  ;  179
@@ -260,6 +279,7 @@ POTENTIAL TEMPERATURE BACKGROUND ERROR        ;  PTBE  ;  182
 POTENTIAL VORTICITY                           ;  PV    ;  060
 PRECIP. ANALYSIS WEIGHTS                      ;  PAW   ;  204
 PRECIPITABLE WATER CONTENT                    ;  PWC   ;  137
+PRECIPITATION TYPE                            ;  PTYPE ; 260015
 PRESSURE                                      ;  PRES  ;  054
 RELATIVE HUMIDITY                             ;  R     ;  157
 RUNOFF                                        ;  RO    ;  205
@@ -276,6 +296,9 @@ SIGNIFICANT HEIGHT TOTAL SWELL              ;  SHPS ; SHTS  ;  237
 SIGNIFICANT HEIGHT WIND WAVES                 ;  SHWW  ;  234
 SIGNIFICANT WAVE HEIGHT                       ;  SWH   ;  229
 SIGNIFICANT WAVE HEIGHT PROBABILITY           ;  SWHP  ;  229
+SIGNIFICANT WAVE HEIGHT OF FIRST SWELL PARTITION ;  SWH1 ;    121
+SIGNIFICANT WAVE HEIGHT OF SECOND SWELL PARTITION;  SWH2 ;    124
+SIGNIFICANT WAVE HEIGHT OF SWELL THIRD PARTITION ;  SWH3 ;    127
 SKIN RESERVOIR CONTENT                        ;  SRC   ;  198
 SKIN TEMPERATURE                              ;  SKT   ;  235
 SLOPE OF SUBGRID OROGRAPHY                    ;  SLOR  ;  163
@@ -286,6 +309,7 @@ SNOW DEPTH                                    ;  SD    ;  141
 SNOW DEPTH ANOMALY                            ;  SDA   ;  171141  ; 141.171
 SNOW EVAPORATION                              ;  ES    ;  044
 SNOWFALL                                      ;  SF    ;  144
+SNOWFALL INDEX                                ;  SFI   ;  144.132
 SNOWFALL PROBABILITY                          ;  SFP   ;  144
 SNOWFALL ANOMALOUS RATE OF ACCUMULATION       ;  SFARA ;  144.173
 SNOWMELT                                      ;  SMLT  ;  045
@@ -345,6 +369,8 @@ TEN METRE WINDSPEED IRRESP OF DIR             ;  10SI  ;  207
 TEN METRE WINDSPEED ONLY                      ;  10WS  ;  246
 TEN METRE WIND DIRECTION                      ;  DWI   ;  249
 TENDENCY SURFACE PRESSURE                     ;  TSP   ;  158
+# THICKNES is derived parameter in ProdGen - thicknes of the layer 1000/500 or 850/500 . Not available in MARS
+THICKNES                                      ;  THK ; 928
 TOP NET RADIATION                             ;  TNR   ;  150
 TOP NET SOLAR RADIATION CLEAR SKY             ;  TSRC  ;  208
 TOP SOLAR RAD. UPWARD CLEAR SKY               ;  TSUC  ;  210
@@ -425,10 +451,10 @@ VERTICALLY INTEGRATED MERIDIONAL VOLUME TRANSPORT  ;  MTR   ;  168
 VERTICALLY INTEGRATED MOISTURE DIVERGENCE     ;  VIMD  ;  213
 VERTICALLY INTEGRATED ZONAL HEAT TRANSPORT         ;  ZHT   ;  169
 VERTICALLY INTEGRATED ZONAL VOLUME TRANSPORT       ;  ZTR   ;  167
-VOLUMETRIC SOIL WATER LAYER 1                 ;  SWVL1 ;  039
-VOLUMETRIC SOIL WATER LAYER 2                 ;  SWVL2 ;  040
-VOLUMETRIC SOIL WATER LAYER 3                 ;  SWVL3 ;  041
-VOLUMETRIC SOIL WATER LAYER 4                 ;  SWVL4 ;  042
+VOLUMETRIC SOIL WATER LAYER 1                 ;  SWV1  ; SWVL1 ;  039
+VOLUMETRIC SOIL WATER LAYER 2                 ;  SWV2  ; SWVL2 ;  040
+VOLUMETRIC SOIL WATER LAYER 3                 ;  SWV3  ; SWVL3 ;  041
+VOLUMETRIC SOIL WATER LAYER 4                 ;  SWV4  ; SWVL4 ;  042
 VORTICITY                                     ;  VO    ;  138
 WAVE HEIGHT                                   ;  WH    ;  229
 WAVE SPECTRAL DIRECTIONAL WIDTH               ;  WDW   ; 222
@@ -436,11 +462,13 @@ WAVE SPECTRAL DIRECTIONAL WIDTH FOR SWELL     ;  DWPS  ; 228
 WAVE SPECTRAL DIRECTIONAL WIDTH FOR WIND WAVES;  DWWW  ; 225
 WAVE SPECTRAL KURTOSIS                        ;  WSK   ; 252
 WAVE SPECTRAL PEAKEDNESS                      ;  WSP   ; 254
+WAVE SPECTRAL SKEWNESS                        ;  WSS   ; 207 
 WILTING POINT                                 ;  WILT  ; 228171  ; 171.228
 WIND GUST AT 10 METRES                        ;  10FG  ;  049
 WIND GUST AT 10 METRES INDEX                  ;  10FGI ;  049
 WIND GUST AT 10 METRES IN THE LAST 6 HOURS     ;  10FG6 ;  123.128
 WIND GUST AT 10 METRES IN THE LAST 3 HOURS     ;  10FG3 ;  228028 ; 028.228
+INSTANTANEOUS 10 METRE WIND GUST              ;  I10FG  ;  228029
 WIND SPEED                                    ;  WS    ;   10
 ZERO DEGREE LEVEL                             ;  DEG0L ; 228024  ; 24.228
 
@@ -1183,13 +1211,14 @@ SATELLITE = (VSS/SSBT/SSMI/SSMIS/QSCAT/REO3/WSAT/VASS/ATMS)
 
 # Type SLNS (NSD)
 
-SINGLE LEVEL UPPER AIR NOT SATELLITE ; SLNS = (141/142/143/144/145)
+SINGLE LEVEL UPPER AIR NOT SATELLITE ; SLNS = (141/142/143/144/145/146)
 
 	CODAR ;  COD ; 141
 	AIREP ;  AIR ; 142
 	COLBA ;  COL ; 143
 	AMDAR ;  AM  ; 144
 	ACARS ;  AC  ; 145
+	E-AMDAR ;  EAM  ; 146
 
 # Type SLS (NSD)
 
diff --git a/share/metview/etc/obsgroups.def b/share/metview/etc/obsgroups.def
index 8e4db31..4a7004c 100755
--- a/share/metview/etc/obsgroups.def
+++ b/share/metview/etc/obsgroups.def
@@ -55,4 +55,5 @@
 57 ; SSMI 1DVAR TCWV Cloudy-Sky ; SSMI_1D
 58 ; MWHS2 All-sky ; MWHS2_AS
 59 ; SSMT2 ; SSMT2
+60 ; SMAP ; SMAP
 99 ; TEST ; TEST
diff --git a/share/metview/etc/reportypes.def b/share/metview/etc/reportypes.def
index 75cf328..4e85ccb 100755
--- a/share/metview/etc/reportypes.def
+++ b/share/metview/etc/reportypes.def
@@ -59,6 +59,7 @@ METEOSAT 8 GEOS Allsky Radiances ; 4018
 COMS-1 GEOS Radiances ; 4019
 METEOSAT 4 GEOS Radiances ; 4020
 METEOSAT 6 GEOS Radiances ; 4021
+Himawari 8 GEOS radiances ; 4022
 ERS 2 GOME O3 ; 5001
 METEOSAT 8 SEVIRI O3 ; 5002
 METEOSAT 9 SEVIRI O3 ; 5003
@@ -195,6 +196,10 @@ Leo-Geo AMV ; 8047
 Dual-Metop AMVs ; 8048
 INSAT-3D AMVs ; 8049
 NPP AMV ; 8050
+GOES 6 AMV subtype 82 ; 8051
+GOES 6 AMV subtype 83 ; 8052
+Himawari 8 AMV ; 8053
+FY-2G AMVs ; 8054
 Old ERS 1 Scatterometer ; 9001
 New ERS 1 Scatterometer ; 9002
 ERS 2 Scatterometer ; 9003
@@ -212,12 +217,19 @@ DMSP 11 SSMI All-sky ; 10005
 DMSP 13 SSMI All-sky ; 10006
 DMSP 14 SSMI All-sky ; 10007
 DMSP 15 SSMI All-sky ; 10008
+DMSP 8 SSMI CMSAF All-sky ; 10009
+DMSP 10 SSMI CMSAF All-sky ; 10010
+DMSP 11 SSMI CMSAF All-sky ; 10011
+DMSP 13 SSMI CMSAF All-sky ; 10012
+DMSP 14 SSMI CMSAF All-sky ; 10013
+DMSP 15 SSMI CMSAF All-sky ; 10014
 METOP-A IASI Radiances ; 11001
 METOP-B IASI Radiances ; 11002
 AQUA AIRS Radiances ; 12001
 DMSP 16 SSMIS Radiances All-sky ; 13001
 DMSP 17 SSMIS Radiances All-sky ; 13002
 DMSP 18 SSMIS Radiances All-sky ; 13003
+DMSP 19 SSMIS Radiances All-sky ; 13004
 TRMM TMI Radiances All-sky ; 14001
 AQUA AMSRE Radiances All-sky ; 15001
 Automatic Land SYNOP ; 16001
@@ -298,6 +310,8 @@ SFERICS lightning observations ; 16079
 ATDNET lightning observations ; 16080
 Upper air WISDOM ; 16081
 WIGOS AMDAR ; 16082
+BUFR MOORED BUOYS ; 16083
+BUFR DRIFTING BUOYS ; 16084
 SMOS ; 18001
 CORIOLIS WINDSAT All-sky ; 19001
 DMSP 8 SSMI ; 20001
@@ -320,6 +334,7 @@ TRMM TMI Radiances ; 23001
 DMSP 16 SSMIS Radiances ; 24001
 DMSP 17 SSMIS Radiances ; 24002
 DMSP 18 SSMIS Radiances ; 24003
+DMSP 19 SSMIS Radiances ; 24004
 Ground-Based Radar ; 25001
 FY-3A MWHS Radiances ; 26001
 FY-3B MWHS Radiances ; 26002
@@ -442,6 +457,7 @@ DMSP 11 SSMT2 Radiances ; 58001
 DMSP 12 SSMT2 Radiances ; 58002
 DMSP 14 SSMT2 Radiances ; 58003
 DMSP 15 SSMT2 Radiances ; 58004
+SMAP ; 59001
 TEST REPORTYPE 1 ; 98001
 TEST REPORTYPE 2 ; 98002
 TEST REPORTYPE 3 ; 98003
diff --git a/share/metview/etc/rt_by_obsgroup.chk b/share/metview/etc/rt_by_obsgroup.chk
index db0df06..42a6940 100755
--- a/share/metview/etc/rt_by_obsgroup.chk
+++ b/share/metview/etc/rt_by_obsgroup.chk
@@ -11,7 +11,7 @@
 	%set REPORTYPE =  3001/3002/3003/3004
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  GEOS ) %and %not REPORTYPE %then
-	%set REPORTYPE =  4002/4003/4004/4005/4006/4007/4008/4009/4010/4011/4012/4013/4014/4015/4016/4017/4018/4019/4020/4021
+	%set REPORTYPE =  4002/4003/4004/4005/4006/4007/4008/4009/4010/4011/4012/4013/4014/4015/4016/4017/4018/4019/4020/4021/4022
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  RESAT ) %and %not REPORTYPE %then
 	%set REPORTYPE =  5001/5002/5003/5004/5005/5006/5007/5008/5009/5010/5011/5012/5013/5014/5015/5016/5017/5018/5019/5020/5021/5022/5023/5024/5025/5026/5027/5028/5029/5030/5031/5032/5033/5034/5035/5036/5037/5038/5039/5040/5041/5042/5043/5044/5045/5046/5047/5048/5049/5050/5051/5052/5053/5054/5055/5056/5057/5058/5059/5060/5061/5062/5063/5064/5065/5066/5067/5068/5069/5070
@@ -23,13 +23,13 @@
 	%set REPORTYPE =  7001/7002/7003/7004/7005/7006/7007/7008/7009/7010/7011/7012/7013/7014/7015
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SATOB ) %and %not REPORTYPE %then
-	%set REPORTYPE =  8001/8002/8003/8004/8005/8006/8007/8008/8009/8010/8011/8012/8013/8014/8015/8016/8017/8018/8019/8020/8021/8022/8023/8024/8025/8026/8027/8028/8029/8030/8031/8032/8033/8034/8035/8036/8037/8038/8039/8040/8041/8042/8043/8044/8045/8046/8047/8048/8049/8050
+	%set REPORTYPE =  8001/8002/8003/8004/8005/8006/8007/8008/8009/8010/8011/8012/8013/8014/8015/8016/8017/8018/8019/8020/8021/8022/8023/8024/8025/8026/8027/8028/8029/8030/8031/8032/8033/8034/8035/8036/8037/8038/8039/8040/8041/8042/8043/8044/8045/8046/8047/8048/8049/8050/8051/8052/8053/8054
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SCATT ) %and %not REPORTYPE %then
 	%set REPORTYPE =  9001/9002/9003/9004/9005/9006/9007/9008/9009
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SSMI_AS ) %and %not REPORTYPE %then
-	%set REPORTYPE =  10001/10002/10003/10004/10005/10006/10007/10008
+	%set REPORTYPE =  10001/10002/10003/10004/10005/10006/10007/10008/10009/10010/10011/10012/10013/10014
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  IASI ) %and %not REPORTYPE %then
 	%set REPORTYPE =  11001/11002
@@ -38,7 +38,7 @@
 	%set REPORTYPE =  12001
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SSMIS_AS ) %and %not REPORTYPE %then
-	%set REPORTYPE =  13001/13002/13003
+	%set REPORTYPE =  13001/13002/13003/13004
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  TMI_AS ) %and %not REPORTYPE %then
 	%set REPORTYPE =  14001
@@ -47,7 +47,7 @@
 	%set REPORTYPE =  15001
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  CONV ) %and %not REPORTYPE %then
-	%set REPORTYPE =  16001/16002/16003/16004/16005/16006/16007/16008/16009/16010/16011/16012/16013/16014/16015/16016/16017/16018/16019/16020/16021/16022/16023/16024/16025/16026/16027/16028/16029/16030/16031/16032/16037/16038/16039/16040/16041/16042/16043/16044/16045/16046/16047/16048/16049/16050/16051/16052/16053/16054/16055/16056/16057/16058/16059/16060/16061/16062/16063/16064/16065/16066/16067/16068/16069/16070/16071/16072/16073/16074/16075/16076/16077/16078/16079/16080/16081/16082
+	%set REPORTYPE =  16001/16002/16003/16004/16005/16006/16007/16008/16009/16010/16011/16012/16013/16014/16015/16016/16017/16018/16019/16020/16021/16022/16023/16024/16025/16026/16027/16028/16029/16030/16031/16032/16037/16038/16039/16040/16041/16042/16043/16044/16045/16046/16047/16048/16049/16050/16051/16052/16053/16054/16055/16056/16057/16058/16059/16060/16061/16062/16063/16064/16065/16066/16067/16068/16069/16070/16071/16072/16073/16074/16075/16076/16077/16078/16079/16080/16081/16082/16083/16084
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SMOS ) %and %not REPORTYPE %then
 	%set REPORTYPE =  18001
@@ -68,7 +68,7 @@
 	%set REPORTYPE =  23001
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SSMIS ) %and %not REPORTYPE %then
-	%set REPORTYPE =  24001/24002/24003
+	%set REPORTYPE =  24001/24002/24003/24004
 
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  GBRAD ) %and %not REPORTYPE %then
 	%set REPORTYPE =  25001
@@ -166,6 +166,9 @@
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SSMT2 ) %and %not REPORTYPE %then
 	%set REPORTYPE =  58001/58002/58003/58004
 
+%if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  SMAP ) %and %not REPORTYPE %then
+	%set REPORTYPE =  59001
+
 %if (TYPE = OFB %or TYPE = MFB %or TYPE = OAI) %and (OBSGROUP =  TEST ) %and %not REPORTYPE %then
 	%set REPORTYPE =  98001/98002/98003/98004/98005/98006/98007/98008/98009/98010
 
diff --git a/share/metview/etc/uPlotTable b/share/metview/etc/uPlotTable
index caecaeb..c4397a7 100644
--- a/share/metview/etc/uPlotTable
+++ b/share/metview/etc/uPlotTable
@@ -452,7 +452,7 @@ dataunit,
 dataunit,
    class         = NETCDF_XY_MATRIX,
    defaultVisDef = MCONT,
-   listVisDef    = MCONT/PCONT
+   listVisDef    = MCONT/PCONT/MWIND/PWIND
 
 dataunit,
    class         = NETCDF_XY_VECTORS,
diff --git a/share/metview/icons/CMakeLists.txt b/share/metview/icons/CMakeLists.txt
index ee14314..fe236cb 100644
--- a/share/metview/icons/CMakeLists.txt
+++ b/share/metview/icons/CMakeLists.txt
@@ -112,6 +112,9 @@ endif()
 #  ---------- end of module-specific icons -------------
 
 
+set (outdir ${CMAKE_BINARY_DIR}/share/metview/icons)
+
+
 ##############################################################
 #
 # Rules to generate the icons
@@ -132,9 +135,9 @@ foreach(file ${full_icons} ${ModuleXpmFiles})
     # filename manipulation to get source and destination filenames
     get_filename_component( path     ${file} PATH   )
     get_filename_component( basefile ${file} NAME_WE )
-    set(full_icon  ${basefile}.icon)
-    set(half_icon  ${basefile}.half)
-    set(fixed_icon ${basefile}.fixed)
+    set(full_icon  ${outdir}/${basefile}.icon)
+    set(half_icon  ${outdir}/${basefile}.half)
+    set(fixed_icon ${outdir}/${basefile}.fixed)
 
     # add custom commands to a) copy the source icons into .icon and b) convert the source icons into .half
     add_custom_command( 
@@ -158,17 +161,17 @@ foreach(file ${full_icons} ${ModuleXpmFiles})
     set_source_files_properties(${half_icon} GENERATED)
 
     # generate lists of these generated files
-    list( APPEND full_icons ${CMAKE_CURRENT_BINARY_DIR}/${full_icon}) 
-    list( APPEND half_icons ${CMAKE_CURRENT_BINARY_DIR}/${half_icon}) 
+    list( APPEND full_icons ${full_icon}) 
+    list( APPEND half_icons ${half_icon}) 
 
 
     # ensure files are installed at install time
-    install( FILES       ${CMAKE_CURRENT_BINARY_DIR}/${full_icon}
+    install( FILES       ${full_icon}
              DESTINATION share/metview/icons
              PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
     ADD_DEPENDENCIES(${basefile}_full_target ${file})
 
-    install( FILES       ${CMAKE_CURRENT_BINARY_DIR}/${half_icon}
+    install( FILES       ${half_icon}
              DESTINATION share/metview/icons
              PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ)
 
diff --git a/share/metview/icons_mv5/CMakeLists.txt b/share/metview/icons_mv5/CMakeLists.txt
index 7033c46..2a014eb 100644
--- a/share/metview/icons_mv5/CMakeLists.txt
+++ b/share/metview/icons_mv5/CMakeLists.txt
@@ -90,7 +90,6 @@ set(xpm_icons
     MAXIS.xpm
     MetPlus.xpm
     MTAYLOR.xpm
-    MTHERMO.xpm
     MVPROFILE.xpm
     MVPROFILEVIEW.xpm
     MVPROFVIEW.xpm
@@ -132,14 +131,15 @@ set(xpm_icons
     XSECTION.xpm        
 )
 
-
+set(build_dir_dor_icons_mv5 "${CMAKE_BINARY_DIR}/share/metview/icons_mv5")
+file(MAKE_DIRECTORY ${build_dir_dor_icons_mv5})
 
 foreach(file ${svg_icons} ${xpm_icons} ${ModuleSvgFiles})
 
     #message(STATUS "converting ${file}")
 
     # copy to the build 'bin' directory
-    configure_file(${file} ${CMAKE_CURRENT_BINARY_DIR} COPYONLY)
+    configure_file(${file} "${build_dir_dor_icons_mv5}" COPYONLY)
 
 
     # ensure file is installed at install time
diff --git a/src/AppMod/CMakeLists.txt b/src/AppMod/CMakeLists.txt
index ac8b076..cb88420 100644
--- a/src/AppMod/CMakeLists.txt
+++ b/src/AppMod/CMakeLists.txt
@@ -1,6 +1,9 @@
 
-QT4_WRAP_CPP(savepool_MOC savepool.h)
-
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(savepool_MOC savepool.h)
+else()
+ QT4_WRAP_CPP(savepool_MOC savepool.h)
+endif()
 
 ecbuild_add_executable( TARGET       savepool 
                         SOURCES      savepool.cc ${savepool_MOC}
@@ -32,7 +35,7 @@ if(ENABLE_MOTIF)
 ecbuild_add_executable( TARGET       exampool
                         SOURCES      examcback.cc exammain.c examwidgets.h
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${METVIEW_EXTRA_LIBRARIES} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
 
@@ -47,7 +50,7 @@ ADD_CUSTOM_TARGET(maillex DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/maill.c)
 ecbuild_add_executable( TARGET       mvnews
                         SOURCES      newsmain.c newscback.c maill.c
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${METVIEW_EXTRA_LIBRARIES} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
 ADD_DEPENDENCIES(mvnews maillex)
@@ -56,14 +59,14 @@ ADD_DEPENDENCIES(mvnews maillex)
 ecbuild_add_executable( TARGET       mvmail
                         SOURCES      mailmain.c mailcback.c
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${METVIEW_EXTRA_LIBRARIES} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
 
 ecbuild_add_executable( TARGET       checkdisplay
                         SOURCES      checkdisplay.cc
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${METVIEW_EXTRA_LIBRARIES} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
 
diff --git a/src/BufrExaminer/CMakeLists.txt b/src/BufrExaminer/CMakeLists.txt
index 3070252..d26b4aa 100644
--- a/src/BufrExaminer/CMakeLists.txt
+++ b/src/BufrExaminer/CMakeLists.txt
@@ -1,6 +1,9 @@
 
-QT4_WRAP_CPP(Bufr_MOC BufrExaminer.h)
-
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(Bufr_MOC BufrExaminer.h)
+else()
+ QT4_WRAP_CPP(Bufr_MOC BufrExaminer.h)
+endif()
 
 ecbuild_add_executable( TARGET       BufrExaminer
                         SOURCES      MvMain.cc BufrMetaData.cc BufrExaminer.cc MvQBufrDumpModel.cc
diff --git a/src/DebugTools/CMakeLists.txt b/src/DebugTools/CMakeLists.txt
index 4f1ab1f..03e4cf4 100644
--- a/src/DebugTools/CMakeLists.txt
+++ b/src/DebugTools/CMakeLists.txt
@@ -2,8 +2,13 @@
 ### TODO: bin/mvmon  bin/MvMonitor
 
 
-QT4_WRAP_CPP(XServ_MOC XServ.h)
-QT4_ADD_RESOURCES(XServ_RES XServ.qrc)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(XServ_MOC XServ.h)
+ QT5_ADD_RESOURCES(XServ_RES XServ.qrc)
+else()
+ QT4_WRAP_CPP(XServ_MOC XServ.h)
+ QT4_ADD_RESOURCES(XServ_RES XServ.qrc)
+endif()
 
 
 set(xserv_srcs
@@ -11,7 +16,6 @@ set(xserv_srcs
 )
 
 
-
 ecbuild_add_executable( TARGET       xserv
                         SOURCES      ${xserv_srcs}
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
@@ -37,8 +41,14 @@ ecbuild_add_executable( TARGET       mvmon
 endif()
 ################################
 
-QT4_WRAP_CPP(MvMonitor_MOC ProcMonitor.h)
-QT4_ADD_RESOURCES(MvMonitor_RES debug.qrc)
+
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(MvMonitor_MOC ProcMonitor.h)
+ QT5_ADD_RESOURCES(MvMonitor_RES debug.qrc)
+else()
+ QT4_WRAP_CPP(MvMonitor_MOC ProcMonitor.h)
+ QT4_ADD_RESOURCES(MvMonitor_RES debug.qrc)
+endif()
 
 #message(STATUS "WRAP_CPP: ${MvMonitor_MOC}")
 #message(STATUS "ADD_RES: ${MvMonitor_RES}")
diff --git a/src/DebugTools/XServ.h b/src/DebugTools/XServ.h
index 6c8e5c1..1b3a067 100644
--- a/src/DebugTools/XServ.h
+++ b/src/DebugTools/XServ.h
@@ -12,7 +12,11 @@
 
 #include "mars.h"
 #undef D  /// MARS
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 class XServBar : public QWidget
 {
diff --git a/src/Desktop/CMakeLists.txt b/src/Desktop/CMakeLists.txt
index c9863db..5191736 100644
--- a/src/Desktop/CMakeLists.txt
+++ b/src/Desktop/CMakeLists.txt
@@ -1,5 +1,4 @@
-
-QT4_WRAP_CPP(Desktop_MOC 
+set(desktop_qt_wrap_files                          
                          MvQAdvancedSearch.h
                          MvQBookmarks.h
                          MvQEditor.h
@@ -55,9 +54,19 @@ QT4_WRAP_CPP(Desktop_MOC
                          MacroParamEditor.h
                          Tools.h
                          Input.h
-)
+ )
 
-QT4_ADD_RESOURCES(Desktop_RES desktop.qrc)
+if(METVIEW_QT5)
+  QT5_WRAP_CPP(Desktop_MOC 
+       ${desktop_qt_wrap_files}
+  )
+  QT5_ADD_RESOURCES(Desktop_RES desktop.qrc)
+else()
+  QT4_WRAP_CPP(Desktop_MOC 
+       ${desktop_qt_wrap_files}
+  )
+  QT4_ADD_RESOURCES(Desktop_RES desktop.qrc)
+endif()
 
 set(desktop_srcs    MvMainQtBrowser.cc
                     MvQ.cc
diff --git a/src/Desktop/Editor.h b/src/Desktop/Editor.h
index af7b4be..1dccf69 100644
--- a/src/Desktop/Editor.h
+++ b/src/Desktop/Editor.h
@@ -60,7 +60,7 @@ protected:
 	virtual void showIt()=0;
 
 private:
-	Editor(const Editor&);
+	explicit Editor(const Editor&);
 	Editor& operator=(const Editor&);
 
 };
diff --git a/src/Desktop/MvQDetailedFolderView.cc b/src/Desktop/MvQDetailedFolderView.cc
index 35b3c79..bbbbd17 100644
--- a/src/Desktop/MvQDetailedFolderView.cc
+++ b/src/Desktop/MvQDetailedFolderView.cc
@@ -88,7 +88,11 @@ MvQDetailedFolderView::MvQDetailedFolderView(MvQFolderModel *folderModel,
 		this,SLOT(slotSelectItem(const QModelIndex)));
 			
 	//Set header ContextMenuPolicy	
+#ifdef METVIEW_QT5
+	header()->setSectionsMovable(false);
+#else
 	header()->setMovable(false);
+#endif
 	header()->setContextMenuPolicy(Qt::CustomContextMenu);
 
 	connect(header(),SIGNAL(customContextMenuRequested(const QPoint &)),
diff --git a/src/Desktop/MvQFileBrowser.cc b/src/Desktop/MvQFileBrowser.cc
index 2368923..7432dfe 100644
--- a/src/Desktop/MvQFileBrowser.cc
+++ b/src/Desktop/MvQFileBrowser.cc
@@ -55,6 +55,8 @@
 #include "Tools.h"
  
 bool MvQFileBrowser::quitStarted_=false;
+bool MvQFileBrowser::logoutStarted_=false;
+
 QList<MvQFileBrowser*> MvQFileBrowser::browsers_;
 
 MvQFileBrowser::MvQFileBrowser(QStringList relPathLst,QWidget *parent) : 
@@ -210,6 +212,9 @@ MvQFileBrowser::MvQFileBrowser(QStringList relPathLst,QWidget *parent) :
 	
 	if(relPathLst.count() > 0)
 	  	folderPanel_->resetWidgets(relPathLst);
+    
+	connect(qApp,SIGNAL(commitDataRequest(QSessionManager&)),
+			this,SLOT(slotCommitDataRequest(QSessionManager&)),Qt::DirectConnection);
 }
 
 MvQFileBrowser::~MvQFileBrowser()
@@ -233,7 +238,9 @@ void MvQFileBrowser::showIt()
 
 void MvQFileBrowser::closeEvent(QCloseEvent* event)
 {
-  	if(MvQFileBrowser::aboutToClose(this))
+	qDebug() << "closeEvent";
+    
+    if(MvQFileBrowser::aboutToClose(this))
 	{	
 		browsers_.removeOne(this);
 		saveFolderInfo();		
@@ -251,6 +258,16 @@ void MvQFileBrowser::slotQuit()
 	 MvQFileBrowser::aboutToQuit(this);  
 }  
 
+
+//This slot is called when the window mangager quits to ask the app to
+//close in a correct way. We set the logoutStarted_ flag to indicate that 
+//this happened. 
+void MvQFileBrowser::slotCommitDataRequest(QSessionManager& manager)
+{
+	qDebug() << "commit";    
+	logoutStarted_=true;
+}
+
 //==============================================================
 //
 //  Set up actions
@@ -1490,7 +1507,12 @@ bool MvQFileBrowser::aboutToClose(MvQFileBrowser* browser)
 		  	int tabCnt=browser->folderPanel_->count();
 			if(tabCnt > 1)
 			{
-		  		if(QMessageBox::question(0,tr("Confirm close"),tr("You are about to close <b>") + QString::number(tabCnt) + tr("</b> tabs. Are you sure you want to continue?"),
+                if(logoutStarted_)
+                {
+                    return true;
+                }    
+                
+                if(QMessageBox::question(0,tr("Confirm close"),tr("You are about to close <b>") + QString::number(tabCnt) + tr("</b> tabs. Are you sure you want to continue?"),
 			    	      QMessageBox::Yes | QMessageBox::Cancel,QMessageBox::Cancel) == QMessageBox::Cancel)
 				{		
 					return false;
@@ -1503,11 +1525,13 @@ bool MvQFileBrowser::aboutToClose(MvQFileBrowser* browser)
 		}	
 		return true;
 	}	
+	
+	return true;
 }	
 
 bool MvQFileBrowser::aboutToQuit(MvQFileBrowser* topBrowser)
 {
-  	if(QMessageBox::question(0,tr("Confirm quit"),tr("Do you want to quit Metview?"),
+	if(logoutStarted_ || QMessageBox::question(0,tr("Confirm quit"),tr("Do you want to quit Metview?"),
 			     QMessageBox::Yes | QMessageBox::Cancel,QMessageBox::Cancel) == QMessageBox::Yes)
 	{
 		quitStarted_=true;
@@ -1521,8 +1545,13 @@ bool MvQFileBrowser::aboutToQuit(MvQFileBrowser* topBrowser)
 		//Save browser settings
 		MvQFileBrowser::save(topBrowser);		
 		
+        if(logoutStarted_)
+            return true;
+        
 		//Exit metview
 		QApplication::quit();
+        
+        return true;
 	}
 	
 	return false;
diff --git a/src/Desktop/MvQFileBrowser.h b/src/Desktop/MvQFileBrowser.h
index cbbd53a..f842d44 100644
--- a/src/Desktop/MvQFileBrowser.h
+++ b/src/Desktop/MvQFileBrowser.h
@@ -15,6 +15,7 @@
 #include <QMap>
 #include <QMainWindow>
 #include <QList>
+#include <QSessionManager>
 #include <QSettings>
 #include <QString>
 
@@ -71,6 +72,7 @@ public:
 	
 public slots:
 	void slotQuit();
+	void slotCommitDataRequest(QSessionManager & manager );
 	void slotOpenInBrowser(QString);
 	void slotOpenInTab(QString);
 	void slotOpenInWin(QString);
@@ -140,6 +142,7 @@ protected:
 	
 	
 	static bool quitStarted_;
+	static bool logoutStarted_;
 	static QList<MvQFileBrowser*> browsers_;	
 	
 	MvQMainWindow::MenuItemMap menuItems_;
diff --git a/src/Desktop/MvQFolderModel.cc b/src/Desktop/MvQFolderModel.cc
index 0e8c641..2ebf14c 100644
--- a/src/Desktop/MvQFolderModel.cc
+++ b/src/Desktop/MvQFolderModel.cc
@@ -421,7 +421,7 @@ QModelIndex MvQFolderModel::index( int row, int column, const QModelIndex & /*pa
 		return QModelIndex();
 	}
 
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
@@ -466,7 +466,7 @@ QModelIndex MvQFolderModel::indexFromObject(IconObject *obj)
 	  	return QModelIndex();
   
 	int i=items_.indexOf(obj);
-	return (i >=0)?createIndex(i,0,0):QModelIndex();
+	return (i >=0)?createIndex(i,0,(void*)0):QModelIndex();
 }
 
 //Should be called between beginResetModel() and endResetModel() !!
@@ -809,7 +809,9 @@ void MvQFolderModel::updateSearchData(bool doReset)
 	if(!hasSearchData())
 	{
 	  	if(doReset)
-		  	reset();
+		  //reset();  NOT in Qt 5
+	      beginResetModel();
+	      endResetModel();
 		return;
 	}
 	
@@ -829,7 +831,9 @@ void MvQFolderModel::updateSearchData(bool doReset)
 	searchData_->matchChanged();
 	
 	if(doReset)
-		reset();	 
+	//reset();  NOT in Qt 5
+	beginResetModel();
+	endResetModel();
 }  
 
 bool MvQFolderModel::hasSearchData() const
diff --git a/src/Desktop/MvQIconFolderView.cc b/src/Desktop/MvQIconFolderView.cc
index 72c8f5a..1ab7c0a 100644
--- a/src/Desktop/MvQIconFolderView.cc
+++ b/src/Desktop/MvQIconFolderView.cc
@@ -30,6 +30,7 @@
 
 #include <QApplication>
 #include <QClipboard>
+#include <QDrag>
 #include <QDropEvent>
 #include <QLinearGradient>
 #include <QLineEdit>
@@ -431,25 +432,23 @@ void MvQIconFolderView::changeEvent(QEvent* event)
 
 QModelIndex MvQIconFolderView::indexAt(QPointF scenePos)
 {
-	QGraphicsItem *item=scene()->itemAt(scenePos);
+	QGraphicsItem *item=scene()->itemAt(scenePos, QTransform());
 	if(item)
 	{	  
 	  	MvQIconItem* icItem=static_cast<MvQIconItem*>(item);
 		return icItem->index();  	
-	}
-	
+	}	
 	return QModelIndex();
 }
 
 IconObject* MvQIconFolderView::iconObjectAt(QPointF scenePos)
 {
-	QGraphicsItem *item=scene()->itemAt(scenePos);
+	QGraphicsItem *item=scene()->itemAt(scenePos, QTransform());
 	if(item)
 	{	  
 	  	MvQIconItem* icItem=static_cast<MvQIconItem*>(item);
 		return folderModel_->objectFromIndex(icItem->index());  	
 	}
-	
 	return 0;
 }
 
diff --git a/src/Desktop/MvQIconHolder.cc b/src/Desktop/MvQIconHolder.cc
index f8fbcf8..aa52043 100644
--- a/src/Desktop/MvQIconHolder.cc
+++ b/src/Desktop/MvQIconHolder.cc
@@ -135,7 +135,7 @@ QVariant MvQIconHolderModel::data( const QModelIndex& index, int role ) const
 
 QModelIndex MvQIconHolderModel::index( int row, int column, const QModelIndex & /*parent */) const
 {
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/Desktop/MvQIconMimeData.cc b/src/Desktop/MvQIconMimeData.cc
index 2176e35..c2a4ed1 100644
--- a/src/Desktop/MvQIconMimeData.cc
+++ b/src/Desktop/MvQIconMimeData.cc
@@ -8,9 +8,11 @@
  ***************************** LICENSE END *************************************/
 
 #include <QDebug>
+#ifdef METVIEW_QT5
+#include <QDataStream>
+#endif
 
 #include "MvQIconMimeData.h"
-
 #include "MvQFolderModel.h"
 #include "IconClass.h"
 #include "IconObject.h"
diff --git a/src/Desktop/MvQIconObjectModel.cc b/src/Desktop/MvQIconObjectModel.cc
index 086c140..c857652 100644
--- a/src/Desktop/MvQIconObjectModel.cc
+++ b/src/Desktop/MvQIconObjectModel.cc
@@ -95,7 +95,7 @@ QVariant MvQIconObjectModel::data( const QModelIndex& index, int role ) const
 
 QModelIndex MvQIconObjectModel::index( int row, int column, const QModelIndex & /*parent */) const
 {
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/Desktop/MvQListFolderViewBase.cc b/src/Desktop/MvQListFolderViewBase.cc
index da95414..07335d0 100644
--- a/src/Desktop/MvQListFolderViewBase.cc
+++ b/src/Desktop/MvQListFolderViewBase.cc
@@ -9,6 +9,7 @@
 
 #include <QApplication>
 #include <QDataStream>
+#include <QDrag>
 #include <QDropEvent>
 #include <QDebug>
 #include <QMouseEvent>
diff --git a/src/Desktop/MvQNewIconWidget.cc b/src/Desktop/MvQNewIconWidget.cc
index 5e372a5..9349b06 100644
--- a/src/Desktop/MvQNewIconWidget.cc
+++ b/src/Desktop/MvQNewIconWidget.cc
@@ -28,6 +28,7 @@
 #include <QStyleOption>
 #include <QToolButton>
 #include <QVBoxLayout>
+#include <QDrag>
 
 #include "MvQIconMimeData.h"
 #include "MvQIconProvider.h"
diff --git a/src/Desktop/MvQProductBrowser.cc b/src/Desktop/MvQProductBrowser.cc
index a1d75c8..ab7f0d0 100644
--- a/src/Desktop/MvQProductBrowser.cc
+++ b/src/Desktop/MvQProductBrowser.cc
@@ -317,7 +317,7 @@ bool MvQProductModel::setData(const QModelIndex & index, QRect rect, int role)
 QModelIndex MvQProductModel::index( int row, int column, const QModelIndex & /*parent*/ ) const
 {
 
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/Desktop/ViewEditor.cc b/src/Desktop/ViewEditor.cc
index 91351d1..80959a5 100644
--- a/src/Desktop/ViewEditor.cc
+++ b/src/Desktop/ViewEditor.cc
@@ -169,8 +169,9 @@ ViewEditor::ViewEditor(const IconClass& name,const string& kind):
 	expandAc->setIcon(QPixmap(":/desktop/page_expand.svg"));
 	
 	QAction *connectAc=new QAction(this);
-	connectAc->setToolTip(tr("Connect selected frames"));	
+	connectAc->setToolTip(tr("Connect selected frames - NOT YET SUPPORTED"));	
 	connectAc->setIcon(QPixmap(":/desktop/page_connect.svg"));
+	connectAc->setEnabled(false);
 		
 	QAction *disconnectAc=new QAction(this);
 	disconnectAc->setToolTip(tr("Disonnect selected frames"));
@@ -191,8 +192,8 @@ ViewEditor::ViewEditor(const IconClass& name,const string& kind):
 	connect(expandAc,SIGNAL(triggered(bool)),
 		this,SLOT(slotExpandSelection(bool)));
 				
-	connect(connectAc,SIGNAL(triggered(bool)),
-		this,SLOT(slotConnectSelection(bool)));
+	//connect(connectAc,SIGNAL(triggered(bool)),
+		//this,SLOT(slotConnectSelection(bool)));
 		
 	connect(disconnectAc,SIGNAL(triggered(bool)),
 		this,SLOT(slotDisconnectSelection(bool)));
diff --git a/src/FlextraExaminer/CMakeLists.txt b/src/FlextraExaminer/CMakeLists.txt
index 802858b..d29ef83 100644
--- a/src/FlextraExaminer/CMakeLists.txt
+++ b/src/FlextraExaminer/CMakeLists.txt
@@ -1,5 +1,8 @@
-
-QT4_WRAP_CPP(FlextraExaminer_MOC FlextraExaminer.h)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(FlextraExaminer_MOC FlextraExaminer.h)
+else()
+ QT4_WRAP_CPP(FlextraExaminer_MOC FlextraExaminer.h)
+endif()
 
 
 ecbuild_add_executable( TARGET       FlextraExaminer
diff --git a/src/GeopExaminer/CMakeLists.txt b/src/GeopExaminer/CMakeLists.txt
index 1f736d9..5e352bf 100644
--- a/src/GeopExaminer/CMakeLists.txt
+++ b/src/GeopExaminer/CMakeLists.txt
@@ -1,5 +1,9 @@
 
-QT4_WRAP_CPP(Geop_MOC GeopExaminer.h)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(Geop_MOC GeopExaminer.h)
+else()
+ QT4_WRAP_CPP(Geop_MOC GeopExaminer.h)
+endif()
 
 
 ecbuild_add_executable( TARGET       GeopExaminer
diff --git a/src/GeopExaminer/MvGeoPointsModel.cc b/src/GeopExaminer/MvGeoPointsModel.cc
index a96e536..acad093 100644
--- a/src/GeopExaminer/MvGeoPointsModel.cc
+++ b/src/GeopExaminer/MvGeoPointsModel.cc
@@ -94,7 +94,7 @@ QModelIndex MvQGeoPointsDataModel::index( int row, int column, const QModelIndex
 	if(data_ == 0 || data_->count() <= 0 || column < 0)
 		return QModelIndex();
 	
-	return createIndex(row, column, 0); 
+	return createIndex(row, column, (void*)0); 
 }
 
 
diff --git a/src/GribExaminer/CMakeLists.txt b/src/GribExaminer/CMakeLists.txt
index 11ba3b7..03b051f 100644
--- a/src/GribExaminer/CMakeLists.txt
+++ b/src/GribExaminer/CMakeLists.txt
@@ -1,5 +1,9 @@
 
-QT4_WRAP_CPP(Grib_MOC GribExaminer.h)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(Grib_MOC GribExaminer.h)
+else()
+ QT4_WRAP_CPP(Grib_MOC GribExaminer.h)
+endif()
 
 
 ecbuild_add_executable( TARGET       GribExaminer
diff --git a/src/GribExaminer/MvQGribDumpModel.cc b/src/GribExaminer/MvQGribDumpModel.cc
index 2260570..714ffab 100644
--- a/src/GribExaminer/MvQGribDumpModel.cc
+++ b/src/GribExaminer/MvQGribDumpModel.cc
@@ -158,7 +158,11 @@ QString MvQGribMvDumpModel::label(GribItem *item,const int column ) const
 
 QModelIndex MvQGribMvDumpModel::index( int row, int column, const QModelIndex & /*parent*/ ) const
 {
-	return createIndex(row,column,0);
+#ifdef METVIEW_QT5
+    return createIndex(row,column,(void*)0);
+#else
+    return createIndex(row,column,0);
+#endif
 }
 
 
@@ -922,7 +926,11 @@ QVariant MvQGribValueDumpModel::headerData( const int section, const Qt::Orienta
 
 QModelIndex MvQGribValueDumpModel::index( int row, int column, const QModelIndex & /*parent*/ ) const
 {
-	return createIndex(row,column,0);
+#ifdef METVIEW_QT5
+    return createIndex(row,column,(void*)0);
+#else
+    return createIndex(row,column,0);
+#endif
 }
 
 
diff --git a/src/Hovmoeller/HovToolkit.cc b/src/Hovmoeller/HovToolkit.cc
index 5f694e7..5c4bc9b 100644
--- a/src/Hovmoeller/HovToolkit.cc
+++ b/src/Hovmoeller/HovToolkit.cc
@@ -539,7 +539,24 @@ double HovToolkit::GetDateDif(string& timekey)
    double ddate = atof(timekey.substr(0,8).c_str());
    double dhour = atof(timekey.substr(8,2).c_str());
    double dmin  = atof(timekey.substr(10,2).c_str());
-   double dstep = atof(timekey.substr(12,HOV_STEPSIZE).c_str());
+   double dstep;
+   string strStep = timekey.substr(12,HOV_STEPSIZE);
+
+
+   // Note that the step can be a negative number. Since it has been padded
+   // with leading zeros, it could look like "000-72", which is not
+   // correctly interpreted as a number. Therefore we need to remove leading
+   // zeros before parsing it.
+   std::size_t found = strStep.find_first_not_of("0");
+
+   if (found!=std::string::npos)
+   {
+       dstep = atof(strStep.substr(found, std::string::npos).c_str());  // parse from the first non-zero character
+   }
+   else
+   {
+       dstep = 0;   // nothing but zeros
+   }
 
    // Compute hour+min+step in fraction of days
    double frac = dhour*3600./86400. + dmin*60./86400. + dstep*3600./86400.;
diff --git a/src/MacroEditor/CMakeLists.txt b/src/MacroEditor/CMakeLists.txt
index db5ee21..e317e0a 100644
--- a/src/MacroEditor/CMakeLists.txt
+++ b/src/MacroEditor/CMakeLists.txt
@@ -1,9 +1,17 @@
 
-QT4_WRAP_CPP      (MacroEd_MOC MvMain.h FindTextDialog.h Highlighter.h MacroEdit.h FunctionListDialog.h mvplaintextedit.h
+if(METVIEW_QT5)
+ QT5_WRAP_CPP      (MacroEd_MOC MvMain.h FindTextDialog.h Highlighter.h MacroEdit.h FunctionListDialog.h mvplaintextedit.h
                    CodeTemplateDialog.h GotoLineDialog.h RunDialog.h TabsDialog.h VerbFunctionHelpDialog.h MacroEdit.h)
-QT4_ADD_RESOURCES (MacroEd_RES MacroEdit.qrc)
-QT4_WRAP_UI       (MacroEd_FORMS_HEADERS CodeTemplateDialog.ui FunctionListDialog.ui VerbFunctionHelpDialog.ui
+ QT5_ADD_RESOURCES (MacroEd_RES MacroEdit.qrc)
+ QT5_WRAP_UI       (MacroEd_FORMS_HEADERS CodeTemplateDialog.ui FunctionListDialog.ui VerbFunctionHelpDialog.ui
                    FindTextDialog.ui MacroEdit.ui GotoLineDialog.ui RunDialog.ui TabsDialog.ui)
+else()
+ QT4_WRAP_CPP      (MacroEd_MOC MvMain.h FindTextDialog.h Highlighter.h MacroEdit.h FunctionListDialog.h mvplaintextedit.h
+                   CodeTemplateDialog.h GotoLineDialog.h RunDialog.h TabsDialog.h VerbFunctionHelpDialog.h MacroEdit.h)
+ QT4_ADD_RESOURCES (MacroEd_RES MacroEdit.qrc)
+ QT4_WRAP_UI       (MacroEd_FORMS_HEADERS CodeTemplateDialog.ui FunctionListDialog.ui VerbFunctionHelpDialog.ui
+                   FindTextDialog.ui MacroEdit.ui GotoLineDialog.ui RunDialog.ui TabsDialog.ui)
+endif()
 
 set(macroeditor_srcs MvMain.cc
                      Highlighter.cc
diff --git a/src/MacroEditor/CodeTemplateDialog.cc b/src/MacroEditor/CodeTemplateDialog.cc
index 6d7c62a..b07e949 100644
--- a/src/MacroEditor/CodeTemplateDialog.cc
+++ b/src/MacroEditor/CodeTemplateDialog.cc
@@ -7,7 +7,11 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 #include "CodeTemplateDialog.h"
 
diff --git a/src/MacroEditor/FunctionListDialog.cc b/src/MacroEditor/FunctionListDialog.cc
index c5a1ae8..bdde9ed 100644
--- a/src/MacroEditor/FunctionListDialog.cc
+++ b/src/MacroEditor/FunctionListDialog.cc
@@ -7,7 +7,11 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 #include "FunctionListDialog.h"
 
diff --git a/src/MacroEditor/GotoLineDialog.cc b/src/MacroEditor/GotoLineDialog.cc
index faef658..0c2f00c 100644
--- a/src/MacroEditor/GotoLineDialog.cc
+++ b/src/MacroEditor/GotoLineDialog.cc
@@ -7,7 +7,11 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 #include "GotoLineDialog.h"
 
diff --git a/src/MacroEditor/MacroEdit.cc b/src/MacroEditor/MacroEdit.cc
index 99638a3..e05966e 100644
--- a/src/MacroEditor/MacroEdit.cc
+++ b/src/MacroEditor/MacroEdit.cc
@@ -7,7 +7,13 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+ #include <QtPrintSupport/QPrinter>
+ #include <QtPrintSupport/QPrintDialog>
+#else
+ #include <QtGui>
+#endif
 
 #include "MacroEdit.h"
 #include "FindTextDialog.h"
diff --git a/src/MacroEditor/VerbFunctionHelp.cc b/src/MacroEditor/VerbFunctionHelp.cc
index 2b3c4b1..a59b7eb 100644
--- a/src/MacroEditor/VerbFunctionHelp.cc
+++ b/src/MacroEditor/VerbFunctionHelp.cc
@@ -7,7 +7,11 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 #include "VerbFunctionHelp.h"
 
diff --git a/src/MacroEditor/VerbFunctionHelpDialog.cc b/src/MacroEditor/VerbFunctionHelpDialog.cc
index c333fde..17e0983 100644
--- a/src/MacroEditor/VerbFunctionHelpDialog.cc
+++ b/src/MacroEditor/VerbFunctionHelpDialog.cc
@@ -7,7 +7,11 @@
 
  ***************************** LICENSE END *************************************/
 
-#include <QtGui>
+#ifdef METVIEW_QT5
+ #include <QtWidgets>
+#else
+ #include <QtGui>
+#endif
 
 #include "VerbFunctionHelpDialog.h"
 
diff --git a/src/MacroEditor/mvplaintextedit.h b/src/MacroEditor/mvplaintextedit.h
index 620f912..9f3cc72 100644
--- a/src/MacroEditor/mvplaintextedit.h
+++ b/src/MacroEditor/mvplaintextedit.h
@@ -10,8 +10,11 @@
 #ifndef MvPlainTextEdit_H
 #define MvPlainTextEdit_H
 
-#include <QtGui/QPlainTextEdit>
-
+#ifdef METVIEW_QT5
+ #include <QtWidgets/QPlainTextEdit>
+#else
+ #include <QtGui/QPlainTextEdit>
+#endif
 #include "TabsSettings.h"
 
 class LineNumberArea;
diff --git a/src/MagML/CMakeLists.txt b/src/MagML/CMakeLists.txt
index 4ec8509..7c6468c 100644
--- a/src/MagML/CMakeLists.txt
+++ b/src/MagML/CMakeLists.txt
@@ -6,6 +6,9 @@ ecbuild_add_executable( TARGET       MagML
                         LIBS         ${METVIEW_QT_LIBRARIES} ${STANDARD_METVIEW_LIBS} ${MAGICS_LIBRARIES}
                     )
 
+# add this dependency manually because CMake does not pick it up otherwise
+ADD_DEPENDENCIES(MagML MagPlusShared MagWrapper)
+
 
 metview_module_files(ETC_FILES ObjectSpec.MagML
                      XPM_FILES MAGML.xpm)
diff --git a/src/MarsCatalog/CMakeLists.txt b/src/MarsCatalog/CMakeLists.txt
index bcbe8d8..6a87508 100644
--- a/src/MarsCatalog/CMakeLists.txt
+++ b/src/MarsCatalog/CMakeLists.txt
@@ -1,6 +1,10 @@
-
-QT4_WRAP_CPP(MarsCat_MOC MvQMarsBrowser.h MvQMarsCatalog.h)
-QT4_ADD_RESOURCES(MarsCat_RES mars.qrc)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(MarsCat_MOC MvQMarsBrowser.h MvQMarsCatalog.h)
+ QT5_ADD_RESOURCES(MarsCat_RES mars.qrc)
+else()
+ QT4_WRAP_CPP(MarsCat_MOC MvQMarsBrowser.h MvQMarsCatalog.h)
+ QT4_ADD_RESOURCES(MarsCat_RES mars.qrc)
+endif()
 
 set(mars_cat_srcs
     MvMain.cc
diff --git a/src/MarsCatalog/ObjectSpec.MarsCatalog b/src/MarsCatalog/ObjectSpec.MarsCatalog
index c3cfc27..5cef2fd 100644
--- a/src/MarsCatalog/ObjectSpec.MarsCatalog
+++ b/src/MarsCatalog/ObjectSpec.MarsCatalog
@@ -21,6 +21,6 @@ service,
 	name	= marscatalog,
 	timeout  = $timeout,
 	fullname = Mars Catalog,
-	cmd		= '$metview_command $METVIEW_BIN/MarsCatalog -maxforks 25 -style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss'
+	cmd		= '$metview_command $METVIEW_BIN/MarsCatalog $METVIEW_QT_APPLICATION_FLAGS'
 	
 
diff --git a/src/MetviewUI/CMakeLists.txt b/src/MetviewUI/CMakeLists.txt
index e4fafc9..b9f796d 100644
--- a/src/MetviewUI/CMakeLists.txt
+++ b/src/MetviewUI/CMakeLists.txt
@@ -393,6 +393,6 @@ include_directories( CMAKE_CURRENT_SOURCE_DIR . )
 ecbuild_add_executable( TARGET       MetviewUI
                         SOURCES      ${MetviewUI_srcs}
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${METVIEW_EXTRA_LIBRARIES} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
diff --git a/src/MvApp/grib_to_geo.cc b/src/MvApp/grib_to_geo.cc
index 193cdff..a3f6438 100644
--- a/src/MvApp/grib_to_geo.cc
+++ b/src/MvApp/grib_to_geo.cc
@@ -67,13 +67,13 @@ void GribToGeo::serve( MvRequest& in, MvRequest& out )
 
   //long timePeriod = grd->getLong("periodOfTimeIntervals");//aki grib2//
   long step = field.stepFoh();
-  if( step != LONG_MAX && step > 0 ) // s1->p1 > 0 )
+  if( step != LONG_MAX && step != 0 ) // s1->p1 > 0 )
   {
       vDate += step;
   }
   long  dat = vDate.YyyyMmDd();
   long  tim = 100*vDate.Hour() + vDate.Minute();
-  cout << height << cTAB << dat << cTAB << tim << endl;
+  //cout << height << cTAB << dat << cTAB << tim << cTAB << step << endl;
 
 
 
diff --git a/src/NcExaminer/CMakeLists.txt b/src/NcExaminer/CMakeLists.txt
index 5dde1da..70212b7 100644
--- a/src/NcExaminer/CMakeLists.txt
+++ b/src/NcExaminer/CMakeLists.txt
@@ -1,5 +1,8 @@
-
-QT4_WRAP_CPP(NcExam_MOC NcExaminer.h)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(NcExam_MOC NcExaminer.h)
+else()
+ QT4_WRAP_CPP(NcExam_MOC NcExaminer.h)
+endif()
 
 
 ecbuild_add_executable( TARGET       NcExaminer
diff --git a/src/OdbExaminer/CMakeLists.txt b/src/OdbExaminer/CMakeLists.txt
index e84818a..4417b04 100644
--- a/src/OdbExaminer/CMakeLists.txt
+++ b/src/OdbExaminer/CMakeLists.txt
@@ -1,5 +1,8 @@
-
-QT4_WRAP_CPP(ODBExaminer_MOC OdbExaminer.h MvQOdbTableView.h)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(ODBExaminer_MOC OdbExaminer.h MvQOdbTableView.h)
+else()
+ QT4_WRAP_CPP(ODBExaminer_MOC OdbExaminer.h MvQOdbTableView.h)
+endif()
 
 set(odbexam_srcs
     MvMain.cc
diff --git a/src/OdbExaminer/MvQOdbStatModel.cc b/src/OdbExaminer/MvQOdbStatModel.cc
index dc2822c..bdd6aa5 100644
--- a/src/OdbExaminer/MvQOdbStatModel.cc
+++ b/src/OdbExaminer/MvQOdbStatModel.cc
@@ -55,7 +55,8 @@ void MvQOdbStatModel::resetLayers()
 void MvQOdbStatModel::setData(QList<MvQOdbStat*> data)
 {
 	data_=data;
-	reset();
+	beginResetModel();
+	endResetModel();
 }
 
 int MvQOdbStatModel::columnCount( const QModelIndex& /* parent */ ) const
@@ -116,7 +117,7 @@ QVariant MvQOdbStatModel::headerData( const int section, const Qt::Orientation o
 
 QModelIndex MvQOdbStatModel::index( int row, int column, const QModelIndex & parent ) const
 {
-   return createIndex(row,column,0);
+   return createIndex(row,column,static_cast<void*>(0));
 }
 
 
diff --git a/src/OgcClient/CMakeLists.txt b/src/OgcClient/CMakeLists.txt
index ac9e903..e044f4f 100644
--- a/src/OgcClient/CMakeLists.txt
+++ b/src/OgcClient/CMakeLists.txt
@@ -1,7 +1,13 @@
 
 #--------COMMON SOURCES--------------------------------------------------
 
-QT4_ADD_RESOURCES(OGC_common_RES MvQOgcClient.qrc)
+if(METVIEW_QT5)
+ QT5_ADD_RESOURCES(OGC_common_RES MvQOgcClient.qrc)
+ QT5_WRAP_CPP(WMS_MOC MvQWmsClient.h MvQWmsClientEditor.h)
+else()
+ QT4_ADD_RESOURCES(OGC_common_RES MvQOgcClient.qrc)
+ QT4_WRAP_CPP(WMS_MOC MvQWmsClient.h MvQWmsClientEditor.h)
+endif()
 
 set(OGC_common_srcs
     MvQHighlighter.cc
@@ -14,9 +20,6 @@ set(OGC_common_srcs
 
 #-------- WmsClient ------------------------------------------------------------------
 
-QT4_WRAP_CPP(WMS_MOC MvQWmsClient.h MvQWmsClientEditor.h)
-
-
 ecbuild_add_executable( TARGET       WmsClient
                         SOURCES      MvMain.cc
                                      ${OGC_common_srcs}
@@ -43,7 +46,11 @@ metview_module_files(ETC_FILES ObjectSpec.WmsClient
 
 if(ENABLE_EXPERIMENTAL)
 
+ if(METVIEW_QT5)
+    QT5_WRAP_CPP(WCS_MOC MvQWcsClient.h MvQWcsClientEditor.h)
+ else()
     QT4_WRAP_CPP(WCS_MOC MvQWcsClient.h MvQWcsClientEditor.h)
+ endif()
 
     ecbuild_add_executable( TARGET       WcsClient
                             SOURCES      MvMainWcsClient.cc
diff --git a/src/OgcClient/MvQWmsClientEditor.cc b/src/OgcClient/MvQWmsClientEditor.cc
index 95133ad..0b16aaa 100644
--- a/src/OgcClient/MvQWmsClientEditor.cc
+++ b/src/OgcClient/MvQWmsClientEditor.cc
@@ -1008,7 +1008,7 @@ void MvQWmsClientEditor::initFormatCombo()
 		formatCombo_->addItem(values[i]);
 		if(!client_->supportedMimeType().contains(values[i]))
 		{
-			formatCombo_->setItemData(i,Qt::darkGray,Qt::ForegroundRole);
+			formatCombo_->setItemData(i,QColor(Qt::darkGray),Qt::ForegroundRole);
 			formatCombo_->setItemData(i,tr("Not supported by Metview"),Qt::ToolTipRole);
 		}
 	}
@@ -1119,7 +1119,7 @@ void MvQWmsClientEditor::initCrsCombo()
 		crsCombo_->addItem(values[i]);
 		if(!client_->supportedCrs().contains(values[i]))
 		{
-			crsCombo_->setItemData(i,Qt::darkGray,Qt::ForegroundRole);
+			crsCombo_->setItemData(i,QColor(Qt::darkGray),Qt::ForegroundRole);
 			crsCombo_->setItemData(i,tr("Not supported by Metview"),Qt::ToolTipRole);
 		}
 	}
diff --git a/src/OgcClient/ObjectSpec.WcsClient b/src/OgcClient/ObjectSpec.WcsClient
index 8e1f738..a817a21 100644
--- a/src/OgcClient/ObjectSpec.WcsClient
+++ b/src/OgcClient/ObjectSpec.WcsClient
@@ -30,7 +30,7 @@ state,
 #action		= visualise/execute/save,
 
 service,
-	cmd		= '$METVIEW_CMD $METVIEW_BIN/WcsClient -maxforks 25 -style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss',
+	cmd		= '$METVIEW_CMD $METVIEW_BIN/WcsClient $METVIEW_QT_APPLICATION_FLAGS',
 	fullname = WCS Client,
 	maximum  = 0,
 	name		=  'wcsclient'
diff --git a/src/OgcClient/ObjectSpec.WmsClient b/src/OgcClient/ObjectSpec.WmsClient
index 59a1de8..0d7795b 100644
--- a/src/OgcClient/ObjectSpec.WmsClient
+++ b/src/OgcClient/ObjectSpec.WmsClient
@@ -41,7 +41,7 @@ state,
 	service		= uPlotManager
 
 service,
-	cmd		= '$METVIEW_CMD $METVIEW_BIN/WmsClient -maxforks 25 -style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss',
+	cmd		= '$METVIEW_CMD $METVIEW_BIN/WmsClient $METVIEW_QT_APPLICATION_FLAGS',
 	fullname = WMS Client,
 	maximum  = 0,
 	name		=  'wmsclient'
diff --git a/src/Reprojection/CMakeLists.txt b/src/Reprojection/CMakeLists.txt
index 285b27e..b90a419 100644
--- a/src/Reprojection/CMakeLists.txt
+++ b/src/Reprojection/CMakeLists.txt
@@ -7,6 +7,9 @@ ecbuild_add_executable( TARGET       Reprojection
                         LIBS         ${METVIEW_QT_LIBRARIES} ${STANDARD_METVIEW_LIBS} ${MAGICS_LIBRARIES}
                     )
 
+# add this dependency manually because CMake does not pick it up otherwise
+ADD_DEPENDENCIES(Reprojection MagPlusShared MagWrapper)
+
 
 metview_module_files(ETC_FILES ObjectSpec.Reprojection
                                ReprojectionDef
diff --git a/src/ScmEditor/CMakeLists.txt b/src/ScmEditor/CMakeLists.txt
index fc32967..1c40fc7 100644
--- a/src/ScmEditor/CMakeLists.txt
+++ b/src/ScmEditor/CMakeLists.txt
@@ -1,7 +1,10 @@
-
-QT4_WRAP_CPP(SCM_MOC ScmDataEditor.h)
-QT4_ADD_RESOURCES(SCM_RES scmEditor.qrc)
-
+if(METVIEW_QT5)
+  QT5_WRAP_CPP(SCM_MOC ScmDataEditor.h)
+  QT5_ADD_RESOURCES(SCM_RES scmEditor.qrc)
+else()
+  QT4_WRAP_CPP(SCM_MOC ScmDataEditor.h)
+  QT4_ADD_RESOURCES(SCM_RES scmEditor.qrc)
+endif()
 
 ecbuild_add_executable( TARGET       ScmDataEditor
                         SOURCES      MvMain.cc ScmDataEditor.cc ScmDataEditor.h ${SCM_MOC} ${SCM_RES}
diff --git a/src/StdAppManager/NetcdfPlusRules b/src/StdAppManager/NetcdfPlusRules
index dc63966..d15d38a 100644
--- a/src/StdAppManager/NetcdfPlusRules
+++ b/src/StdAppManager/NetcdfPlusRules
@@ -24,8 +24,6 @@
      %unset NETCDF_Y_VARIABLE
      %unset NETCDF_X_POSITION_VARIABLE
      %unset NETCDF_Y_POSITION_VARIABLE
-     %unset NETCDF_X_COMPONENT_VARIABLE
-     %unset NETCDF_Y_COMPONENT_VARIABLE
 
 %if NETCDF_PLOT_TYPE = XY_POINTS %then
      %unset NETCDF_LATITUDE_VARIABLE
@@ -49,7 +47,5 @@
 %if NETCDF_PLOT_TYPE = XY_MATRIX %then
      %unset NETCDF_LATITUDE_VARIABLE
      %unset NETCDF_LONGITUDE_VARIABLE
-     %unset NETCDF_X_COMPONENT_VARIABLE
-     %unset NETCDF_Y_COMPONENT_VARIABLE
      %unset NETCDF_X_POSITION_VARIABLE
      %unset NETCDF_Y_POSITION_VARIABLE
diff --git a/src/Thermo/BufrThermo.cc b/src/Thermo/BufrThermo.cc
index 2010882..4af2614 100644
--- a/src/Thermo/BufrThermo.cc
+++ b/src/Thermo/BufrThermo.cc
@@ -36,23 +36,47 @@ BufrThermo::BufrThermo(const char* kw) :
 }
 
 void
-BufrThermo::initialiseDataMemory()
+BufrThermo::allocateDataMemory()
 {
       pCount_ = 0;
       T_.clear(); TD_.clear();
       U_.clear(); V_.clear();
       P_.clear();
+
+      // Allocate memory
+      if ( nlev_ > 0 )
+      {
+         T_.resize(nlev_);
+         TD_.resize(nlev_);
+         U_.resize(nlev_);
+         V_.resize(nlev_);
+         P_.resize(nlev_);
+      }
+}
+
+void
+BufrThermo::initialiseDataMemory()
+{
+      pCount_ = 0;
+      for ( int i = 0; i < nlev_; i++ )
+      {
+         T_[i]  = MissingValue;
+         TD_[i] = MissingValue;
+         U_[i]  = MissingValue;
+         V_[i]  = MissingValue;
+         P_[i]  = MissingValue;
+      }
 }
 
 bool BufrThermo::getAppParameters( MvRequest& in )
 {
    // Get station input parameter
-   if ( !in.countValues("STATION") )
+   station_ = in.getSubrequest("STATION");
+   if ( !station_ )
    {
       setError(1,"Thermo ERROR: No Station info specified!");
       return false;
    }
-   in.getValue(station_,"STATION");
 
    return true;
 }
@@ -98,6 +122,14 @@ bool BufrThermo::processData()
    // Remove this function after updating library MvNetCDF to create
    // files of type Netcdf4 (allowing multiple unlimited dimensions)
    nlev_ = this->evaluateNLevels(iter);
+   if ( nlev_ <= 0 )
+   {
+      setError(0,"Thermo: No Levels found" );
+      return false;
+   }
+
+   // Allocate memory
+   this->allocateDataMemory();
 
    // Main loop
    // Compute data values
@@ -115,11 +147,11 @@ bool BufrThermo::processData()
 
       //obs.printAllValues();
 
-      // Initialise data values storage
+      // Initialise data values storage with MissingValue
       this->initialiseDataMemory();
 
       // Get/compute data values for all pressure levels
-      double val;
+      int ic = 0;
       float PrevLevel = FLT_MAX;
       float flevel = obs.firstPressureLevel();
       while( flevel != MissingValue )
@@ -137,29 +169,25 @@ bool BufrThermo::processData()
          float myStr = obs.valueByPressureLevel( flevel, obsStrength);
 
          // Temperatura value
-         val = ( myT == MissingValue ) ? MissingValue : myT - K2C;
-         T_.push_back(val);
+         if ( myT != MissingValue )
+            T_[ic] = myT - K2C;
 
          // Dewpoint value
-         val = ( myDew == MissingValue ) ? MissingValue : myDew - K2C;
-         TD_.push_back(val);
+         if ( myDew != MissingValue )
+         TD_[ic] = myDew - K2C;
 
          // Wind values
-         if ( myDir == MissingValue )
-         {
-            U_.push_back(MissingValue);
-            V_.push_back(MissingValue);
-         }
-         else
+         if ( myDir != MissingValue )
          {
-            U_.push_back( -myStr * sin(myDir*PI/180.0) );
-            V_.push_back( -myStr * cos(myDir*PI/180.0) );
+            U_[ic] = -myStr * sin(myDir*PI/180.0);
+            V_[ic] = -myStr * cos(myDir*PI/180.0);
          }
 
          // Pressure value
-         P_.push_back(flevel);
+         P_[ic] = flevel;
          pCount_++;
 
+         ic++;
          PrevLevel = flevel;
          flevel = obs.nextPressureLevel();
       } // end while
@@ -171,18 +199,6 @@ bool BufrThermo::processData()
          return false;
       }
 
-      // Fill the data arrays with missing values, since nlev_ (calculated
-      // maximum number of levels) may be bigger than pCount_ (number of levels
-      // of a given message
-      for ( int i = pCount_; i < nlev_; i++ )
-      {
-         T_[i]  = MissingValue;
-         TD_[i] = MissingValue;
-         U_[i]  = MissingValue;
-         V_[i]  = MissingValue;
-         P_[i]  = MissingValue;
-      }
-
       // Write info to the netCDF file
       if ( !this->generate(netcdf,obs) )
       {
@@ -340,10 +356,12 @@ bool BufrThermo::createOutputRequest(MvRequest& out)
    ncDataReq("TEMPORARY") = 1;
 
    // Create Temperature output request
+   int thermoId = rand() % 10000;
    MvRequest dReq("NETCDF_XY_POINTS");
    dReq("NETCDF_DATA") = ncDataReq;
    dReq("NETCDF_Y_VARIABLE") = sPRESSURE.c_str();
    dReq("NETCDF_X_VARIABLE") = sTEMP.c_str();
+   dReq("_MODULEID") = thermoId;
 
    MvRequest gReq("MGRAPH");
    gReq("GRAPH_LINE_COLOUR") = "red";
@@ -351,6 +369,8 @@ bool BufrThermo::createOutputRequest(MvRequest& out)
    gReq("GRAPH_MISSING_DATA_MODE") = "join";
    gReq("GRAPH_MISSING_DATA_STYLE") = "solid";
    gReq("GRAPH_MISSING_DATA_THICKNESS") = 8;
+   gReq("_CLASS") = "MGRAPH";
+   gReq("_MODULEID") = thermoId;
    MvRequest dataReq = dReq + gReq;
 
    // Create Dewpoint output request
@@ -366,21 +386,22 @@ bool BufrThermo::createOutputRequest(MvRequest& out)
    wdReq("NETCDF_X_POSITION_VARIABLE")  = sXWIND.c_str();
    wdReq("NETCDF_X_COMPONENT_VARIABLE") = sU.c_str();
    wdReq("NETCDF_Y_COMPONENT_VARIABLE") = sV.c_str();
+   wdReq("_MODULEID") = thermoId;
 
    MvRequest wReq("MWIND");
    wReq("WIND_FIELD_TYPE")  = "flags";
    wReq("WIND_FLAG_COLOUR") = "black";
+   wReq("_CLASS") = "MWIND";
+   wReq("_MODULEID") = thermoId;
 
    dataReq = dataReq + dReq + gReq + wdReq + wReq;
 
-   // Create customised Cartesian View request.
-   // If an icon was dropped into a view, uPlot will ignore it.
-   // Mode-specific options
-   MvRequest viewReq("CARTESIANVIEW");
-   viewReq("MAP_PROJECTION") = "tephigram";
+   // Create a default ThermoView request
+   MvRequest viewReq("THERMOVIEW");
    //viewReq("X_AUTOMATIC") = "on";  //Not working 20140304, Sylvie is going to fixed.
-   viewReq("X_MIN") = -40;  //Remove this later when the X_AUTOMATIC problem is fixed.
-   viewReq("X_MAX") = -40;
+   viewReq("MINIMUM_TEMPERATURE") = -40;  //Remove this when the X_AUTOMATIC problem is fixed.
+   viewReq("MAXIMUM_TEMPERATURE") = -40;
+   viewReq("_MODULEID") = thermoId;
 
    // If action is not visualisation related then return the netcdf data.
    // Also, add the visualisation and original requests as hidden parameters.
@@ -388,20 +409,27 @@ bool BufrThermo::createOutputRequest(MvRequest& out)
    if ( !this->isVisualise() )
    {
       out = ncDataReq;
-//      ncDataReq("_VIEW") = view_.c_str();
-//      ncDataReq("_VISUALISE") = out1;
-//      ncDataReq("_CARTESIANVIEW") = viewReq;
-//      ncDataReq("_ORIGINAL_REQUEST") = origReq_;
+      out("_VIEW") = "THERMOVIEW";
+      out("_VISUALISE") = dataReq;
+      out("_CARTESIANVIEW") = viewReq;
+      out("_ORIGINAL_REQUEST") = origReq_;
+      out("_MODULEID") = thermoId;
+
       return true;
    }
 
-   // Create title information
+   // Add title information.
+   // It must be positioned before the Data+Visdef set of requests to avoid the
+   // following problem in uPlot: if another visdef (MGRAPH or MWIND) is defined
+   // after the GribThermo requests then it will not be associated to the GribThermo's
+   // output data because the existence of a MTEXT request between them.
    MvRequest titleReq("MTEXT");
    titleReq("TEXT_LINE_1") = this->title().c_str();
    titleReq("TEXT_FONT_SIZE") = 0.5;
+   titleReq("_MODULEID") = thermoId;
 
    // Final output request
-   out = viewReq + dataReq + titleReq;
+   out = viewReq + titleReq + dataReq;
 
    return true;
 }
diff --git a/src/Thermo/BufrThermo.h b/src/Thermo/BufrThermo.h
index f37b9d3..b4961ff 100644
--- a/src/Thermo/BufrThermo.h
+++ b/src/Thermo/BufrThermo.h
@@ -27,6 +27,9 @@ public:
    // Destructor
    ~BufrThermo() {}
 
+   // Allocate data values storage
+   void allocateDataMemory();
+
    // Initialise data values storage
    void initialiseDataMemory();
 
diff --git a/src/Thermo/CMakeLists.txt b/src/Thermo/CMakeLists.txt
index 934a34b..82d7e16 100644
--- a/src/Thermo/CMakeLists.txt
+++ b/src/Thermo/CMakeLists.txt
@@ -19,7 +19,14 @@ metview_module_files(ETC_FILES ObjectSpec.Thermo
                                ThermoViewRules
                                ThermoDataDef
                                ThermoDataRules
-                               
+                               MTHERMOGRIDDef
+                               MTHERMOGRIDRules
+                               MThermoDef
+                               MThermoRules
+
                      XPM_FILES THERMOVIEW.xpm
                                THERMODATA.xpm
+
+                     SVG_FILES MTHERMOGRID.svg
+                               MTHERMO.svg
                     )
diff --git a/src/Thermo/GribThermo.cc b/src/Thermo/GribThermo.cc
index a235150..5dd9908 100644
--- a/src/Thermo/GribThermo.cc
+++ b/src/Thermo/GribThermo.cc
@@ -323,15 +323,18 @@ bool GribThermo::createOutputRequest(MvRequest& out)
    ncDataReq("TEMPORARY") = 1;
 
    // Create Temperature output request
+   int thermoId = rand() % 10000;
    MvRequest outd("NETCDF_XY_POINTS");
    outd("NETCDF_DATA") = ncDataReq;
    outd("NETCDF_Y_VARIABLE") = sPRESSURE.c_str();
    outd("NETCDF_X_VARIABLE") = sTEMP.c_str();
+   outd("_MODULEID") = thermoId;
 
    MvRequest gReq("MGRAPH");
    gReq("GRAPH_LINE_COLOUR") = "red";
    gReq("GRAPH_LINE_THICKNESS") = 8;
    gReq("_CLASS") = "MGRAPH";
+   gReq("_MODULEID") = thermoId;
    outd = outd + gReq;
 
    // Create Dewpoint output request
@@ -339,6 +342,7 @@ bool GribThermo::createOutputRequest(MvRequest& out)
    outtd("NETCDF_DATA") = ncDataReq;
    outtd("NETCDF_Y_VARIABLE") = sPRESSURE.c_str();
    outtd("NETCDF_X_VARIABLE") = sDEWPOINT.c_str();
+   outtd("_MODULEID") = thermoId;
 
    gReq("GRAPH_LINE_COLOUR") = "red";
    gReq("GRAPH_LINE_STYLE") = "dash",
@@ -354,22 +358,20 @@ bool GribThermo::createOutputRequest(MvRequest& out)
       outw("NETCDF_Y_POSITION_VARIABLE")  = sPWIND.c_str();
       outw("NETCDF_X_COMPONENT_VARIABLE") = sU.c_str();
       outw("NETCDF_Y_COMPONENT_VARIABLE") = sV.c_str();
+      outw("_MODULEID") = thermoId;
 
       MvRequest wReq("MWIND");
       wReq("WIND_FIELD_TYPE")  = "flags";
       wReq("WIND_FLAG_COLOUR") = "black";
       wReq("_CLASS") = "MWIND";
+      wReq("_MODULEID") = thermoId;
 
       outd = outd + outw + wReq;
    }
-   // Create customised Cartesian View request.
-   // If an icon was dropped into a view, uPlot will ignore it.
-   // Mode-specific options
-   MvRequest viewReq("CARTESIANVIEW");
-   viewReq("MAP_PROJECTION") = "tephigram";
-   viewReq("Y_AUTOMATIC") = "off";    // remove these command when Magics is updated
-   viewReq("Y_MIN") = 1015;           // At the moment, the default value in Magics is 200
-   viewReq("Y_MAX") = 100;
+
+   // Create a default THERMOVIEW request
+   MvRequest viewReq("THERMOVIEW");
+   viewReq("_MODULEID") = thermoId;
 
    // If action is not visualisation related then return the netcdf data.
    // Also, add the visualisation and original requests as hidden parameters.
@@ -377,20 +379,27 @@ bool GribThermo::createOutputRequest(MvRequest& out)
    if ( !this->isVisualise() )
    {
       out = ncDataReq;
-//      ncDataReq("_VIEW") = view_.c_str();
-//      ncDataReq("_VISUALISE") = out1;
-//      ncDataReq("_CARTESIANVIEW") = viewReq;
-//      ncDataReq("_ORIGINAL_REQUEST") = origReq_;
+      out("_VIEW") = "THERMOVIEW";
+      out("_VISUALISE") = outd;
+      out("_CARTESIANVIEW") = viewReq;
+      out("_ORIGINAL_REQUEST") = origReq_;
+      out("_MODULEID") = thermoId;
+
       return true;
    }
 
-   // Create title information
+   // Add title information.
+   // It must be positioned before the Data+Visdef set of requests to avoid the
+   // following problem in uPlot: if another visdef (MGRAPH or MWIND) is defined
+   // after the GribThermo requests then it will not be associated to the GribThermo's
+   // output data because the existence of a MTEXT request between them.
    MvRequest titleReq("MTEXT");
    titleReq("TEXT_LINE_1") = title_.c_str();
    titleReq("TEXT_FONT_SIZE") = 0.5;
+   titleReq("_MODULEID") = thermoId;
 
    // Final output request
-   out = viewReq + outd + titleReq;
+   out = viewReq + titleReq + outd;
 
    return true;
 }
diff --git a/src/Thermo/MTHERMO.svg b/src/Thermo/MTHERMO.svg
new file mode 100644
index 0000000..663c3aa
--- /dev/null
+++ b/src/Thermo/MTHERMO.svg
@@ -0,0 +1,390 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   inkscape:export-ydpi="180"
+   inkscape:export-xdpi="180"
+   width="32"
+   height="32"
+   id="svg11300"
+   sodipodi:version="0.32"
+   inkscape:version="0.48.4 r9939"
+   sodipodi:docname="MTHERMO.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape"
+   version="1.0"
+   style="display:inline">
+  <sodipodi:namedview
+     stroke="#3465a4"
+     fill="#729fcf"
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="0.25490196"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="16.15625"
+     inkscape:cx="19.34236"
+     inkscape:cy="13.505245"
+     inkscape:current-layer="layer1"
+     showgrid="true"
+     inkscape:grid-bbox="false"
+     inkscape:document-units="px"
+     inkscape:showpageshadow="false"
+     inkscape:window-width="1920"
+     inkscape:window-height="1152"
+     inkscape:window-x="-3"
+     inkscape:window-y="-3"
+     gridtolerance="50"
+     inkscape:grid-points="false"
+     showguides="true"
+     inkscape:guide-bbox="true"
+     objecttolerance="0.4"
+     inkscape:object-paths="true"
+     width="32px"
+     height="32px"
+     inkscape:window-maximized="1"
+     inkscape:snap-grids="false"
+     inkscape:snap-to-guides="false">
+    <sodipodi:guide
+       orientation="horizontal"
+       position="50.977307"
+       id="guide9112" />
+    <inkscape:grid
+       type="xygrid"
+       id="grid2849" />
+  </sodipodi:namedview>
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title />
+        <cc:license
+           rdf:resource="Apache License 2.0" />
+        <dc:creator>
+          <cc:Agent>
+            <dc:title />
+          </cc:Agent>
+        </dc:creator>
+        <dc:publisher>
+          <cc:Agent>
+            <dc:title>ECMWF</dc:title>
+          </cc:Agent>
+        </dc:publisher>
+        <dc:language>en-GB</dc:language>
+        <dc:subject>
+          <rdf:Bag>
+            <rdf:li>Metview icon</rdf:li>
+          </rdf:Bag>
+        </dc:subject>
+        <dc:description>Metview icon</dc:description>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+     id="defs3">
+    <linearGradient
+       id="linearGradient3869">
+      <stop
+         style="stop-color:#fffa02;stop-opacity:1;"
+         offset="0"
+         id="stop3871" />
+      <stop
+         style="stop-color:#dddb31;stop-opacity:1;"
+         offset="1"
+         id="stop3873" />
+    </linearGradient>
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3869"
+       id="linearGradient3875"
+       x1="19.671978"
+       y1="7.6915169"
+       x2="22.446272"
+       y2="10.200515"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="translate(-0.06189555,0.99032878)" />
+    <linearGradient
+       y2="11.078368"
+       x2="22.297274"
+       y1="8.1580601"
+       x1="7.6711636"
+       gradientTransform="translate(-0.912603,0.70904558)"
+       gradientUnits="userSpaceOnUse"
+       id="linearGradient4175-46"
+       xlink:href="#linearGradient3889-7-1-2-9"
+       inkscape:collect="always" />
+    <linearGradient
+       id="linearGradient3889-7-1-2-9">
+      <stop
+         style="stop-color:#cfc0af;stop-opacity:1;"
+         offset="0"
+         id="stop3891-7-1-5-2" />
+      <stop
+         style="stop-color:#ffe2ab;stop-opacity:1;"
+         offset="1"
+         id="stop3893-5-0-8-24" />
+    </linearGradient>
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3889-8-5-7"
+       id="linearGradient4197-7"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="translate(-0.23428491,0.99686468)"
+       x1="8.2786636"
+       y1="12.442157"
+       x2="29.438562"
+       y2="12.071977" />
+    <linearGradient
+       id="linearGradient3889-8-5-7">
+      <stop
+         style="stop-color:#cfc0af;stop-opacity:1;"
+         offset="0"
+         id="stop3891-0-0-5" />
+      <stop
+         style="stop-color:#ffe2ab;stop-opacity:1;"
+         offset="1"
+         id="stop3893-2-6-4" />
+    </linearGradient>
+  </defs>
+  <g
+     inkscape:groupmode="layer"
+     id="layer3"
+     inkscape:label="frame"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:#aa4400;fill-opacity:0;stroke:#ffffcc;stroke-width:0.89999998;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0;stroke-dashoffset:0"
+       d="m 4.5449877,0.41131106 27.0025713,0 0,31.15167094 -31.13624794,0 L 0.45244217,4.4293064 4.5449877,0.41131106 z"
+       id="rect2911"
+       sodipodi:nodetypes="cccccc"
+       inkscape:connector-curvature="0" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4023"
+       width="31.876209"
+       height="31.876209"
+       x="0.061895553"
+       y="-7.1054274e-15" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4025"
+       width="19.249516"
+       height="17.702127"
+       x="-6.3752418"
+       y="8.727273" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4027"
+       width="16.030949"
+       height="15.226306"
+       x="-16.897486"
+       y="17.887814" />
+    <rect
+       style="fill:#ff0000;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4029"
+       width="20.363636"
+       height="13.245648"
+       x="-19.868471"
+       y="17.702127" />
+    <path
+       sodipodi:type="star"
+       style="fill:#ff5555;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="path4033"
+       sodipodi:sides="5"
+       sodipodi:cx="-19.125725"
+       sodipodi:cy="7.2417793"
+       sodipodi:r1="26.745827"
+       sodipodi:r2="13.372913"
+       sodipodi:arg1="0.98471927"
+       sodipodi:arg2="1.6130378"
+       inkscape:flatsided="false"
+       inkscape:rounded="0"
+       inkscape:randomized="0"
+       d="m -4.3326878,29.524178 -15.3577602,-8.921414 -16.055798,7.59367 3.738961,-17.362968 -12.183524,-12.9233971 17.668566,-1.8094891 8.525965,-15.5807688 7.180814,16.2446412 L 6.6373958,0.05840507 -6.5931829,11.907635 z"
+       inkscape:transform-center-x="-0.34901834"
+       inkscape:transform-center-y="-2.2197847" />
+    <path
+       style="fill:#ffffcc;fill-opacity:1;stroke:none"
+       d="m 2.7234043,2.5377176 -2.21998959,2.1044323 0.0536453,26.9646341 30.88587999,0 0,-31.11161959 -26.7388781,0.1237911 z"
+       id="path4046"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="ccccccc" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer17"
+     inkscape:label="wmo"
+     style="display:inline">
+    <path
+       style="fill:#0000ff;stroke:#0000ff;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
+       d="M 3.8215805,3.883476 31.458884,31.211302"
+       id="path3226"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="cc" />
+    <path
+       style="fill:none;stroke:#0000ff;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
+       d="M 0.30947776,18.382979 C 13.059961,31.195358 13.49323,31.628627 13.49323,31.628627"
+       id="path3996"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="cc" />
+    <path
+       style="fill:none;stroke:#0000ff;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
+       d="M 18.630561,0.55705996 C 31.381044,12.502901 31.381044,12.502901 31.381044,12.502901"
+       id="path3998"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:none;stroke:#f30000;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
+       d="m 24.634429,0.68085106 c 0,0 -6.213239,4.58150524 -11.26499,14.35976794 -5.0517513,9.778262 -5.6943906,16.464217 -5.6943906,16.464217"
+       id="path4000"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="czc" />
+    <path
+       style="fill:none;stroke:#f30000;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none"
+       d="m 31.566731,14.235977 c 0,0 -3.268939,3.69194 -5.199226,7.241779 -1.930288,3.54984 -2.970987,9.965184 -2.970987,9.965184 l -0.06189,0.0619"
+       id="path4002"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="czcc" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer1"
+     inkscape:label="profile"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:none;stroke:#eb0f04;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0"
+       d="m 10.769826,0.74274662 c 0,0 -3.5119695,3.89934018 -3.7756287,6.49903288 -0.2636592,2.5996927 2.8697721,5.2483495 2.5996131,7.7369435 -0.270159,2.488594 -3.0884165,3.617551 -2.7234042,5.818182 0.3650122,2.200632 4.8278528,5.01354 4.8278528,5.01354 l 5.261122,5.570599"
+       id="path3145"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="czzzcc" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer13"
+     inkscape:label="pencil"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:url(#linearGradient3875);fill-opacity:1;stroke:#030000;stroke-width:0.80000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+       d="M 26.385405,2.5533108 14.539646,14.028888 13.141188,17.483902 16.760726,16.044312 28.359698,4.5276038 c 0,0 -0.401184,-0.8947574 -0.74036,-1.2339332 C 27.280162,2.9544948 26.385405,2.5533108 26.385405,2.5533108 z"
+       id="path3867"
+       sodipodi:nodetypes="cccccsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#6c5353;fill-opacity:1;stroke:none"
+       d="M 27.59738,3.7774139 15.996886,15.343095 15.463703,14.755841 27.099652,3.003764 27.59738,3.7774139 z"
+       id="path3877"
+       sodipodi:nodetypes="ccccc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#c8a656;fill-opacity:1;stroke:none"
+       d="m 14.786433,14.316806 -0.781491,2.262211 2.385605,-0.699229 -1.604114,-1.562982 z"
+       id="path3883"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="m 14.416253,14.028888 0,0 z"
+       id="path3885"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#050505;fill-opacity:1;stroke:none"
+       d="m 14.087204,15.427346 -0.411311,1.48072 1.357326,-0.452442 -0.946015,-1.028278 z"
+       id="path3887"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer2"
+     inkscape:label="hand"
+     style="display:inline">
+    <rect
+       style="opacity:0.53603599;fill:none;stroke:none;display:inline"
+       id="rect2939"
+       width="2.2622108"
+       height="7.7326479"
+       x="28.946869"
+       y="12.422921" />
+    <path
+       style="fill:url(#linearGradient4197-7);fill-opacity:1;stroke:#000000;stroke-width:0.69999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 22.313954,10.737511 -0.01309,1.314106 c 0,0 -0.279375,0.695239 -0.498394,0.842143 -0.583486,0.391362 -1.682438,0.804466 -1.682438,0.804466 l -1.190713,-10e-7 c -0.520389,-0.02751 0.340234,-0.122332 -1.842144,-0.110299 l -0.542738,0.447381 c -0.176833,0.145764 -0.193333,0.469266 -0.123393,0.6875 0.08204,0.255999 0.596717,0.743084 0.596717,0.743084 0.01713,0.213098 1.145554,0.158656 1.615606,0.258523 l 1.113512,-0.06997 0.866726,0.176814 1.00482,0.516549 1.021369,0.5625 0.78125 [...]
+       id="path3960-0-4"
+       sodipodi:nodetypes="ccscccssccccccccssccccsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:url(#linearGradient4175-46);fill-opacity:1;stroke:#000000;stroke-width:0.69999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 21.09338,6.2952894 c 0,0 -0.864273,-0.2489256 -1.443927,0.044344 -0.70956,0.3589861 -2.635122,2.1909541 -2.635122,2.1909541 l -1.389702,1.256428 c 0,0 -1.104461,0.7803535 -1.329048,1.2927365 -0.140325,0.320144 -0.692423,1.042346 -0.434287,1.278035 0,0 0.242673,0.235308 0.772976,0.309047 0.530303,0.07374 1.389701,-0.638095 1.389701,-0.638095 l 1.53125,-1.374998 1.269762,-0.7417255 0.491726,-0.355239 0.278036,-0.217143 2.443099,-2.642618 C 21.255676,6.3335626 21.09338,6.2952894 [...]
+       id="path3983-4"
+       sodipodi:nodetypes="csccscsccccccc"
+       inkscape:connector-curvature="0" />
+    <rect
+       style="fill:#0d0b06;fill-opacity:1;fill-rule:evenodd;stroke:none;display:inline"
+       id="rect4212"
+       width="2.2210789"
+       height="7.4035988"
+       x="28.988001"
+       y="12.751971" />
+    <path
+       style="fill:none;stroke:#000000;stroke-width:0.09999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 18.369329,14.157079 -0.110147,1.037779 -0.734318,-0.01777 c 0,0 -0.389617,-0.174751 -0.477307,-0.328567 -0.07209,-0.126452 0,-0.418174 0,-0.418174 0,-0.155527 0.200218,-0.282651 0.367159,-0.358436 0.07557,-0.0343 0.25701,-0.02987 0.25701,-0.02987 l 0.697603,0.115036 z"
+       id="path4268"
+       sodipodi:nodetypes="cccssscc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;fill-opacity:1;stroke:none;display:inline"
+       d="m 28.782344,18.016748 0,-1.686372 -2.467866,0.04113 -1.398458,-0.452442 c 0,0 -0.964908,-0.709613 -1.521851,-0.904884 -0.470245,-0.164874 -1.033801,-0.288768 -1.562982,-0.37018 l -1.069409,-0.164524 -0.987146,0 -1.316196,0.04113 0.08226,0.658097 0.946016,0.08226 0.987147,0.04113 1.028277,0.493573 c 0,0 0.584391,0.442159 0.904885,0.616967 0.339801,0.185339 1.069408,0.452442 1.069408,0.452442 l 1.231113,0.745142 c 0.388462,0.23512 0.810343,0.414981 1.236754,0.571053 0.387323,0.14 [...]
+       id="path4270"
+       sodipodi:nodetypes="ccccsscccccccscsscsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;stroke:none;display:inline"
+       d="m 15.003423,12.422922 c -0.287918,-0.109683 -0.575835,-0.219366 -0.863753,-0.329049 0.594291,-0.536642 1.20232,-1.058562 1.766868,-1.627072 0.444514,-0.42915 0.918257,-0.7067235 1.394946,-1.1008715 0.281295,-0.253216 0.653857,-0.536296 0.965672,-0.751322 0.400107,-0.287782 0.660647,-0.723125 1.092134,-0.964017 0.186134,-0.106708 0.365481,-0.235485 0.555742,-0.328776 0.268538,-0.01343 0.66047,0.01428 0.929008,8.5e-4 0.06855,0.08226 0.01371,0 0.08226,0.08226 -0.67532,0.662346 -1. [...]
+       id="path4274"
+       sodipodi:nodetypes="cccsssccccsscc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;stroke:none;display:inline"
+       d="m 22.98286,10.572022 0.658096,-0.6992275 c 0,0 0.02532,1.1696845 -0.123393,1.7275045 -0.113731,0.426608 -0.575836,1.192802 -0.575836,1.192802 l -1.110539,0.575836 c 0,0 0.682272,-0.768009 0.822621,-1.275065 0.140349,-0.507056 -0.08226,-1.110539 -0.08226,-1.110539 l 0.411311,-0.411311 z"
+       id="path3659-8"
+       sodipodi:nodetypes="ccscczcc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer4"
+     inkscape:label="top frame"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:none;stroke:#27324e;stroke-width:0.89999998;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dashoffset:0;display:inline"
+       d="m 4.544988,0.45511225 27.002571,0 0,31.15167175 -31.136248,0 0.04113,-27.1336764 4.092546,-4.01799535 z"
+       id="rect2911-2"
+       sodipodi:nodetypes="cccccc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer5"
+     inkscape:label="tri"
+     style="display:inline">
+    <path
+       style="fill:#27324e;fill-opacity:1;fill-rule:evenodd;stroke:none;display:inline"
+       d="M 5.0100774,0.40809484 5.0020674,5.0387137 0.43672699,4.9993417 5.0100732,0.40809454 z"
+       id="path4199-9"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+  </g>
+</svg>
diff --git a/src/Thermo/MTHERMOGRID.svg b/src/Thermo/MTHERMOGRID.svg
new file mode 100644
index 0000000..cbb479e
--- /dev/null
+++ b/src/Thermo/MTHERMOGRID.svg
@@ -0,0 +1,377 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   inkscape:export-ydpi="180"
+   inkscape:export-xdpi="180"
+   width="32"
+   height="32"
+   id="svg11300"
+   sodipodi:version="0.32"
+   inkscape:version="0.48.4 r9939"
+   sodipodi:docname="THERMOGRID.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape"
+   version="1.0"
+   style="display:inline">
+  <sodipodi:namedview
+     stroke="#3465a4"
+     fill="#729fcf"
+     id="base"
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="0.25490196"
+     inkscape:pageopacity="0.0"
+     inkscape:pageshadow="2"
+     inkscape:zoom="16.15625"
+     inkscape:cx="0.11733392"
+     inkscape:cy="13.505245"
+     inkscape:current-layer="layer5"
+     showgrid="true"
+     inkscape:grid-bbox="false"
+     inkscape:document-units="px"
+     inkscape:showpageshadow="false"
+     inkscape:window-width="1920"
+     inkscape:window-height="1152"
+     inkscape:window-x="-3"
+     inkscape:window-y="-3"
+     gridtolerance="50"
+     inkscape:grid-points="false"
+     showguides="true"
+     inkscape:guide-bbox="true"
+     objecttolerance="0.4"
+     inkscape:object-paths="true"
+     width="32px"
+     height="32px"
+     inkscape:window-maximized="1"
+     inkscape:snap-grids="false"
+     inkscape:snap-to-guides="false">
+    <sodipodi:guide
+       orientation="horizontal"
+       position="50.977307"
+       id="guide9112" />
+    <inkscape:grid
+       type="xygrid"
+       id="grid2849" />
+  </sodipodi:namedview>
+  <metadata
+     id="metadata7">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title></dc:title>
+        <cc:license
+           rdf:resource="Apache License 2.0" />
+        <dc:creator>
+          <cc:Agent>
+            <dc:title />
+          </cc:Agent>
+        </dc:creator>
+        <dc:publisher>
+          <cc:Agent>
+            <dc:title>ECMWF</dc:title>
+          </cc:Agent>
+        </dc:publisher>
+        <dc:language>en-GB</dc:language>
+        <dc:subject>
+          <rdf:Bag>
+            <rdf:li>Metview icon</rdf:li>
+          </rdf:Bag>
+        </dc:subject>
+        <dc:description>Metview icon</dc:description>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+     id="defs3">
+    <linearGradient
+       id="linearGradient3869">
+      <stop
+         style="stop-color:#fffa02;stop-opacity:1;"
+         offset="0"
+         id="stop3871" />
+      <stop
+         style="stop-color:#dddb31;stop-opacity:1;"
+         offset="1"
+         id="stop3873" />
+    </linearGradient>
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3869"
+       id="linearGradient3875"
+       x1="19.671978"
+       y1="7.6915169"
+       x2="22.446272"
+       y2="10.200515"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="translate(-0.06189555,0.99032878)" />
+    <linearGradient
+       y2="11.078368"
+       x2="22.297274"
+       y1="8.1580601"
+       x1="7.6711636"
+       gradientTransform="translate(-0.912603,0.70904558)"
+       gradientUnits="userSpaceOnUse"
+       id="linearGradient4175-46"
+       xlink:href="#linearGradient3889-7-1-2-9"
+       inkscape:collect="always" />
+    <linearGradient
+       id="linearGradient3889-7-1-2-9">
+      <stop
+         style="stop-color:#cfc0af;stop-opacity:1;"
+         offset="0"
+         id="stop3891-7-1-5-2" />
+      <stop
+         style="stop-color:#ffe2ab;stop-opacity:1;"
+         offset="1"
+         id="stop3893-5-0-8-24" />
+    </linearGradient>
+    <linearGradient
+       inkscape:collect="always"
+       xlink:href="#linearGradient3889-8-5-7"
+       id="linearGradient4197-7"
+       gradientUnits="userSpaceOnUse"
+       gradientTransform="translate(-0.23428491,0.99686468)"
+       x1="8.2786636"
+       y1="12.442157"
+       x2="29.438562"
+       y2="12.071977" />
+    <linearGradient
+       id="linearGradient3889-8-5-7">
+      <stop
+         style="stop-color:#cfc0af;stop-opacity:1;"
+         offset="0"
+         id="stop3891-0-0-5" />
+      <stop
+         style="stop-color:#ffe2ab;stop-opacity:1;"
+         offset="1"
+         id="stop3893-2-6-4" />
+    </linearGradient>
+  </defs>
+  <g
+     inkscape:groupmode="layer"
+     id="layer3"
+     inkscape:label="frame"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:#aa4400;fill-opacity:0;stroke:#ffffcc;stroke-width:0.89999998;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:0;stroke-dashoffset:0"
+       d="m 4.5449877,0.41131106 27.0025713,0 0,31.15167094 -31.13624794,0 L 0.45244217,4.4293064 4.5449877,0.41131106 z"
+       id="rect2911"
+       sodipodi:nodetypes="cccccc"
+       inkscape:connector-curvature="0" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4023"
+       width="31.876209"
+       height="31.876209"
+       x="0.061895553"
+       y="-7.1054274e-15" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4025"
+       width="19.249516"
+       height="17.702127"
+       x="-6.3752418"
+       y="8.727273" />
+    <rect
+       style="fill:#ffb380;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4027"
+       width="16.030949"
+       height="15.226306"
+       x="-16.897486"
+       y="17.887814" />
+    <rect
+       style="fill:#ff0000;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="rect4029"
+       width="20.363636"
+       height="13.245648"
+       x="-19.868471"
+       y="17.702127" />
+    <path
+       sodipodi:type="star"
+       style="fill:#ff5555;fill-opacity:0;stroke:#ffffcc;stroke-opacity:0"
+       id="path4033"
+       sodipodi:sides="5"
+       sodipodi:cx="-19.125725"
+       sodipodi:cy="7.2417793"
+       sodipodi:r1="26.745827"
+       sodipodi:r2="13.372913"
+       sodipodi:arg1="0.98471927"
+       sodipodi:arg2="1.6130378"
+       inkscape:flatsided="false"
+       inkscape:rounded="0"
+       inkscape:randomized="0"
+       d="m -4.3326878,29.524178 -15.3577602,-8.921414 -16.055798,7.59367 3.738961,-17.362968 -12.183524,-12.9233971 17.668566,-1.8094891 8.525965,-15.5807688 7.180814,16.2446412 L 6.6373958,0.05840507 -6.5931829,11.907635 z"
+       inkscape:transform-center-x="-0.34901834"
+       inkscape:transform-center-y="-2.2197847" />
+    <path
+       style="fill:#ffffcc;fill-opacity:1;stroke:none"
+       d="m 2.7234043,2.5377176 -2.21998959,2.1044323 0.0536453,26.9646341 30.88587999,0 0,-31.11161959 -26.7388781,0.1237911 z"
+       id="path4046"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="ccccccc" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer17"
+     inkscape:label="wmo"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:#0000ff;stroke:#0000ff;stroke-width:0.96811259px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="M 3.8215805,3.883476 31.458884,31.211302"
+       id="path3226"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="cc" />
+    <path
+       style="fill:none;stroke:#0000ff;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="M 0.30947776,18.382979 C 13.059961,31.195358 13.49323,31.628627 13.49323,31.628627"
+       id="path3996"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="cc" />
+    <path
+       style="fill:none;stroke:#0000ff;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="M 18.630561,0.55705996 C 31.381044,12.502901 31.381044,12.502901 31.381044,12.502901"
+       id="path3998"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:none;stroke:#f30000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="m 24.634429,0.68085106 c 0,0 -6.213239,4.58150524 -11.26499,14.35976794 -5.0517513,9.778262 -5.6943906,16.464217 -5.6943906,16.464217"
+       id="path4000"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="czc" />
+    <path
+       style="fill:none;stroke:#f30000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="m 31.566731,14.235977 c 0,0 -3.268939,3.69194 -5.199226,7.241779 -1.930288,3.54984 -2.970987,9.965184 -2.970987,9.965184 l -0.06189,0.0619"
+       id="path4002"
+       inkscape:connector-curvature="0"
+       sodipodi:nodetypes="czcc" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer13"
+     inkscape:label="pencil"
+     style="display:inline">
+    <path
+       style="fill:url(#linearGradient3875);fill-opacity:1;stroke:#030000;stroke-width:0.80000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+       d="M 26.385405,2.5533108 14.539646,14.028888 13.141188,17.483902 16.760726,16.044312 28.359698,4.5276038 c 0,0 -0.401184,-0.8947574 -0.74036,-1.2339332 C 27.280162,2.9544948 26.385405,2.5533108 26.385405,2.5533108 z"
+       id="path3867"
+       sodipodi:nodetypes="cccccsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#6c5353;fill-opacity:1;stroke:none"
+       d="M 28.03065,4.3963695 16.430156,15.96205 15.896973,15.374796 27.532922,3.6227196 28.03065,4.3963695 z"
+       id="path3877"
+       sodipodi:nodetypes="ccccc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#c8a656;fill-opacity:1;stroke:none"
+       d="m 14.786433,14.316806 -0.781491,2.262211 2.385605,-0.699229 -1.604114,-1.562982 z"
+       id="path3883"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       d="m 14.416253,14.028888 0,0 z"
+       id="path3885"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#050505;fill-opacity:1;stroke:none"
+       d="m 14.087204,15.427346 -0.411311,1.48072 1.357326,-0.452442 -0.946015,-1.028278 z"
+       id="path3887"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer2"
+     inkscape:label="hand"
+     style="display:inline">
+    <rect
+       style="opacity:0.53603599;fill:none;stroke:none;display:inline"
+       id="rect2939"
+       width="2.2622108"
+       height="7.7326479"
+       x="28.946869"
+       y="12.422921" />
+    <path
+       style="fill:url(#linearGradient4197-7);fill-opacity:1;stroke:#000000;stroke-width:0.69999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 22.313954,10.737511 -0.01309,1.314106 c 0,0 -0.279375,0.695239 -0.498394,0.842143 -0.583486,0.391362 -1.682438,0.804466 -1.682438,0.804466 l -1.190713,-10e-7 c -0.520389,-0.02751 0.340234,-0.122332 -1.842144,-0.110299 l -0.542738,0.447381 c -0.176833,0.145764 -0.193333,0.469266 -0.123393,0.6875 0.08204,0.255999 0.596717,0.743084 0.596717,0.743084 0.01713,0.213098 1.145554,0.158656 1.615606,0.258523 l 1.113512,-0.06997 0.866726,0.176814 1.00482,0.516549 1.021369,0.5625 0.78125 [...]
+       id="path3960-0-4"
+       sodipodi:nodetypes="ccscccssccccccccssccccsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:url(#linearGradient4175-46);fill-opacity:1;stroke:#000000;stroke-width:0.69999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 21.09338,6.2952894 c 0,0 -0.864273,-0.2489256 -1.443927,0.044344 -0.70956,0.3589861 -2.635122,2.1909541 -2.635122,2.1909541 l -1.389702,1.256428 c 0,0 -1.104461,0.7803535 -1.329048,1.2927365 -0.140325,0.320144 -0.692423,1.042346 -0.434287,1.278035 0,0 0.242673,0.235308 0.772976,0.309047 0.530303,0.07374 1.389701,-0.638095 1.389701,-0.638095 l 1.53125,-1.374998 1.269762,-0.7417255 0.491726,-0.355239 0.278036,-0.217143 2.443099,-2.642618 C 21.255676,6.3335626 21.09338,6.2952894 [...]
+       id="path3983-4"
+       sodipodi:nodetypes="csccscsccccccc"
+       inkscape:connector-curvature="0" />
+    <rect
+       style="fill:#0d0b06;fill-opacity:1;fill-rule:evenodd;stroke:none;display:inline"
+       id="rect4212"
+       width="2.2210789"
+       height="7.4035988"
+       x="28.988001"
+       y="12.751971" />
+    <path
+       style="fill:none;stroke:#000000;stroke-width:0.09999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;display:inline"
+       d="m 18.369329,14.157079 -0.110147,1.037779 -0.734318,-0.01777 c 0,0 -0.389617,-0.174751 -0.477307,-0.328567 -0.07209,-0.126452 0,-0.418174 0,-0.418174 0,-0.155527 0.200218,-0.282651 0.367159,-0.358436 0.07557,-0.0343 0.25701,-0.02987 0.25701,-0.02987 l 0.697603,0.115036 z"
+       id="path4268"
+       sodipodi:nodetypes="cccssscc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;fill-opacity:1;stroke:none;display:inline"
+       d="m 28.782344,18.016748 0,-1.686372 -2.467866,0.04113 -1.398458,-0.452442 c 0,0 -0.964908,-0.709613 -1.521851,-0.904884 -0.470245,-0.164874 -1.033801,-0.288768 -1.562982,-0.37018 l -1.069409,-0.164524 -0.987146,0 -1.316196,0.04113 0.08226,0.658097 0.946016,0.08226 0.987147,0.04113 1.028277,0.493573 c 0,0 0.584391,0.442159 0.904885,0.616967 0.339801,0.185339 1.069408,0.452442 1.069408,0.452442 l 1.231113,0.745142 c 0.388462,0.23512 0.810343,0.414981 1.236754,0.571053 0.387323,0.14 [...]
+       id="path4270"
+       sodipodi:nodetypes="ccccsscccccccscsscsc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;stroke:none;display:inline"
+       d="m 15.003423,12.422922 c -0.287918,-0.109683 -0.575835,-0.219366 -0.863753,-0.329049 0.594291,-0.536642 1.20232,-1.058562 1.766868,-1.627072 0.444514,-0.42915 0.918257,-0.7067235 1.394946,-1.1008715 0.281295,-0.253216 0.653857,-0.536296 0.965672,-0.751322 0.400107,-0.287782 0.660647,-0.723125 1.092134,-0.964017 0.186134,-0.106708 0.365481,-0.235485 0.555742,-0.328776 0.268538,-0.01343 0.66047,0.01428 0.929008,8.5e-4 0.06855,0.08226 0.01371,0 0.08226,0.08226 -0.67532,0.662346 -1. [...]
+       id="path4274"
+       sodipodi:nodetypes="cccsssccccsscc"
+       inkscape:connector-curvature="0" />
+    <path
+       style="fill:#d6b370;stroke:none;display:inline"
+       d="m 22.98286,10.572022 0.658096,-0.6992275 c 0,0 0.02532,1.1696845 -0.123393,1.7275045 -0.113731,0.426608 -0.575836,1.192802 -0.575836,1.192802 l -1.110539,0.575836 c 0,0 0.682272,-0.768009 0.822621,-1.275065 0.140349,-0.507056 -0.08226,-1.110539 -0.08226,-1.110539 l 0.411311,-0.411311 z"
+       id="path3659-8"
+       sodipodi:nodetypes="ccscczcc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer4"
+     inkscape:label="top frame"
+     style="display:inline"
+     sodipodi:insensitive="true">
+    <path
+       style="fill:none;stroke:#27324e;stroke-width:0.89999998;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dashoffset:0;display:inline"
+       d="m 4.544988,0.45511225 27.002571,0 0,31.15167175 -31.136248,0 0.04113,-27.1336764 4.092546,-4.01799535 z"
+       id="rect2911-2"
+       sodipodi:nodetypes="cccccc"
+       inkscape:connector-curvature="0" />
+  </g>
+  <g
+     inkscape:groupmode="layer"
+     id="layer5"
+     inkscape:label="tri"
+     style="display:inline">
+    <path
+       style="fill:#27324e;fill-opacity:1;fill-rule:evenodd;stroke:none;display:inline"
+       d="M 5.0100774,0.40809484 5.0020674,5.0387137 0.43672699,4.9993417 5.0100732,0.40809454 z"
+       id="path4199-9"
+       sodipodi:nodetypes="cccc"
+       inkscape:connector-curvature="0" />
+  </g>
+</svg>
diff --git a/src/Thermo/MTHERMOGRIDDef b/src/Thermo/MTHERMOGRIDDef
new file mode 100644
index 0000000..511fe49
--- /dev/null
+++ b/src/Thermo/MTHERMOGRIDDef
@@ -0,0 +1,322 @@
+PARAMSHARE ; ParamShare; PARAMSHARE
+{
+	COLOUR {
+		%include MagicsColors.h
+	}
+	STYLE {
+		SOLID; SOLID
+		DASH; DASH
+		DOT; DOT
+		CHAIN_DOT; CHAIN_DOT
+		CHAIN_DASH; CHAIN_DASH
+	}
+}
+
+MTHERMOGRID; Magics; Automatically generated
+{
+	THERMO_ISOTHERM_GRID [ help_text = 'Plot the isotherms' ]
+ 	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
+	THERMO_ISOTHERM_COLOUR [ help = help_colour,interface = colour, help_text='Colou of the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_ISOTHERM_THICKNESS[ help_text = 'Thickness  of the isotherms' ]
+	{
+		*
+	} = 1
+
+	THERMO_ISOTHERM_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = SOLID
+
+	THERMO_ISOTHERM_INTERVAL[ help_text = 'interval for isotherms grid' ]
+	{
+		*
+	} = 10
+
+	THERMO_ISOTHERM_REFERENCE[ help_text = 'Reference   of the isotherms' ]
+	{
+		*
+	} = 0
+
+	THERMO_ISOTHERM_REFERENCE_COLOUR [ help = help_colour,interface = colour, help_text='Reference   of the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = RED
+
+	THERMO_ISOTHERM_REFERENCE_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = SOLID
+
+	THERMO_ISOTHERM_REFERENCE_THICKNESS[ help_text = 'Reference   of the isotherms' ]
+	{
+		*
+	} = 2
+
+	THERMO_ISOTHERM_LABEL_COLOUR [ help = help_colour,interface = colour, help_text='Label Colour for the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_ISOTHERM_LABEL_FONT_NAME
+	{
+		@
+	} = SANSERIF
+
+	THERMO_ISOTHERM_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
+	THERMO_ISOTHERM_LABEL_FONT_SIZE[ help_text = 'Font Size used for the isotherms labels' ]
+	{
+		*
+	} = 0.3
+
+	THERMO_ISOTHERM_LABEL_FREQUENCY[ help_text = 'Isotherm frequency for labelling' ]
+	{
+		*
+	} = 1
+
+	THERMO_ISOBAR_GRID [ help_text = 'Plot the isobars' ]
+ 	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
+	THERMO_ISOBAR_COLOUR [ help = help_colour,interface = colour, help_text='Colou of the isobars' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = EVERGREEN
+
+	THERMO_ISOBAR_THICKNESS[ help_text = 'Thickness  of the isobars' ]
+	{
+		*
+	} = 2
+
+	THERMO_ISOBAR_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = SOLID
+
+	THERMO_ISOBAR_INTERVAL[ help_text = 'Interval between isobars' ]
+	{
+		*
+	} = 100
+
+	THERMO_ISOBAR_REFERENCE[ help_text = 'Line Style  of the isobars' ]
+	{
+		*
+	} = 1000
+
+	THERMO_ISOBAR_LABEL_COLOUR [ help = help_colour,interface = colour, help_text='Label Colour for the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = EVERGREEN
+
+	THERMO_ISOBAR_LABEL_FONT_NAME
+	{
+		@
+	} = SANSERIF
+
+	THERMO_ISOBAR_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
+	THERMO_ISOBAR_LABEL_FONT_SIZE[ help_text = 'Font Size used for the isobars labels' ]
+	{
+		*
+	} = 0.3
+
+	THERMO_ISOBAR_LABEL_FREQUENCY[ help_text = 'isobar frequency for labelling' ]
+	{
+		*
+	} = 1
+
+	THERMO_DRY_ADIABATIC_GRID [ help_text = 'Plot the dry_adiabatics' ]
+ 	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
+	THERMO_DRY_ADIABATIC_COLOUR [ help = help_colour,interface = colour, help_text='Colou of the dry_adiabatics' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_DRY_ADIABATIC_THICKNESS[ help_text = 'Thickness  of the dry_adiabatics' ]
+	{
+		*
+	} = 1
+
+	THERMO_DRY_ADIABATIC_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = SOLID
+
+	THERMO_DRY_ADIABATIC_INTERVAL[ help_text = 'Interval between 2 dry_adiabatics.' ]
+	{
+		*
+	} = 10
+
+	THERMO_DRY_ADIABATIC_REFERENCE[ help_text = 'Reference   of the dry_adiabatics' ]
+	{
+		*
+	} = 0
+
+	THERMO_DRY_ADIABATIC_LABEL_COLOUR [ help = help_colour,interface = colour, help_text='Label Colour for the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_DRY_ADIABATIC_LABEL_FONT_NAME
+	{
+		@
+	} = SANSERIF
+
+	THERMO_DRY_ADIABATIC_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
+	THERMO_DRY_ADIABATIC_LABEL_FONT_SIZE[ help_text = 'Font Size used for the dry_adiabatics labels' ]
+	{
+		*
+	} = 0.3
+
+	THERMO_DRY_ADIABATIC_LABEL_FREQUENCY[ help_text = 'frequency for dry_adiabatic labelling' ]
+	{
+		*
+	} = 1
+
+	THERMO_SATURATED_ADIABATIC_GRID [ help_text = 'Plot the saturated_adiabatics' ]
+ 	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
+	THERMO_SATURATED_ADIABATIC_COLOUR [ help = help_colour,interface = colour, help_text='Colou of the saturated_adiabatics' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_SATURATED_ADIABATIC_THICKNESS[ help_text = 'Thickness  of the dry_adiabatics' ]
+	{
+		*
+	} = 2
+
+	THERMO_SATURATED_ADIABATIC_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = SOLID
+
+	THERMO_SATURATED_ADIABATIC_INTERVAL[ help_text = 'interval for saturated_adiabatics grid' ]
+	{
+		*
+	} = 5
+
+	THERMO_SATURATED_ADIABATIC_REFERENCE[ help_text = 'Reference   of the saturated_adiabatics' ]
+	{
+		*
+	} = 0
+
+	THERMO_SATURATED_ADIABATIC_LABEL_COLOUR [ help = help_colour,interface = colour, help_text='Label Colour for the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = CHARCOAL
+
+	THERMO_SATURATED_ADIABATIC_LABEL_FONT_NAME
+	{
+		@
+	} = SANSERIF
+
+	THERMO_SATURATED_ADIABATIC_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
+	THERMO_SATURATED_ADIABATIC_LABEL_FONT_SIZE[ help_text = 'Font Size used for the saturated_adiabatics labels' ]
+	{
+		*
+	} = 0.3
+
+	THERMO_SATURATED_ADIABATIC_LABEL_FREQUENCY[ help_text = 'saturated_adiabatic frequency for labelling' ]
+	{
+		*
+	} = 1
+
+	THERMO_MIXING_RATIO_GRID [ help_text = 'Plot the mixing_ratios' ]
+ 	{
+		ON;  ON
+		OFF; OFF
+	} = ON
+
+	THERMO_MIXING_RATIO_COLOUR [ help = help_colour,interface = colour, help_text='Colou of the mixing_ratios' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = PURPLE
+
+	THERMO_MIXING_RATIO_THICKNESS[ help_text = 'Thickness  of the mixing_ratios' ]
+	{
+		*
+	} = 1
+
+	THERMO_MIXING_RATIO_STYLE
+	{
+		&PARAMSHARE&STYLE
+	} = DASH
+
+	THERMO_MIXING_RATIO_FREQUENCY[ help_text = 'mixing_ratio frequency for grid' ]
+	{
+		*
+	} = 1
+
+	THERMO_MIXING_RATIO_LABEL_COLOUR [ help = help_colour,interface = colour, help_text='Label Colour for the isotherms' ]
+	{ 
+		&PARAMSHARE&COLOUR
+	} = PURPLE
+
+	THERMO_MIXING_RATIO_LABEL_FONT_NAME
+	{
+		@
+	} = SANSERIF
+
+	THERMO_MIXING_RATIO_LABEL_FONT_STYLE
+	{
+		NORMAL;NORMAL
+		BOLD;BOLD
+		ITALIC;ITALIC
+		BOLDITALIC;BOLDITALIC
+	} = NORMAL
+
+	THERMO_MIXING_RATIO_LABEL_FONT_SIZE[ help_text = 'Font Size used for the mixing_ratios labels' ]
+	{
+		*
+	} = 0.3
+
+	THERMO_MIXING_RATIO_LABEL_FREQUENCY[ help_text = 'mixing_ratio frequency for labelling' ]
+	{
+		*
+	} = 1
+
+}
diff --git a/src/Thermo/MTHERMOGRIDRules b/src/Thermo/MTHERMOGRIDRules
new file mode 100644
index 0000000..bbfe9f1
--- /dev/null
+++ b/src/Thermo/MTHERMOGRIDRules
@@ -0,0 +1,62 @@
+
+%if THERMO_ISOTHERM_GRID <> ON %then
+	%unset THERMO_ISOTHERM_LABEL_FONT_STYLE
+	%unset THERMO_ISOTHERM_LABEL_COLOUR
+	%unset THERMO_ISOTHERM_LABEL_FREQUENCY
+	%unset THERMO_ISOTHERM_REFERENCE_STYLE
+	%unset THERMO_ISOTHERM_REFERENCE_THICKNESS
+	%unset THERMO_ISOTHERM_STYLE
+	%unset THERMO_ISOTHERM_COLOUR
+	%unset THERMO_ISOTHERM_REFERENCE
+	%unset THERMO_ISOTHERM_LABEL_FONT_NAME
+	%unset THERMO_ISOTHERM_INTERVAL
+	%unset THERMO_ISOTHERM_REFERENCE_COLOUR
+	%unset THERMO_ISOTHERM_THICKNESS
+	%unset THERMO_ISOTHERM_LABEL_FONT_SIZE
+
+%if THERMO_MIXING_RATIO_GRID <> ON %then
+	%unset THERMO_MIXING_RATIO_STYLE
+	%unset THERMO_MIXING_RATIO_COLOUR
+	%unset THERMO_MIXING_RATIO_LABEL_COLOUR
+	%unset THERMO_MIXING_RATIO_LABEL_FONT_STYLE
+	%unset THERMO_MIXING_RATIO_LABEL_FONT_SIZE
+	%unset THERMO_MIXING_RATIO_LABEL_FONT_NAME
+	%unset THERMO_MIXING_RATIO_THICKNESS
+	%unset THERMO_MIXING_RATIO_LABEL_FREQUENCY
+
+%if THERMO_ISOBAR_GRID <> ON %then
+	%unset THERMO_ISOBAR_INTERVAL
+	%unset THERMO_ISOBAR_LABEL_FREQUENCY
+	%unset THERMO_ISOBAR_COLOUR
+	%unset THERMO_ISOBAR_LABEL_FONT_NAME
+	%unset THERMO_ISOBAR_STYLE
+	%unset THERMO_ISOBAR_THICKNESS
+	%unset THERMO_ISOBAR_LABEL_FONT_SIZE
+	%unset THERMO_ISOBAR_LABEL_REFERENCE
+	%unset THERMO_ISOBAR_LABEL_COLOUR
+	%unset THERMO_ISOBAR_LABEL_FONT_STYLE
+	%unset THERMO_ISOBAR_REFERENCE
+
+%if THERMO_SATURATED_ADIABATIC_GRID <> ON %then
+	%unset THERMO_SATURATED_ADIABATIC_REFERENCE
+	%unset THERMO_SATURATED_ADIABATIC_LABEL_FONT_STYLE
+	%unset THERMO_SATURATED_ADIABATIC_LABEL_COLOUR
+	%unset THERMO_SATURATED_ADIABATIC_LABEL_FONT_NAME
+	%unset THERMO_SATURATED_ADIABATIC_STYLE
+	%unset THERMO_SATURATED_ADIABATIC_THICKNESS
+	%unset THERMO_SATURATED_ADIABATIC_COLOUR
+	%unset THERMO_SATURATED_ADIABATIC_LABEL_FONT_SIZE
+	%unset THERMO_SATURATED_ADIABATIC_LABEL_FREQUENCY
+	%unset THERMO_SATURATED_ADIABATIC_INTERVAL
+
+%if THERMO_DRY_ADIABATIC_GRID <> ON %then
+	%unset THERMO_DRY_ADIABATIC_THICKNESS
+	%unset THERMO_DRY_ADIABATIC_COLOUR
+	%unset THERMO_DRY_ADIABATIC_STYLE
+	%unset THERMO_DRY_ADIABATIC_LABEL_FONT_NAME
+	%unset THERMO_DRY_ADIABATIC_LABEL_COLOUR
+	%unset THERMO_DRY_ADIABATIC_REFERENCE
+	%unset THERMO_DRY_ADIABATIC_LABEL_FONT_STYLE
+	%unset THERMO_DRY_ADIABATIC_LABEL_FREQUENCY
+	%unset THERMO_DRY_ADIABATIC_LABEL_FONT_SIZE
+	%unset THERMO_DRY_ADIABATIC_INTREVAL
diff --git a/src/Thermo/MThermoDef b/src/Thermo/MThermoDef
new file mode 100644
index 0000000..173fc07
--- /dev/null
+++ b/src/Thermo/MThermoDef
@@ -0,0 +1,114 @@
+PARAMSHARE ; ParamShare; PARAMSHARE
+{
+   COLOUR {
+      %include MagicsColors.h
+   }
+
+   STYLE {
+      SOLID; SOLID
+      DASH; DASH
+      DOT; DOT
+      CHAIN_DOT; CHAIN_DOT
+      CHAIN_DASH; CHAIN_DASH
+   }
+}
+
+MTHERMO; Metview; manually generated
+{
+   LEGEND
+   {
+      ON;  ON
+      OFF; OFF
+   } = OFF
+
+   LEGEND_USER_TEXT
+   {
+      @
+   } = ''
+
+   THERMO_TEMPERATURE_LINE
+   {
+      ON;  ON
+      OFF; OFF
+   } = ON
+
+   THERMO_TEMPERATURE_LINE_STYLE
+   {
+      &PARAMSHARE&STYLE
+   } = SOLID
+
+   THERMO_TEMPERATURE_LINE_COLOUR [ help = help_colour,interface = colour ]
+   {
+      &PARAMSHARE&COLOUR
+   } = RED
+
+   THERMO_TEMPERATURE_LINE_THICKNESS
+   {
+      *
+   } = 8
+
+   THERMO_TEMPERATURE_MISSING_DATA_MODE
+   {
+      IGNORE;IGNORE
+      JOIN;JOIN
+      DROP;DROP
+   } = JOIN
+
+   THERMO_TEMPERATURE_MISSING_DATA_STYLE
+   {
+      &PARAMSHARE&STYLE
+   } = SOLID
+
+   THERMO_TEMPERATURE_MISSING_DATA_COLOUR [ help = help_colour,interface = colour ]
+   { 
+      &PARAMSHARE&COLOUR
+   } = RED
+
+   THERMO_TEMPERATURE_MISSING_DATA_THICKNESS
+   {
+      *
+   } = 8
+
+   THERMO_DEWPOINT_LINE
+   {
+      ON;  ON
+      OFF; OFF
+   } = ON
+
+   THERMO_DEWPOINT_LINE_STYLE
+   {
+      &PARAMSHARE&STYLE
+   } = DASH
+
+   THERMO_DEWPOINT_LINE_COLOUR [ help = help_colour,interface = colour ]
+   {
+      &PARAMSHARE&COLOUR
+   } = RED
+
+   THERMO_DEWPOINT_LINE_THICKNESS
+   {
+      *
+   } = 8
+
+   THERMO_DEWPOINT_MISSING_DATA_MODE
+   {
+      IGNORE;IGNORE
+      JOIN;JOIN
+      DROP;DROP
+   } = JOIN
+
+   THERMO_DEWPOINT_MISSING_DATA_STYLE
+   {
+      &PARAMSHARE&STYLE
+   } = DASH
+
+   THERMO_DEWPOINT_MISSING_DATA_COLOUR [ help = help_colour,interface = colour ]
+   { 
+      &PARAMSHARE&COLOUR
+   } = RED
+
+   THERMO_DEWPOINT_MISSING_DATA_THICKNESS
+   {
+      *
+   } = 8
+}
diff --git a/src/Thermo/MThermoRules b/src/Thermo/MThermoRules
new file mode 100644
index 0000000..06069d2
--- /dev/null
+++ b/src/Thermo/MThermoRules
@@ -0,0 +1,4 @@
+%if GRAPH_LINE <> ON %then
+   %unset GRAPH_LINE_COLOUR
+   %unset GRAPH_LINE_STYLE
+   %unset GRAPH_LINE_THICKNESS
diff --git a/src/Thermo/ObjectSpec.Thermo b/src/Thermo/ObjectSpec.Thermo
index ef90eca..4fce311 100644
--- a/src/Thermo/ObjectSpec.Thermo
+++ b/src/Thermo/ObjectSpec.Thermo
@@ -83,3 +83,31 @@ state,
    class      = THERMOVIEW,
    action     = execute/visualise,
    service    = uPlotManager
+
+object,
+   class           = MTHERMOGRID,
+   icon_box        = Visual definitions,
+   can_be_created  = True,
+   definition_file = '$METVIEW_DIR_SHARE/etc/MTHERMOGRIDDef',
+   rules_file      = '$METVIEW_DIR_SHARE/etc/MTHERMOGRIDRules',
+   default_name    = Thermo Grid,
+   help_page       = Thermo_Grid,
+   type            = Visdef,
+   macro           = mthermogrid,
+   expand          = 128,     #EXPAND_NO_DEFAULT
+   editor_type     = SimpleEditor,
+   pixmap          = '$METVIEW_DIR_SHARE/icons/MTHERMOGRID.icon'
+
+object,
+   class           = MTHERMO,
+   icon_box        = Visual definitions,
+   can_be_created  = True,
+   definition_file = '$METVIEW_DIR_SHARE/etc/MThermoDef',
+   rules_file      = '$METVIEW_DIR_SHARE/etc/MThermoRules',
+   default_name    = Thermo Plotting,
+   help_page       = Thermo_Plotting,
+   type            = Visdef,
+   macro           = mthermo,
+   expand          = 128,    #EXPAND_NO_DEFAULT
+   editor_type     = SimpleEditor,
+   pixmap          = '$METVIEW_DIR_SHARE/icons/MTHERMO.icon'
diff --git a/src/Thermo/Thermo.cc b/src/Thermo/Thermo.cc
index a11431b..1000a4a 100644
--- a/src/Thermo/Thermo.cc
+++ b/src/Thermo/Thermo.cc
@@ -28,21 +28,28 @@ void Thermo::serve(MvRequest& in,MvRequest& out)
 cout << "request IN" << endl;
 in.print();
 
-   // Create a temporary netCDF file name
-   ncFileName_ = marstmp();
-
    // Get Input parameters
-   //origReq_ = in;
+   origReq_ = in;
    if ( !this->getInputParameters(in) )
       return;
 
-   // Process data
-   if ( !this->processData() )
-      return;
-
+   // It is a netCDF data and it has been already processed.
    // Build the output request
-   if ( !this->createOutputRequest(out) )
-      return;
+   if ( dataRequest_.getVerb() == string("NETCDF") )
+      this->createProcessedOutputRequest( out );
+   else
+   {
+      // Create a temporary netCDF file name
+      ncFileName_ = marstmp();
+
+      // Process data
+      if ( !this->processData() )
+         return;
+
+      // Build the output request
+      if ( !this->createOutputRequest(out) )
+         return;
+   }
 
    // Add hidden values to tne output request
    // out1("_VERB") = "NETCDF_MATRIX";
@@ -129,14 +136,14 @@ bool Thermo::getInputParameters( MvRequest& in )
       if ( !modRequest )
          modRequest = in;
 
+      // Retrieve application specific parametes
+      if ( !this->getAppParameters( modRequest ) )
+         return false;
+
       // Consistency check, only for non-default View request
       if ( !((const char*)commonRequest("_DEFAULT") && (int)commonRequest("_DEFAULT") == 1) )
          if ( !this->consistencyCheck(commonRequest, modRequest) )
             return false;
-
-      // Retrieve application specific parametes
-      if ( !this->getAppParameters( modRequest ) )
-         return false;
    }
 
    return true;
@@ -180,6 +187,23 @@ MvRequest Thermo::getAppView ( MvRequest& viewRequest )
       return viewRequest;
 }
 
+void Thermo::createProcessedOutputRequest( MvRequest& out )
+{
+   // Create NetCDF output request
+   MvRequest data = origReq_.getSubrequest("DATA");
+   MvRequest out1 = data.getSubrequest("_VISUALISE");
+   MvRequest viewReq = data.getSubrequest("_CARTESIANVIEW");
+   data.unsetParam("_VISUALISE");        // to avoid duplication of info
+   data.unsetParam("_CARTESIANVIEW");    // to avoid duplication of info
+   data.unsetParam("_ORIGINAL_REQUEST"); // to avoid duplication of info
+   out1("NETCDF_DATA") = data;
+
+   // Final output request
+   // If an icon was dropped into a view, uPlot will ignore it.
+   // Mode-specific options
+   out = viewReq + out1;
+}
+
 //------------------------------------------------------------------------------
 
 int main(int argc,char **argv)
diff --git a/src/Thermo/Thermo.h b/src/Thermo/Thermo.h
index 2c551c8..d284bd0 100644
--- a/src/Thermo/Thermo.h
+++ b/src/Thermo/Thermo.h
@@ -42,10 +42,10 @@ public:
    virtual bool getInputParameters( MvRequest& );
 
    // Process data and build all data structures
-   virtual bool processData() { return false; };
+   virtual bool processData() = 0;
 
    // Create output request
-   virtual bool createOutputRequest( MvRequest& ) { return false; };
+   virtual bool createOutputRequest( MvRequest& ) = 0;
 
    // Handle variable members
    void actionMode( string action ) { actionMode_ = action; }
@@ -76,11 +76,14 @@ protected:
    // they were computed.
    virtual bool consistencyCheck( MvRequest&, MvRequest& ) { return true; }
 
+   void createProcessedOutputRequest( MvRequest& );
+
    // Variable members
    string actionMode_;      // e.g. "examine"/"save"/"execute"/...
    string ncFileName_;      // netcdf file name
    int procType_;           // processing type, e.g.,THERMO_DATA_MODULE,...
    MvRequest dataRequest_;  // data request
+   MvRequest origReq_;      // input request
 };
 
 #endif
diff --git a/src/WebAccess/CMakeLists.txt b/src/WebAccess/CMakeLists.txt
index c004b7e..bf44981 100644
--- a/src/WebAccess/CMakeLists.txt
+++ b/src/WebAccess/CMakeLists.txt
@@ -2,7 +2,7 @@
 ecbuild_add_executable( TARGET       WebAccess
                         SOURCES      WebAccess.cc remote.c
                         DEFINITIONS  ${METVIEW_EXTRA_DEFINITIONS}
-                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES}
+                        INCLUDES     ${X11_INCLUDE_DIR} ${METVIEW_STANDARD_INCLUDES} ${METVIEW_MOTIF_INCLUDE_DIR}
                         LIBS         ${METVIEW_MOTIF_LIBS} ${STANDARD_METVIEW_LIBS} ${MOTIF_LIBRARIES} ${X11_LIBRARIES}
                     )
 
diff --git a/src/XSection/Average.cc b/src/XSection/Average.cc
index c8fbd78..7c27c1c 100644
--- a/src/XSection/Average.cc
+++ b/src/XSection/Average.cc
@@ -74,17 +74,6 @@ bool Average::getAppParameters( MvRequest& in, ApplicationInfo& appInfo )
    if ( !this->getCoordinates(in,appInfo) )
       return false;
 
-#if 0
-   // Retrieve interpolation flag
-   // Normal interpolation of levels unless INTERPOLATE_VALUES = NO
-   bool interpolate = true;
-   if ( (const char*)in("INTERPOLATE_VALUES") &&
-        strcmp(in("INTERPOLATE_VALUES"),"NO") == 0 )
-           interpolate = false;
-
-   appInfo.Interpolate(interpolate);
-#endif
-
    inputMode_ = (strcmp(in("DIRECTION"),"NS") == 0 || strcmp(in("DIRECTION"),"NORTH SOUTH") == 0) ? AVERAGE_NS : AVERAGE_EW;
 
    return true;
@@ -124,7 +113,7 @@ bool Average::generateData( ApplicationInfo& appInfo, ParamMap &params,
                             MvNetCDF &cdf, MvField& field, const string& key )
 {
    // Get parameter info
-   ParamInfo *par = this->getParamInfo(params,key);
+   ParamInfo *par = appInfo.getParamInfo(params,key);
    if ( !par )
       return false;
 
@@ -185,11 +174,11 @@ bool Average::fillValues( ApplicationInfo& appInfo, MvField &field, double *vals
    return true;
 }
 
-MvRequest Average::createOutputRequest( ApplicationInfo& appInfo, string netcdfName, ParamInfo* parInfo )
+MvRequest Average::createOutputRequest( ApplicationInfo& appInfo, ParamInfo* parInfo )
 {
    // Create netCDF data request
    MvRequest xs("NETCDF");
-   xs("PATH") = netcdfName.c_str();
+   xs("PATH") = ncName_.c_str();
    xs("TEMPORARY") = 1;
 
    // Create NetCDF output request
diff --git a/src/XSection/Average.h b/src/XSection/Average.h
index 7b90c63..92d77ff 100644
--- a/src/XSection/Average.h
+++ b/src/XSection/Average.h
@@ -43,7 +43,7 @@ public:
    bool generateData( ApplicationInfo&, ParamMap&, MvNetCDF&, MvField&, const string& );
 
    // Create output request
-   MvRequest createOutputRequest( ApplicationInfo&, string, ParamInfo* );
+   MvRequest createOutputRequest( ApplicationInfo&, ParamInfo* );
 
    int computeGeographicalPoints( ApplicationInfo&, MvField* = 0 );
 
diff --git a/src/XSection/CrossS.cc b/src/XSection/CrossS.cc
index 47b8f47..4607435 100644
--- a/src/XSection/CrossS.cc
+++ b/src/XSection/CrossS.cc
@@ -33,13 +33,19 @@ enum { XWIND,XVELOCITY,XCONTOUR};
 // Wind values
 enum {PERPENDICULAR, PARALLEL, INTENSITY };
 
+
+//Wind scaling type
+// W_SCALE_PB is derived from a formula given by Peter Bechtold
+enum {W_SCALE_PB=998, W_SCALE_AUTO_MV3=999};
+
 CrossS::CrossS() :
                    Xsect("MXSECTION"),
                    foundUV_(false), foundW_(false),
                    hcNumber_(0), hcPerpendicular_(0), hcParallel_(0),
                    hcIntensity_(0), currentHC_(0),
                    inputMode_(XCONTOUR),
-                   oroColour_("CYAN")
+                   oroColour_("CYAN"),
+                   wScaling_(W_SCALE_AUTO_MV3)
 {
    type_ = "MXSECTION";
    view_ = "MXSECTIONVIEW";
@@ -51,7 +57,8 @@ CrossS::CrossS(const char*kw) :
                    hcNumber_(0), hcPerpendicular_(0), hcParallel_(0),
                    hcIntensity_(0), currentHC_(0),
                    inputMode_(XCONTOUR),
-                   oroColour_("CYAN")
+                   oroColour_("CYAN"),
+                   wScaling_(W_SCALE_AUTO_MV3)
 {
    type_ = kw;
    view_ = "MXSECTIONVIEW";
@@ -77,17 +84,6 @@ bool CrossS::getAppParameters( MvRequest& in, ApplicationInfo& appInfo )
    if ( !this->getCoordinates(in,appInfo) )
       return false;
 
-#if 0
-   // Retrieve interpolation flag
-   // Normal interpolation of levels unless INTERPOLATE_VALUES = NO
-   bool interpolate = true;
-   if ( (const char*)in("INTERPOLATE_VALUES") &&
-        strcmp(in("INTERPOLATE_VALUES"),"NO") == 0 )
-           interpolate = false;
-
-   appInfo.Interpolate(interpolate);
-#endif
-
    // Retrieve Wind input info
    hcNumber_ = 0;
    if( (const char*)in("WIND_PERPENDICULAR") &&
@@ -121,7 +117,69 @@ bool CrossS::getAppParameters( MvRequest& in, ApplicationInfo& appInfo )
    if( (const char*)in( "LNSP_PARAM" ) )
       LNSP_FIELD = (int)in( "LNSP_PARAM" );
 
-   // Retrieve orography colour
+   if ( (const char*)in("HORIZONTAL_POINT_MODE") )
+       appInfo.horPointMode( (const char*)in("HORIZONTAL_POINT_MODE") );
+
+   // Retrieve vertical coordinates information
+   if ( (const char*)in("VERTICAL_COORDINATES") &&
+        (const char*)in("VERTICAL_COORDINATES") == string("USER") )
+          appInfo.haveGHBC(true);
+
+   if ( (const char*)in("VERTICAL_COORDINATE_PARAM") )
+       appInfo.setGHBC( (int)in("VERTICAL_COORDINATE_PARAM") );
+
+   // Retrieve W component scaling factor
+   if( (const char*)in( "W_WIND_SCALING_FACTOR_MODE" ) &&
+       strcmp(in("W_WIND_SCALING_FACTOR_MODE"),"AUTOMATIC") == 0 )
+      wScaling_ = W_SCALE_AUTO_MV3;
+
+   else if( (const char*)in( "W_WIND_SCALING_FACTOR_MODE" ) &&
+            strcmp(in("W_WIND_SCALING_FACTOR_MODE"),"USER") == 0 )
+           if( (const char*)in( "W_WIND_SCALING_FACTOR" ) )
+              wScaling_ = (double)in( "W_WIND_SCALING_FACTOR" );
+
+
+
+   // Retrieve parameters related to the vertical levels definition
+   if( (const char*)in( "LEVEL_SELECTION_TYPE" ) )
+      appInfo.levelSelectionType((const char*)in( "LEVEL_SELECTION_TYPE" ));
+
+   if( (const char*)in( "LEVEL_LIST" ) )
+   {
+      double val;
+      double factor = 100.; // input values are in hPa
+      int cnt = in.iterInit("LEVEL_LIST");
+      vector<double> lslist;
+      lslist.reserve(cnt);
+      for( int i = 0; i < cnt; ++i )
+      {
+         in.iterGetNextValue(val);
+         lslist.push_back(val*factor);
+      }
+      
+      // Make sure the values are in crescent order
+      std::sort(lslist.begin(),lslist.end());
+
+      appInfo.levelList(lslist);
+   }
+
+   if( (const char*)in( "LEVEL_COUNT" ) )
+      appInfo.levelCount((int)in( "LEVEL_COUNT" ));
+
+   if( (const char*)in( "VERTICAL_SCALING" ) )
+   {
+      string vs = (const char*)in( "VERTICAL_SCALING" );
+      bool bvs = (vs == "LINEAR") ? true : false;
+      appInfo.vLinearScaling(bvs);
+   }
+
+   if( (const char*)in( "BOTTOM_LEVEL" ) )
+      appInfo.bottomLevel( (double)in( "BOTTOM_LEVEL" ) * 100. );   //hPa
+
+   if( (const char*)in( "TOP_LEVEL" ) )
+      appInfo.topLevel( (double)in( "TOP_LEVEL" ) * 100. );         //hPa
+
+    // Retrieve orography colour
    if( (const char*)in( "OROGRAPHY_COLOUR" ) )
       oroColour_ = (const char*)in( "OROGRAPHY_COLOUR" );
    else if ( (const char*)in("_CONTEXT") )
@@ -135,17 +193,6 @@ bool CrossS::getAppParameters( MvRequest& in, ApplicationInfo& appInfo )
       }
    }
 
-   // Retrieve vertical coordinates information
-   if ( (const char*)in("VERTICAL_COORDINATES") &&
-        (const char*)in("VERTICAL_COORDINATES") == string("USER") )
-          appInfo.haveGHBC(true);
-
-   if ( (const char*)in("VERTICAL_COORDINATE_PARAM") )
-       appInfo.setGHBC( (int)in("VERTICAL_COORDINATE_PARAM") );
-
-   if ( (const char*)in("HORIZONTAL_POINT_MODE") )
-       appInfo.horPointMode( (const char*)in("HORIZONTAL_POINT_MODE") );
-
    return true;
 }
 
@@ -162,10 +209,6 @@ bool CrossS::consistencyCheck( MvRequest& req1, MvRequest& req2)
       return false;
    }
 
-   // Check interpolation option
-//   if ( (const char*)req1("INTERPOLATE_VALUES") != (const char*)req2("INTERPOLATE_VALUES") )
-//      setError(0,"INTERPOLATE_VALUES parameter is not consistent");
-
    // Check Wind parameters
    if ( (const char*)req1("WIND_PARALLEL")      != (const char*)req2("WIND_PARALLEL")      ||
         (const char*)req1("WIND_PERPENDICULAR") != (const char*)req2("WIND_PERPENDICULAR") ||
@@ -184,7 +227,7 @@ bool CrossS::generateData ( ApplicationInfo& appInfo, ParamMap& params,
                             const string& key )
 {
    // Get parameter info
-   ParamInfo *par = getParamInfo(params,key);
+   ParamInfo *par = appInfo.getParamInfo(params,key);
    if ( !par )
       return false;
 
@@ -205,7 +248,7 @@ bool CrossS::generateXsectData ( ApplicationInfo& appInfo, ParamMap &params,
                                  const string& key )
 {
    // Get parameter info
-   ParamInfo *par = this->getParamInfo(params,key);
+   ParamInfo *par = appInfo.getParamInfo(params,key);
    if ( !par )
       return false;
 
@@ -223,6 +266,11 @@ bool CrossS::generateXsectData ( ApplicationInfo& appInfo, ParamMap &params,
    }
    else if ( foundW_ && par->Parameter() == W_FIELD )
    {
+      // Special 2 cases because Magics does not interpolate winds:
+      // ML to PL or PL
+      if( appInfo.levelType() == XS_ML_LNSP || appInfo.levelType() == XS_PL )
+         appInfo.setVerticalInterpolationFlag(true);
+
       inputMode_ = XVELOCITY;
       return velocityValues(appInfo,params,cdf,key,field);
    }
@@ -237,18 +285,18 @@ bool CrossS::generateXsectData ( ApplicationInfo& appInfo, ParamMap &params,
 bool CrossS::generateLNSP(ApplicationInfo& appInfo, MvNetCDF &cdf, ParamInfo* par )
 {
    // Get initial info
-   double low   = appInfo.PresTop()/100.;
-   double high  = appInfo.PresBot()/100.;
+   double low   = appInfo.topLevel()/100.;
+   double high  = appInfo.bottomLevel()/100.;
    int nrPoints = appInfo.NrPoints();
 
    // Add/update LNSP and auxiliary variables to the netCDF
    // These auxiliary variables will be used to plot the orography
-   string varname = this->getNetcdfVarname(par->ParamName());
+   string varname = Xsect::getNetcdfVarname(par->ParamName());  // varname is LNSP
    MvNcVar *ncx1 = cdf.getVariable("orography_x_values");
    MvNcVar *ncy1 = cdf.getVariable("orography_y1_values");
    MvNcVar *ncy2 = cdf.getVariable("orography_y2_values");
    MvNcVar *ncln = cdf.getVariable(varname);
-   if ( !ncln )   // Create new variables
+   if ( !ncx1 || !ncy1 || !ncy2 || !ncln )   // Create new variables
    {
       ntime_ = -1;
 
@@ -261,32 +309,44 @@ bool CrossS::generateLNSP(ApplicationInfo& appInfo, MvNetCDF &cdf, ParamInfo* pa
       values_sdim.push_back("npoints");
 
       // Create LNSP variable
-      ncln = cdf.addVariable(varname,ncDouble,values_ndim,values_sdim); //2,nrPoints);
-      ncln->addAttribute("long_name", par->ParamLongName().c_str());
-      ncln->addAttribute("units", par->Units().c_str());
-      ncln->addAttribute("_FillValue", XMISSING_VALUE);
+      if ( !ncln )
+      {
+         ncln = cdf.addVariable(varname,ncDouble,values_ndim,values_sdim);
+         ncln->addAttribute("long_name", par->ParamLongName().c_str());
+         ncln->addAttribute("units", par->Units().c_str());
+         ncln->addAttribute("_FillValue", XMISSING_VALUE);
+      }
 
       // Create orography x values variable
-      ncx1 = cdf.addVariable("orography_x_values",ncDouble,values_ndim,values_sdim);
-      ncx1->addAttribute("long_name", "orography_x_values");
-      ncx1->addAttribute("units", " ");
-      ncx1->addAttribute("_FillValue", XMISSING_VALUE);
+      if ( !ncx1 )
+      {
+         ncx1 = cdf.addVariable("orography_x_values",ncFloat,values_ndim,values_sdim);
+         ncx1->addAttribute("long_name", "orography_x_values");
+         ncx1->addAttribute("units", " ");
+         ncx1->addAttribute("_FillValue", (float)XMISSING_VALUE);
+      }
 
       // Create orography y1 values variable
-      ncy1 = cdf.addVariable("orography_y1_values",ncDouble,values_ndim, values_sdim);
-      ncy1->addAttribute("long_name", "orography_y1_values");
-      ncy1->addAttribute("units", " ");
-      ncy1->addAttribute("_FillValue", XMISSING_VALUE);
+      if ( !ncy1 )
+      {
+         ncy1 = cdf.addVariable("orography_y1_values",ncDouble,values_ndim, values_sdim);
+         ncy1->addAttribute("long_name", "orography_y1_values");
+         ncy1->addAttribute("units", " ");
+         ncy1->addAttribute("_FillValue", XMISSING_VALUE);
+      }
 
       // Create orography y2 values variable
-      ncy2 = cdf.addVariable("orography_y2_values",ncDouble,values_ndim, values_sdim);
-      ncy2->addAttribute("long_name", "orography_y2_values");
-      ncy2->addAttribute("units", " ");
-      ncy2->addAttribute("_FillValue", XMISSING_VALUE);
+      if ( !ncy2 )
+      {
+         ncy2 = cdf.addVariable("orography_y2_values",ncDouble,values_ndim, values_sdim);
+         ncy2->addAttribute("long_name", "orography_y2_values");
+         ncy2->addAttribute("units", " ");
+         ncy2->addAttribute("_FillValue", XMISSING_VALUE);
+      }
    }
 
    // Get LNSP values
-   double *splin = appInfo.getOneLevelValues(par,"1");
+   double *splin = par->getOneLevelValues("1");
    if ( !splin )
    {
       setError(1,"ERROR: Could not find LNSP Level values");
@@ -343,13 +403,13 @@ bool CrossS::windValues( ApplicationInfo& appInfo, ParamMap &params, MvNetCDF &c
    int i,j;
 
    // Find the v field
-   ParamInfo* par_v = this->getParamInfo( params,key );
+   ParamInfo* par_v = appInfo.getParamInfo( params,key );
    if ( !par_v )
       return false;
 
    // The paraminfo contains the v field, now find the u field,
    // substitute u for v in the key and find info in list.
-   ParamInfo *par_u = this->getParamInfo( appInfo,params,U_FIELD,key );
+   ParamInfo *par_u = appInfo.getParamInfo( params,U_FIELD,key );
    if ( !par_u )
       return false;
 
@@ -357,11 +417,13 @@ bool CrossS::windValues( ApplicationInfo& appInfo, ParamMap &params, MvNetCDF &c
    ParamInfo par_uv( par_v->Parameter(), par_v->Date(), par_v->Time(), par_v->Step(), par_v->ParamName(), par_v->ParamLongName(), par_v->Units(), par_v->LevelType() );
 
    // Allocate memory
-   int nrLevels = appInfo.NrLevels();
+   int nrLevels = appInfo.outputLevels();
    int nrPoints = appInfo.NrPoints();
-   double **cp =  new double* [ nrLevels ];
-   for (i = 0; i < nrLevels; i++)
-      cp[i] = new double [ nrPoints ];
+   vector<double> cp;
+   cp.reserve(nrLevels*nrPoints);
+//   =  new double* [ nrLevels ];
+//   for (i = 0; i < nrLevels; i++)
+//      cp[i] = new double [ nrPoints ];
 
    // Main loop
    int hc_perp = hcPerpendicular_;
@@ -406,6 +468,7 @@ bool CrossS::windValues( ApplicationInfo& appInfo, ParamMap &params, MvNetCDF &c
          currentHC_ = hc_int; hc_int = 0;
       }
 
+      // Map U/V into planes
       this->mapValues(appInfo,par_uv,par_u,par_v);
 
       vector<double> y_values;
@@ -420,23 +483,17 @@ bool CrossS::windValues( ApplicationInfo& appInfo, ParamMap &params, MvNetCDF &c
          // Get LNSP only once
          if ( i == 0 )
          {
-            ParamInfo* parLnsp = this->getParamInfo( appInfo,params,appInfo.LNSP(),key );
+            ParamInfo* parLnsp = appInfo.getParamInfo( params,appInfo.LNSP(),key );
             if ( ! parLnsp )  //LNSP not found
             {
                setError(1,"ERROR: Could not find parameter LNSP");
-               for (j = 0; j < nrLevels; j++)
-                  delete [] cp[j];
-               delete [] cp;
                return false;
             }
 
-            splin = appInfo.getOneLevelValues(parLnsp,"1");
+            splin = parLnsp->getOneLevelValues("1");
             if ( !splin )  //LNSP not found
             {
                setError(1,"ERROR: Could not find LNSP Level values");
-               for (j = 0; j < nrLevels; j++)
-                  delete [] cp[j];
-               delete [] cp;
                return false;
             }
          }
@@ -453,84 +510,51 @@ bool CrossS::windValues( ApplicationInfo& appInfo, ParamMap &params, MvNetCDF &c
       for ( j = 0; j < nrLevels; j++ )
       {
          ncv->setCurrent(ntime_,j);
-         ncv->put(cp[j],1,1,(long)nrPoints);
+         ncv->put(&cp[j*nrPoints],1,1,(long)nrPoints);
       }
    }
 
-   // Release memory
-   for ( i = 0; i < nrLevels; i++ )
-      delete [] cp[i];
-   delete [] cp;
-
    return true;
 }
 
-// Generate wind data for u,v&w.
+// Generate wind data for U/V/W
 bool CrossS::velocityValues( ApplicationInfo& appInfo, ParamMap &params,
-                             MvNetCDF &cdf, const string& key,
-                             MvField& field )
+                             MvNetCDF &cdf, const string& key, MvField& field )
 {
-   int i,j;
-
    // Find the w field
-   ParamInfo* par_w = this->getParamInfo( params,key );
+   ParamInfo* par_w = appInfo.getParamInfo( params,key );
    if ( !par_w )
       return false;
 
-   // The paraminfo contains the W field, now find the U and V fields.
-   // Use the W field key to find U/V info in the list.
-   ParamInfo* par_u = this->getParamInfo( appInfo,params,U_FIELD,key );
+   // Use the W field key to find U/V info in the list
+   ParamInfo* par_u = appInfo.getParamInfo( params,U_FIELD,key );
    if ( !par_u )
       return false;
 
-   ParamInfo* par_v = this->getParamInfo( appInfo,params,V_FIELD,key );
+   ParamInfo* par_v = appInfo.getParamInfo( params,V_FIELD,key );
    if ( !par_v )
       return false;
 
+   // Scale velocity
    currentHC_ = hcParallel_;
-   appInfo.scaleVelocity(par_w);
+   if ( wScaling_ == W_SCALE_AUTO_MV3 )
+      appInfo.scaleVelocity(par_w);
+   else if ( wScaling_ == W_SCALE_PB )
+      appInfo.scaleVelocityPB(par_w);
+   else
+      appInfo.scaleVelocity1(par_w,wScaling_);
+
+   // Create a structure for the x_component
    ParamInfo par_uv( par_v->Parameter(), par_v->Date(), par_v->Time(), par_v->Step(), par_v->ParamName(), par_v->ParamLongName(), par_v->Units(), par_v->LevelType() );
 
+   // Map U/V into planes
    this->mapValues(appInfo,par_uv,par_u,par_v);
 
-   // Get/create the netCDF variable
-   int nrLevels = appInfo.NrLevels();
-   int nrPoints = appInfo.NrPoints();
-   string varname = this->getNetcdfVarname(par_w->ParamName());
-   MvNcVar *ncv = cdf.getVariable(varname);
-   if ( !ncv )   // Create new variable
-   {
-      ntime_ = -1;
-
-      // Initialise dimensions
-      vector<long> values_ndim;
-      values_ndim.push_back(appInfo.NTimes());
-      values_ndim.push_back(2);
-      values_ndim.push_back(nrLevels);
-      values_ndim.push_back(nrPoints);
-      vector<string> values_sdim;
-      values_sdim.push_back(XS_VARTIME);
-      values_sdim.push_back("uvw");
-      values_sdim.push_back(XS_VARLEVEL);
-      values_sdim.push_back(XS_VARLON);
-
-      // Create variable
-      ncv = cdf.addVariable(varname,ncDouble,values_ndim, values_sdim);
-      ncv->addAttribute("long_name", par_w->ParamLongName().c_str());
-      ncv->addAttribute("units", par_w->Units().c_str());
-      ncv->addAttribute("_FillValue", XMISSING_VALUE);
-      ncv->addAttribute("title",titleVariable(appInfo,par_w).c_str());
-   }
-
-   // Allocate memory
-   double **cp = new double* [ nrLevels ];
-   for (i = 0; i < nrLevels; i++)
-      cp[i] = new double [ nrPoints ];
-
-   // Compute UV values
+   // Compute UV values (x_component).
+   vector<double> cp;
    vector<double> y_values;
-   double* splin;
-   if( appInfo.levelType() != XS_ML_LNSP )
+   double* splin = 0;
+   if( !appInfo.isInterpolate() )
    {
       // Compute level values and interpolate matrix
       appInfo.computeLevelInfo(&par_uv,y_values);
@@ -538,65 +562,90 @@ bool CrossS::velocityValues( ApplicationInfo& appInfo, ParamMap &params,
    }
    else
    {
-      ParamInfo* parLnsp = this->getParamInfo( appInfo,params,appInfo.LNSP(),key );
-      if ( ! parLnsp )  // LNSP not found
+      // It will always go to interpolate on the vertical because Magics
+      // can not interpolate wind arrows at the moment
+      if( appInfo.levelType() == XS_ML_LNSP )
       {
-         setError(1,"ERROR: Could not find parameter LNSP");
-         for (j = 0; j < nrLevels; j++)
-            delete [] cp[j];
-         delete [] cp;
-         return false;
-      }
+         ParamInfo* parLnsp = appInfo.getParamInfo( params,appInfo.LNSP(),key );
+         if ( ! parLnsp )  // LNSP not found
+         {
+            setError(1,"ERROR: Could not find parameter LNSP");
+            return false;
+         }
 
-      splin = appInfo.getOneLevelValues(parLnsp,"1");
-      if ( !splin )  // LNSP values not found
+         splin = parLnsp->getOneLevelValues("1");
+         if ( !splin )  // LNSP values not found
+         {
+            setError(1,"ERROR: Could not find LNSP Level values");
+            return false;
+         }
+
+         // Compute level values and interpolate matrix
+         appInfo.computeLevelInfoUI(&par_uv,y_values,splin,field);
+         appInfo.InterpolateVerticalb(field,cp,&par_uv,splin,y_values);
+      }
+      else
       {
-         setError(1,"ERROR: Could not find LNSP Level values");
-         for (j = 0; j < nrLevels; j++)
-            delete [] cp[j];
-         delete [] cp;
-         return false;
+         // Compute level values and interpolate matrix
+         appInfo.computeLevelInfoUI(&par_uv,y_values,splin,field);
+         appInfo.InterpolateVerticala(cp,&par_uv,y_values);
       }
-
-      // Compute level values and interpolate matrix
-      appInfo.computeLevelInfo(&par_uv,y_values,splin,field);
-      appInfo.InterpolateVerticalb(field,cp,&par_uv,splin,y_values);
    }
 
-   // Write UV values to the netCDF
-   ntime_++;
+   // Get/create the netCDF variable (x_component)
+   string varname = this->getNetcdfXComponentVarname();
+   MvNcVar *ncvx = this->getNetcdfVariable(cdf,varname,appInfo,varname,par_u);
+
+   // Write UV values to the netCDF (x_component)
+   int nrLevels = appInfo.outputLevels();
+   int nrPoints = appInfo.NrPoints();
+   ntime_ = 0;
+   int i;
    for ( i = 0; i < nrLevels; i++)
    {
-      ncv->setCurrent(ntime_,0,i);
-      ncv->put(cp[i],1,1,1,(long)nrPoints);
+      ncvx->setCurrent(ntime_,i);
+      ncvx->put(&cp[i*nrPoints],1,1,(long)nrPoints);
    }
 
-   // Now for the Velocity values
-   // Compute Velocity values
+   // Compute Velocity values (y_component)
    if( appInfo.levelType() != XS_ML_LNSP )
    {
       // Compute level values and interpolate matrix
-      appInfo.computeLevelInfo(par_w,y_values);
+      // Assume that the level values are the same as of x_component
+      //  appInfo.computeLevelInfo(par_w,y_values);
       appInfo.InterpolateVerticala(cp,par_w,y_values);
    }
    else
    {
       // Compute level values and interpolate matrix
-      appInfo.computeLevelInfo(par_w,y_values,splin,field);
+      // appInfo.computeLevelInfo(par_w,y_values,splin,field);
       appInfo.InterpolateVerticalb(field,cp,par_w,splin,y_values);
    }
 
-   // Write Velocity values to the netCDF
+   // Get/create the netCDF variable (y_component)
+   varname = this->getNetcdfYComponentVarname();
+   MvNcVar* ncvy = this->getNetcdfVariable(cdf,varname,appInfo,varname,par_w);
+
+   // Write Velocity values to the netCDF (y_component)
    for ( i = 0; i < nrLevels; i++ )
    {
-      ncv->setCurrent(ntime_,1,i);
-      ncv->put(cp[i],1,1,1,(long)nrPoints);
+      ncvy->setCurrent(ntime_,i);
+      ncvy->put(&cp[i*nrPoints],1,1,(long)nrPoints);
    }
 
-   // Release memory
-   for ( i = 0; i < nrLevels; i++)
-      delete [] cp[i];
-   delete [] cp;
+   // Compute level values
+   // Assume that the values are the same for the x and y component
+   if ( appInfo.isInterpolate() )
+      for ( i = 0; i < nrLevels ;i++ )
+         y_values[i] /= 100.;
+
+   // Get/create the netCDF variable (levels)
+   varname = "lev";
+   MvNcVar* ncvl = this->getNetcdfVariableLevel(cdf,varname,appInfo);
+
+   // Write level values to the netCDF
+   ncvl->setCurrent(ntime_);
+   ncvl->put(y_values,1,(long)y_values.size());
 
    return true;
 }
@@ -646,7 +695,8 @@ void CrossS::mapValues( ApplicationInfo& appInfo, ParamInfo &par_uv, ParamInfo *
             valuesuv[i] = XMISSING_VALUE;
       }
 
-      par_uv.Level(valuesuv,(*uu).first,nrPoints,appInfo.levelType());
+      bool modlev = appInfo.levelTypeFlag();
+      par_uv.Level(valuesuv,(*uu).first,nrPoints,modlev);
    }
 
    delete [] valuesuv;
@@ -701,11 +751,11 @@ bool CrossS::fillValues( ApplicationInfo& appInfo, MvField &field, double *vals
    return true;
 }
 
-MvRequest CrossS::createOutputRequest( ApplicationInfo& appInfo, string netcdfName, ParamInfo* parInfo )
+MvRequest CrossS::createOutputRequest( ApplicationInfo& appInfo, ParamInfo* parInfo )
 {
    // Create netCDF data request
    MvRequest xs("NETCDF");
-   xs("PATH") = netcdfName.c_str();
+   xs("PATH") = ncName_.c_str();
    xs("TEMPORARY") = 1;
 
    // Create NetCDF output request
@@ -729,13 +779,23 @@ MvRequest CrossS::createOutputRequest( ApplicationInfo& appInfo, string netcdfNa
       out1("NETCDF_X_GEOLINE_CONVENTION") = "lonlat";
    }
 
+   // Add X/Y Component, if this is the case
+   if ( inputMode_ == XVELOCITY )
+   {
+      out1("NETCDF_X_COMPONENT_VARIABLE") = (const char*)this->getNetcdfXComponentVarname().c_str();
+      out1("NETCDF_Y_COMPONENT_VARIABLE") = (const char*)this->getNetcdfYComponentVarname().c_str();
+
+      // Add flag to indicate that a MWIND visdef should be applied to this data
+      out1("_VISDEF") = "MWIND";
+   }
+
    // Add the orography curve visualiser
    if ( appInfo.haveLNSP() && (appInfo.levelType() == XS_ML_LNSP || appInfo.levelType() == XS_PL) )
    {
       MvRequest out_orog("NETCDF_XY_POINTS");
       out_orog("NETCDF_DATA") = xs;
-      out_orog("NETCDF_Y_VARIABLE")  = "orography_y1_values";
-      out_orog("NETCDF_Y2_VARIABLE") = "orography_y2_values";
+      out_orog("NETCDF_Y_VARIABLE")  = "orography_y2_values";
+      out_orog("NETCDF_Y2_VARIABLE") = "orography_y1_values";
       out_orog("NETCDF_X_VARIABLE")  = "orography_x_values";
       out_orog("NETCDF_X2_VARIABLE") = "orography_x_values";//"orography_x2_values";
       out_orog("NETCDF_MISSING_ATTRIBUTE") = "_FillValue";
@@ -768,6 +828,9 @@ MvRequest CrossS::createOutputRequest( ApplicationInfo& appInfo, string netcdfNa
         appInfo.levelType() != XS_ML_GHBC )  // UK MetOffice model levels and GHBC fields are 'upside-down'
       viewReq("_Y_AUTOMATIC_REVERSE") = "on";
 
+   if ( !appInfo.vLinearScaling() )
+      viewReq("VERTICAL_SCALING")= "log";
+
    // If action is not visualisation related then return the netcdf data.
    // Also, add the visualisation and original requests as hidden parameters.
    // These may be used later to help the visualisation of the netcdf data.
@@ -809,6 +872,22 @@ string CrossS::titleVariable( ApplicationInfo&, ParamInfo* par )
    return string(titlestr);
 }
 
+string CrossS::getNetcdfLevelVarname( string& varname )
+{
+   if ( inputMode_ == XVELOCITY )
+      return string("lev");
+
+   return Xsect::getNetcdfLevelVarname(varname);
+}
+
+string CrossS::getNetcdfVarname( const string& varname)
+{
+   if ( inputMode_ == XVELOCITY )
+      return getNetcdfXComponentVarname();
+
+   return Xsect::getNetcdfVarname(varname);
+}
+
 //------------------------------------------------------------------------------
 
 // All these methods are created to allow backwards compatibility with Metvew 3.
diff --git a/src/XSection/CrossS.h b/src/XSection/CrossS.h
index 8a5fbd6..831487a 100644
--- a/src/XSection/CrossS.h
+++ b/src/XSection/CrossS.h
@@ -43,7 +43,7 @@ public:
    bool generateData( ApplicationInfo&, ParamMap&, MvNetCDF&, MvField&, const string& );
 
    // Create output request
-   MvRequest createOutputRequest( ApplicationInfo&, string, ParamInfo*);
+   MvRequest createOutputRequest( ApplicationInfo&, ParamInfo*);
 
    // Check if parameters between two requests are consistent
    bool consistencyCheck( MvRequest&, MvRequest& );
@@ -69,11 +69,18 @@ private:
 
    string titleVariable( ApplicationInfo&, ParamInfo*);
 
+   // Get netCDF level variable name
+   string getNetcdfLevelVarname( string& );
+
+   // Get netCDF variable name
+   string getNetcdfVarname( const string& );
+
    // Variables
    bool foundUV_, foundW_;
    int hcNumber_, hcPerpendicular_, hcParallel_, hcIntensity_, currentHC_;
-   int inputMode_;      // XWIND, XVELOCITY, XCONTOUR
-   string oroColour_;   // orography colour
+   int inputMode_;        // XWIND, XVELOCITY, XCONTOUR
+   string oroColour_;     // orography colour
+   double wScaling_;      // w component scaling factor
 };
 
 //---------------------------------------------------------------------------------
diff --git a/src/XSection/MXSectionCommonDef b/src/XSection/MXSectionCommonDef
index 824ba3d..977aad6 100755
--- a/src/XSection/MXSectionCommonDef
+++ b/src/XSection/MXSectionCommonDef
@@ -77,3 +77,38 @@ VERTICAL_COORDINATE_PARAM
 {
    @
 }
+
+W_WIND_SCALING_FACTOR_MODE
+{
+    AUTOMATIC
+    USER
+} = AUTOMATIC
+
+W_WIND_SCALING_FACTOR
+{
+   *
+} = -100
+
+LEVEL_SELECTION_TYPE
+{
+   FROM_DATA
+   COUNT
+   LEVEL_LIST
+} = FROM_DATA
+
+LEVEL_LIST
+{
+   *
+   /
+} = 0.01/0.02/0.05/0.1/0.2/0.5/1/2/3/5/7/10/20/30/50/70/100/150/200/250/300/400/500/600/700/800/850/900/925/950/1000
+
+LEVEL_COUNT
+{
+   *
+} = 100
+
+VERTICAL_SCALING
+{
+   LINEAR
+   LOG
+} = LINEAR
diff --git a/src/XSection/MXSectionCommonRules b/src/XSection/MXSectionCommonRules
index 1c1b958..d29aa6f 100644
--- a/src/XSection/MXSectionCommonRules
+++ b/src/XSection/MXSectionCommonRules
@@ -1,2 +1,15 @@
 %if VERTICAL_COORDINATES = DEFAULT %then
    %unset VERTICAL_COORDINATE_PARAM
+
+%if LEVEL_SELECTION_TYPE = COUNT %then
+   %unset LEVEL_LIST
+
+%if LEVEL_SELECTION_TYPE = LEVEL_LIST %then
+   %unset LEVEL_COUNT
+
+%if LEVEL_SELECTION_TYPE = FROM_DATA %then
+   %unset LEVEL_COUNT
+   %unset LEVEL_LIST
+
+%if W_WIND_SCALING_FACTOR_MODE = AUTOMATIC %then
+    %unset W_WIND_SCALING_FACTOR
diff --git a/src/XSection/MXSectionDef b/src/XSection/MXSectionDef
index c040073..b8494e7 100644
--- a/src/XSection/MXSectionDef
+++ b/src/XSection/MXSectionDef
@@ -17,4 +17,14 @@ MXSECTION; Metview 4; Specific Application
     { @ }
 
    %include MXSectionCommonDef
+
+   BOTTOM_LEVEL
+   {
+      *
+   } = 1100.0
+
+   TOP_LEVEL
+   {
+      *
+   } = 0.01
 }
diff --git a/src/XSection/MXSectionRules b/src/XSection/MXSectionRules
index 47a13d9..1718a6c 100644
--- a/src/XSection/MXSectionRules
+++ b/src/XSection/MXSectionRules
@@ -1 +1,11 @@
 %include MXSectionCommonRules
+
+%if LEVEL_SELECTION_TYPE = FROM_DATA %then
+   %unset BOTTOM_LEVEL
+   %unset TOP_LEVEL
+   %unset VERTICAL_SCALING
+
+%if LEVEL_SELECTION_TYPE = LEVEL_LIST %then
+   %unset BOTTOM_LEVEL
+   %unset TOP_LEVEL
+   %unset VERTICAL_SCALING
diff --git a/src/XSection/MXSectionViewDef b/src/XSection/MXSectionViewDef
index 3c3b1d5..1515339 100644
--- a/src/XSection/MXSectionViewDef
+++ b/src/XSection/MXSectionViewDef
@@ -3,7 +3,7 @@ MXSECTIONVIEW; uPlot Icon; Metview
    BOTTOM_LEVEL
    {
       *
-   } = 1015.0
+   } = 1100.0
 
    TOP_LEVEL
    {
@@ -12,12 +12,6 @@ MXSECTIONVIEW; uPlot Icon; Metview
 
    %include MXSectionCommonDef
 
-   VERTICAL_SCALING
-   {
-      LINEAR
-      LOG
-   } = LINEAR
-
    MAP_PROJECTION  [ visible = false ]
    {
       cartesian
diff --git a/src/XSection/MvXsectFrame.cc b/src/XSection/MvXsectFrame.cc
index 0c7e893..5f7ee43 100644
--- a/src/XSection/MvXsectFrame.cc
+++ b/src/XSection/MvXsectFrame.cc
@@ -108,23 +108,35 @@ MvDate ParamInfo::VerificationDate()
    return MvDate(tt);
 }
 
+double* ParamInfo::getOneLevelValues( const string& clev )
+{
+   // Find the input level
+   LevelIterator ll = levels_.find(clev);
+   if ( ll == levels_.end() )
+      return 0;
+
+   return (*ll).second->XValues();
+}
+
 /////////////////// ApplicationInfo /////////////////////
 
 // Constructor
 ApplicationInfo::ApplicationInfo() :
                     x1_(0), x2_(0), y1_(0), y2_(0),
                     gridNS_(0), gridEW_(0),
-                    PresTop_(0),PresBot_(0),
-                    nrPoints_(0), nrLevels_(0), levType_(XS_PL),
+                    topLevel_(0),bottomLevel_(0),
+                    nrPoints_(0), nInputLevels_(0), nOutputLevels_(0),
+                    levType_(XS_PL),
                     viaPole_(false), haveLNSP_(false),
                     haveGHBC_(false), paramGHBC_(-991),
                     hor_point_("INTERPOLATE"),
-                    interpolate_(false)
+                    interpolate_(false),
+                    uiLSType_("FROM_DATA"),
+                    uiLSCount_(100),
+                    uiVLinearScaling_(true)
 { }
 
-// Check the level type info and update the levels accordingly
-// This info is not known when the parameters and levels were added.
-int ApplicationInfo::updateLevels(ParamMap& params, bool isML, bool isPL)
+int ApplicationInfo::levelType(bool isML, bool isPL)
 {
    // isML and isPL are both true if a fieldset contains LNSP and PL data.
    // In this case, treat as PL with LNSP.
@@ -146,6 +158,13 @@ int ApplicationInfo::updateLevels(ParamMap& params, bool isML, bool isPL)
          levType_ = XS_PL;
    }
 
+   return levType_;
+}
+
+// Check the level type info and update the levels accordingly
+// This info is not known when the parameters and levels were added.
+void ApplicationInfo::updateLevels(ParamMap& params)
+{
    // Get level type flag
    bool modlev = this->levelTypeFlag();
 
@@ -154,7 +173,7 @@ int ApplicationInfo::updateLevels(ParamMap& params, bool isML, bool isPL)
    for ( ii = params.begin(); ii != params.end(); ii++)
       (*ii).second->UpdateLevels(modlev);
    
-   return levType_;
+   return;
 }
 
 void ApplicationInfo::Grid( double ns, double ew )
@@ -292,7 +311,7 @@ void ApplicationInfo::computeLine(int& npoints, MvField* field )
 
 // Generate data values.
 // Only ever called if we use pressure levels or UKMO model levels
-void ApplicationInfo::InterpolateVerticala( double **cp,ParamInfo *param, vector<double>& yvals )
+void ApplicationInfo::InterpolateVerticala( vector<double>& cp, ParamInfo *param, vector<double>& yvals )
 {
    if ( ! interpolate_ )
    {
@@ -303,10 +322,13 @@ void ApplicationInfo::InterpolateVerticala( double **cp,ParamInfo *param, vector
    int i;
    double lpa,pk;
    LevelInfo *firstlev, *nextlev;
-   for ( int k = 0; k < nrLevels_; k++ )
+   int nrLevels = this->outputLevels();
+   cp.clear();
+   cp.reserve(nrLevels*nrPoints_);
+   for ( int k = 0; k < nrLevels; k++ )
    {
       // Invert Model level data, except for UKMO
-      //kmodel = (levType_ == cML_UKMO_ND) ? k : (nrLevels_)-k-1;
+      //kmodel = (levType_ == cML_UKMO_ND) ? k : (nrLevels)-k-1;
 
       //pk = GetInterpolatedYValue(k);
       pk = yvals[k];
@@ -327,20 +349,20 @@ void ApplicationInfo::InterpolateVerticala( double **cp,ParamInfo *param, vector
          for (i = 0; i < nrPoints_; i++ )
          {
             if ( xvals[i] < XMISSING_VALUE && xnext[i] < XMISSING_VALUE )
-               cp[k][i] = xvals[i] + ( xnext[i] - xvals[i]) *lpa; //replace k with kmodel
+               cp.push_back(xvals[i] + ( xnext[i] - xvals[i]) *lpa); //replace k with kmodel
             else
-               cp[k][i] = XMISSING_VALUE; // replace k with kmodel
+               cp.push_back(XMISSING_VALUE); // replace k with kmodel
          }
       }
       else
          for (i = 0;i < nrPoints_; i++)
-            cp[k][i] = XMISSING_VALUE;
+            cp.push_back(XMISSING_VALUE);
    }
 }
 
 // Generate data values.
 // Only ever called if levType_ == XS_ML_LNSP ie if we use non-UKMO model levels
-void ApplicationInfo::InterpolateVerticalb( MvField &field, double **cp, ParamInfo *param, double *splin, vector<double>& yvals )
+void ApplicationInfo::InterpolateVerticalb( MvField &field, vector<double>& cp, ParamInfo *param, double *splin, vector<double>& yvals )
 {
    if ( ! interpolate_ )
    {
@@ -348,49 +370,68 @@ void ApplicationInfo::InterpolateVerticalb( MvField &field, double **cp, ParamIn
       return;
    }
 
-   int i;
+   // Convert surface pressure
+   vector<double> sp;
+   sp.reserve(nrPoints_);
+   for (int i = 0; i < nrPoints_; i++)
+      sp.push_back(exp(splin[i]));
+
+   // Allocate memory for the output data
+   int nrLevels = outputLevels();
+   cp.clear();
+   cp.reserve(nrLevels*nrPoints_);
+
+   // Main loop
    double lpa;
-   double *sp = new double[nrPoints_];
    LevelInfo *firstlev,*nextlev;
    double  firstval, nextval;
-
-   for (i = 0; i < nrPoints_; i++)
-      sp[i] = exp(splin[i]);
-
-   for ( int k = 0; k < nrLevels_; k++ )
+   for ( int k = 0; k < nrLevels; k++ )
    {
       double pk = yvals[k];
 
       // Invert Model level data
-      for ( i = 0; i < nrPoints_; i++)
+      for ( int i = 0; i < nrPoints_; i++)
       {
          if ( sp[i] >= XMISSING_VALUE )
          {
-            cp[k][i] = XMISSING_VALUE;
+            cp.push_back(XMISSING_VALUE);
             continue;
          }
 
-         if ( findModelPressure( param->Levels(), pk, sp[i], field, firstlev, nextlev, firstval, nextval) )
+         if ( this->findModelPressure( param->Levels(), pk, sp[i], field, firstlev, nextlev, firstval, nextval) )
          {
             if ( firstlev->XValues()[i] < XMISSING_VALUE && nextlev->XValues()[i] < XMISSING_VALUE )
             {
                lpa = log(pk/firstval)/log(nextval/firstval);
-               cp[k][i] = firstlev->XValues()[i] + ( nextlev->XValues()[i] - firstlev->XValues()[i] ) * lpa;
+               cp.push_back(firstlev->XValues()[i] + ( nextlev->XValues()[i] - firstlev->XValues()[i] ) * lpa);
             }
             else
-               cp[k][i] = XMISSING_VALUE;
+               cp.push_back(XMISSING_VALUE);
          }
+         // Create more 'valid' points near the orography to avoid
+         // having empty areas in the plot
          else
-            cp[k][i] = XMISSING_VALUE;
+         {
+            bool useValue = false;
+            if (firstval < THRESHOLD_INTERPOLATION) // upper atmosphere?
+                useValue = fabs(pk - firstval) < (firstval*0.5); // close to 'real' level?
+            else
+                useValue = fabs(pk - firstval) < THRESHOLD_INTERPOLATION;
+            
+            if (useValue)
+               cp.push_back(firstlev->XValues()[i]);
+            else
+               cp.push_back(XMISSING_VALUE); 
+         }
       }
    }
 
-   delete [] sp;
+   return;
 }
 
 // Generate data values.
 // Only ever called if levType_ == XS_ML_GHBC
-void ApplicationInfo::InterpolateVerticalGHBC( double **cp, ParamInfo *param, ParamInfo *paramGHBC, vector<double>& yvals )
+void ApplicationInfo::InterpolateVerticalGHBC( vector<double>& cp, ParamInfo *param, ParamInfo *paramGHBC, vector<double>& yvals )
 {
    if ( ! interpolate_ )
    {
@@ -405,7 +446,10 @@ void ApplicationInfo::InterpolateVerticalGHBC( double **cp, ParamInfo *param, Pa
 
    LevelIterator ii = param->Levels().begin();
    LevelIterator jj = paramGHBC->Levels().begin();
-   for ( int k = 0; k < nrLevels_; k++, ii++, jj++ )
+   int nrLevels = this->outputLevels();
+   cp.clear();
+   cp.reserve(nrLevels*nrPoints_);
+   for ( int k = 0; k < nrLevels; k++, ii++, jj++ )
    {
       double pk = yvals[k];                    // pressure level index
       double* pval = (*ii).second->XValues();  // param X values
@@ -416,7 +460,7 @@ void ApplicationInfo::InterpolateVerticalGHBC( double **cp, ParamInfo *param, Pa
          // Ignore missing values
          if ( pval[i] >= XMISSING_VALUE )
          {
-            cp[k][i] = XMISSING_VALUE;
+            cp.push_back(XMISSING_VALUE);
             continue;
          }
 
@@ -425,19 +469,19 @@ void ApplicationInfo::InterpolateVerticalGHBC( double **cp, ParamInfo *param, Pa
             if ( firstlev->XValues()[i] < XMISSING_VALUE && nextlev->XValues()[i] < XMISSING_VALUE )
             {
                if ( firstval == 0. && nextval == 0. )
-                  cp[k][i] = firstlev->XValues()[i];
+                  cp.push_back(firstlev->XValues()[i]);
                else
                {
                   //lpa = log(pk/firstval)/log(nextval/firstval);
                   lpa = (pk - firstval) / (nextval - firstval);
-                  cp[k][i] = firstlev->XValues()[i] + ( nextlev->XValues()[i] - firstlev->XValues()[i] ) * lpa;
+                  cp.push_back(firstlev->XValues()[i] + ( nextlev->XValues()[i] - firstlev->XValues()[i] ) * lpa);
                }
             }
             else
-               cp[k][i] = XMISSING_VALUE;
+               cp.push_back(XMISSING_VALUE);
          }
          else
-            cp[k][i] = XMISSING_VALUE;
+            cp.push_back(XMISSING_VALUE);
       }
    }
 
@@ -478,6 +522,15 @@ bool ApplicationInfo::findModelPressure( LevelMap& lmap, double value, double sp
    ii++;
    tmpval1 = field.meanML_to_Pressure_bySP(splin,(int)(tmpl1->YValue()));
 
+   // desired pressure above (in the atmosphere) the top (first) level in the data?
+   if (value < tmpval1)
+   {
+      val1 = tmpval1;
+      l1 = tmpl1;
+      return false;
+   }
+
+
    for (; ii != lmap.end(); ii++ )
    {
       tmpl2 = (*ii).second;
@@ -548,7 +601,7 @@ void ApplicationInfo::scaleVelocity(ParamInfo *par)
    double dist = 110442.3*sqrt (dellat*dellat + dellona*dellona);
 
    double hscale = 21./dist;
-   double vscale = 12./(PresBot_ - PresTop_);
+   double vscale = 12./(bottomLevel_ - topLevel_);
 
    if (levType_ == XS_ML )
       vscale = 12./(100 * 1000);
@@ -571,20 +624,62 @@ void ApplicationInfo::scaleVelocity(ParamInfo *par)
    return;
 }
 
+void ApplicationInfo::scaleVelocityPB(ParamInfo *par)
+{
+   LevelMap lmap = par->Levels();
+   LevelIterator ii = lmap.begin();
+
+   double *values;
+   for ( ; ii  != lmap.end(); ii++ )
+   {
+      values = (*ii).second->XValues();
+      double P = (*ii).second->YValue();
+      for (int i=0; i<nrPoints_; i++)
+      {
+         if (values[i] < XMISSING_VALUE)
+            values[i] = values[i] / (-9.8 * P/(286.*273.));
+         else
+            values[i] = XMISSING_VALUE;
+      }
+   }
+
+   return;
+}
+
+void ApplicationInfo::scaleVelocity1(ParamInfo *par, double factor)
+{
+   LevelMap lmap = par->Levels();
+   LevelIterator ii = lmap.begin();
+
+   double *values;
+   for ( ; ii  != lmap.end(); ii++ )
+   {
+      values = (*ii).second->XValues();
+      for (int i=0; i<nrPoints_; i++)
+      {
+         if (values[i] < XMISSING_VALUE)
+            values[i] *= factor;
+         else
+            values[i] = XMISSING_VALUE;
+      }
+   }
+
+   return;
+}
+
 void ApplicationInfo::setMinMaxLevels( double P1, double P2, int nlevel )
 {
-    PresBot_ = P1;
-    PresTop_ = P2;
+    bottomLevel_ = P1;
+    topLevel_ = P2;
 
-//    nrLevels_ = (!nlevel || interpolate_) ? 85 : nlevel;
-    nrLevels_ = nlevel;
+    nInputLevels_ = nlevel;
 }
 
 void ApplicationInfo::getMinMaxLevels( double& P1, double& P2, int& nlevel )
 {
-    P1 = PresBot_;
-    P2 = PresTop_;
-    nlevel = nrLevels_;
+    P1 = bottomLevel_;
+    P2 = topLevel_;
+    nlevel = nInputLevels_;
 }
 
 #if 0
@@ -645,30 +740,125 @@ void ApplicationInfo::setYValues(MvNcVar *yvar, ParamInfo *par)
 }
 #endif
 
-void ApplicationInfo::computeLevelInfo( ParamInfo* par, vector<double>& vals )
+bool ApplicationInfo::computeLevelMatrixValues ( ParamMap& params, const string& key,
+                                                   vector<double>& y_values,
+                                                   vector<double>& cp,
+                                                   MvField& field )
+{
+   // Get parameter info
+   ParamIterator ii = params.find(key);
+   ParamInfo *par = (*ii).second;
+
+   // Compute values
+   double* splin = 0;
+   if( levType_ == XS_ML_LNSP )
+   {
+      // Get LNSP values
+      ParamInfo* parLnsp = this->getParamInfo( params,LNSP_FIELD,key );
+      if ( ! parLnsp )
+      {
+         cout << "ERROR: Could not find parameter LNSP" << endl;
+         return false;
+      }
+
+      splin = parLnsp->getOneLevelValues("1");
+      if ( !splin )  // LNSP not found
+      {
+         cout << "ERROR: Could not find LNSP Level values" << endl;
+         return false;
+      }
+
+      // Compute level values
+      this->computeLevelInfoUI(par,y_values,splin,field);
+
+      // Interpolate matrix
+      this->InterpolateVerticalb(field,cp,par,splin,y_values);
+   }
+   else if (levType_ == XS_ML_GHBC ) // handle height-based coordinates
+   {
+      // Get extra values
+      ParamInfo* parGHBC = this->getParamInfo( params,paramGHBC_,key );
+      if ( ! parGHBC )
+      {
+         cout << "ERROR: Could not find parameter GHBC" << endl;
+         return false;
+      }
+
+      // Compute level values
+      this->computeLevelInfoGHBC(parGHBC,y_values);
+
+      // Interpolate matrix
+      this->InterpolateVerticalGHBC(cp,par,parGHBC,y_values);
+   }
+   else
+   {
+      // Compute level values
+      this->computeLevelInfoUI(par,y_values,splin,field);
+
+      // Interpolate matrix
+      this->InterpolateVerticala(cp,par,y_values);
+   }
+
+   return true;
+}
+
+int ApplicationInfo::computeLevelInfoUI( ParamInfo* par, vector<double>& vals, double* splin, MvField& field )
+{
+   // Compute the levels according to the parameters given in the user interface
+   if ( uiLSType_ == "FROM_DATA" )
+   {
+      if ( splin == 0 )
+         return this->computeLevelInfo( par,vals );
+      else
+         return this->computeLevelInfo( par,vals,splin,field );
+   }
+   else if ( uiLSType_ == "COUNT" )
+   {
+      LevelMap lmap = par->Levels();
+      nInputLevels_ = lmap.size();
+      return this->computeLevelInfo( vals );
+   }
+   else
+   {
+      vals = this->levelList();
+      nOutputLevels_ = vals.size();
+      nInputLevels_  = vals.size();
+      return nOutputLevels_;
+   }
+}
+
+int ApplicationInfo::computeLevelInfo( ParamInfo* par, vector<double>& vals )
 {
    // Get levels
-   double factor = this->levelTypeFlag() ? 1. : 100.;
-   vals.reserve(nrLevels_);
    LevelMap lmap = par->Levels();
+   int nrLevels = lmap.size();
+   vals.clear();
+   vals.reserve(nrLevels);
    for ( LevelIterator jj = lmap.begin(); jj != lmap.end(); jj++ )
-      vals.push_back( (*jj).second->YValue() / factor );
+      vals.push_back( (*jj).second->YValue() );
 
-   return;
+   nInputLevels_ = nOutputLevels_ = nrLevels;
+
+   return nrLevels;
 }
 
-void ApplicationInfo::computeLevelInfo( ParamInfo* par, vector<double>& vals, double* splin, MvField& field )
+int ApplicationInfo::computeLevelInfo( ParamInfo* par, vector<double>& vals, double* splin, MvField& field )
 {
-   // Convert ML&LNSP to PL using the following algorithm: for each ML value
-   // (1,2,...N) get all the correspondent values and compute the average
+   // Convert ML&LNSP to PL using the following algorithm:
+   // a) for each ML value (1,2,...N) get all the correspondent values
+   //    and compute the average
+   // b) compute extra levels by adding an offset (10 hPa) until reaches the highest
+   //    pressure value (bottomLevel_), which was computed previously.
    if ( levType_ != XS_ML_LNSP )
    {
-      this->computeLevelInfo( par,vals );
-      return;
+      return this->computeLevelInfo( par,vals );
    }
 
-   vals.reserve(nrLevels_);
+   // Part A: compute "average" levels 
    LevelMap lmap = par->Levels();
+   int nrLevels = lmap.size();
+   vals.clear();
+   vals.reserve(nrLevels);  // initial allocation, it will increase in part B
    for ( LevelIterator jj = lmap.begin(); jj != lmap.end(); jj++ )
    {
       LevelInfo *lInfo = (*jj).second;
@@ -687,15 +877,59 @@ void ApplicationInfo::computeLevelInfo( ParamInfo* par, vector<double>& vals, do
       vals.push_back(mean);
    }
 
-   return;
+   // Part B: add extra levels
+   double level1 = vals[nrLevels-1] + OFFSET_LEVELINFO;
+   while ( level1 <= bottomLevel_ )
+   {
+      vals.push_back(level1);
+      level1 += OFFSET_LEVELINFO;
+   }
+
+   // Assume that the visualisation will be in the Log space too
+   uiVLinearScaling_ = false;
+
+   nInputLevels_ = nrLevels;
+   nOutputLevels_ = vals.size();
+
+   return nOutputLevels_;
+}
+
+int ApplicationInfo::computeLevelInfo( vector<double>& vals )
+{
+   // Initialize array
+   vals.clear();
+   vals.reserve(uiLSCount_);
+
+   if ( uiVLinearScaling_ )
+   {
+      // Compute equal separated levels
+      double zdp = ( bottomLevel_ - topLevel_) / double (uiLSCount_ - 1);
+      for (int i = 0; i < uiLSCount_; i++)
+         vals.push_back(topLevel_ + i*zdp);
+   }
+   else
+   {
+      // Compute levels using a log scaling 
+      double logBottomLevel = log(bottomLevel_);
+      double logTopLevel = log(topLevel_);
+      double zdp = ( logBottomLevel - logTopLevel) / double (uiLSCount_ - 1);
+      for (int i = 0; i < uiLSCount_; i++)
+         vals.push_back(exp(logTopLevel + i*zdp));
+   }
+
+   nOutputLevels_ = uiLSCount_;
+
+   return nOutputLevels_;
 }
 
-void ApplicationInfo::computeLevelInfoGHBC( ParamInfo* par, vector<double>& vals )
+int ApplicationInfo::computeLevelInfoGHBC( ParamInfo* par, vector<double>& vals )
 {
    // Convert ML&GHBC to PL using the following algorithm: for each ML value
    // (1,2,...N) get all the correspondent values and compute the average
-   vals.reserve(nrLevels_);
    LevelMap lmap = par->Levels();
+   int nrLevels = lmap.size();
+   vals.clear();
+   vals.reserve(nrLevels);
    double xval;
    for ( LevelIterator jj = lmap.begin(); jj != lmap.end(); jj++ )
    {
@@ -716,17 +950,20 @@ void ApplicationInfo::computeLevelInfoGHBC( ParamInfo* par, vector<double>& vals
       vals.push_back(mean);
    }
 
-   return;
+   nInputLevels_ = nOutputLevels_ = nrLevels;
+
+   return nrLevels;
 }
 
-void ApplicationInfo::getLevelValues( ParamInfo *par, double **cp )
+void ApplicationInfo::getLevelValues( ParamInfo *par, vector<double>& cp )
 {
    LevelMap lmap = par->Levels();
    LevelIterator ii;
 
 #if 1
-   int k = 0;
-   for (ii = lmap.begin(); ii != lmap.end(); ii++, k++ )
+   cp.clear();
+   cp.reserve(lmap.size() * nrPoints_);
+   for (ii = lmap.begin(); ii != lmap.end(); ii++ )
 
 #else
    int nrY = NrYValues(par);
@@ -745,21 +982,10 @@ void ApplicationInfo::getLevelValues( ParamInfo *par, double **cp )
    {
       LevelInfo *lInfo = (*ii).second;
       for (int i = 0; i < nrPoints_; i++ )
-         cp[k][i] = lInfo->XValues()[i];
+         cp.push_back(lInfo->XValues()[i]);
    }
 }
 
-double* ApplicationInfo::getOneLevelValues( ParamInfo* par, const string& clev )
-{
-   // Find the input level
-   LevelMap levelMap = par->Levels();
-   LevelIterator ll = levelMap.find(clev);
-   if ( ll == levelMap.end() )
-      return 0;
-
-   return (*ll).second->XValues();
-}
-
 #if 0
 double ApplicationInfo::GetInterpolatedYValue(int index)
 {
@@ -831,3 +1057,67 @@ bool ApplicationInfo::levelTypeFlag()
     else
         return true;
 }
+
+void ApplicationInfo::setVerticalInterpolationFlag()
+{
+   if (levType_ == XS_ML_LNSP || levType_ == XS_ML_GHBC)
+      interpolate_ = true;
+   else if (uiLSType_ == "COUNT" || uiLSType_ == "LEVEL_LIST")
+      interpolate_ = true;
+   else
+      interpolate_ = false;
+
+   return;
+}
+
+void ApplicationInfo::setVerticalInterpolationFlag( bool flag )
+{
+   interpolate_ = flag;
+}
+
+ParamInfo* ApplicationInfo::getParamInfo( ParamMap &params, const string& key )
+{
+   // Check if field is valid
+   ParamIterator ii = params.find(key);
+   if ( ii == params.end() )
+   {
+      cout << "ERROR: Could not find the requested field (getParamInfo)" << endl;
+      return 0;
+   }
+
+   // Get parameter info
+   return (*ii).second;
+}
+
+ParamInfo* ApplicationInfo::getParamInfo( ParamMap &params, int key, const string& keyBase )
+{
+   // Build the new key based on keyBase
+   char newKey[60];
+   sprintf(newKey,"p%06d%s",key,keyBase.substr(7,50).c_str() );
+
+   // Get paraminfo
+   ParamInfo* par = this->getParamInfo( params, newKey );
+   if ( par )
+      return par;
+
+   // Special case: if paramInfo not found and key is "extra" (LNSP or GHBC)
+   // then try to find any other "extra" paramInfo (do not use the keyBase info)
+   if ( this->isLNSP(key) || this->isGHBC(key) )
+   {
+      for ( ParamIterator ii = params.begin(); ii != params.end(); ii++ )
+      {
+         par = (*ii).second;
+         if ( par->Parameter() == key )
+            return par;
+      }
+   }
+
+   return par;
+}
+
+void ApplicationInfo::levelList( vector<double>& list )
+{
+   uiLSList_ = list;
+   topLevel_ = list[0];
+   bottomLevel_ = list[list.size()-1];
+}
diff --git a/src/XSection/MvXsectFrame.h b/src/XSection/MvXsectFrame.h
index b8b8c16..badfce8 100644
--- a/src/XSection/MvXsectFrame.h
+++ b/src/XSection/MvXsectFrame.h
@@ -19,6 +19,13 @@
 
 const double XMISSING_VALUE = 1.0E22;
 
+// Used in the interpolation procedure to create more 'valid' points near 
+// the orography. This is to avoid having empty areas in the plot.
+const double THRESHOLD_INTERPOLATION = 3000.; // 30hPa
+
+// Offset used to add extra levels when converting model to pressure levels
+const float OFFSET_LEVELINFO = 1000.;  // 10hPa
+
 // Level type data combined with specific fields
 // Values are: model level, pressure level, model level + lnsp, model level + GHBC
 // cML_UKMO_ND =  n;       // UKMO New Dynamics - defined elsewhere
@@ -135,6 +142,8 @@ public:
      return ( p1.param_ < p2.param_ || p1.date_ < p2.date_ || p1.time_ < p2.time_ || p1.step_ < p2.step_ );
   }
 
+  double* getOneLevelValues( const string& );
+
 private:
 
   int param_, date_, step_, time_;
@@ -161,11 +170,10 @@ public:
   // Constructor
   ApplicationInfo();
 
-  void levelType(int lt) { levType_ = lt; }
-  int  levelType() { return levType_; }
-  bool levelTypeFlag();
-  double PresTop() { return PresTop_; }
-  double PresBot() { return PresBot_; }
+  double topLevel() { return topLevel_; }
+  double bottomLevel() { return bottomLevel_; }
+  void topLevel( double d ) { topLevel_ = d; }
+  void bottomLevel( double d ) { bottomLevel_ = d; }
 
   // Handle geographical coordinates
   void computeLine( int );
@@ -201,26 +209,35 @@ public:
   void NTimes( int ntimes ) { ntimes_ = ntimes; }
 
   // Handle level info
-  int updateLevels(ParamMap&, bool, bool);
+  void levelType( int lt ) { levType_ = lt; }
+  int  levelType() { return levType_; }
+  int levelType( bool, bool );
+  bool levelTypeFlag();
+  void updateLevels( ParamMap& );
   void setMinMaxLevels( double, double, int=0 );
   void getMinMaxLevels( double&, double&, int& );
-  int NrLevels() { return nrLevels_; }
-//  int NrYValues(ParamInfo *par ) { return interpolate_ ? 2 : par->NrLevels(); }
-//  int NrLevels(ParamInfo *par ) { return interpolate_ ? nrLevels_ : par->NrLevels(); }
+  void outputLevels( int n ) { nOutputLevels_ = n; }
+  int outputLevels() { return nOutputLevels_; }
 
   // Get level values
-  void getLevelValues( ParamInfo*, double** );
-  double* getOneLevelValues( ParamInfo*, const string& );
+  void getLevelValues( ParamInfo*, vector<double>& );
 
   // Compute indexes levels (vertical values)
-  void computeLevelInfo ( ParamInfo*, vector<double>& );  // model/pressure level
-  void computeLevelInfo ( ParamInfo*, vector<double>&, double*, MvField& ); // model level & LNSP
-  void computeLevelInfoGHBC ( ParamInfo*, vector<double>&  ); // model level & GHBC
+  int computeLevelInfoUI( ParamInfo*, vector<double>&, double*, MvField& ); // from UI
+  int computeLevelInfo ( ParamInfo*, vector<double>& );  // model/pressure level
+  int computeLevelInfo ( ParamInfo*, vector<double>&, double*, MvField& ); // model level & LNSP
+  int computeLevelInfo ( vector<double>& );  // compute equal separated levels
+  int computeLevelInfoGHBC ( ParamInfo*, vector<double>&  ); // model level & GHBC
+
+  bool computeLevelMatrixValues ( ParamMap&, const string&, vector<double>&, vector<double>&, MvField& );
+  
+  void scaleVelocity(ParamInfo*);
+void scaleVelocityPB(ParamInfo*);
+void scaleVelocity1(ParamInfo*,double);
 
-  void scaleVelocity(ParamInfo *);
-  void InterpolateVerticala(double**,ParamInfo*,vector<double>&);
-  void InterpolateVerticalb(MvField&,double**,ParamInfo*,double*,vector<double>&);
-  void InterpolateVerticalGHBC(double**,ParamInfo*,ParamInfo*,vector<double>&);
+  void InterpolateVerticala(vector<double>&,ParamInfo*,vector<double>&);
+  void InterpolateVerticalb(MvField&,vector<double>&,ParamInfo*,double*,vector<double>&);
+  void InterpolateVerticalGHBC(vector<double>&,ParamInfo*,ParamInfo*,vector<double>&);
 
   bool findModelPressure(LevelMap&, double, double, MvField&, LevelInfo*&, LevelInfo*&, double&, double&);
 
@@ -230,8 +247,14 @@ public:
 
   bool generateAverageData(ParamMap&, MvNetCDF&, const string&, MvField&, double*, double* , double*);
 
-//  bool Interpolate() { return interpolate_; }
-  void Interpolate(bool xx) { interpolate_ = xx; }
+  // Handle vertical interpolation settings
+  // Two ways to set a vertical interpolation flag: 
+  // a) model to pressure level (setVerticalInterpolationFlag)
+  // b) wind plotting (setVerticalInterpolationFlag(flag). This
+  //    is because Magics is not doing the interpolation for winds.
+  void setVerticalInterpolationFlag();
+  void setVerticalInterpolationFlag( bool );
+  bool isInterpolate() { return interpolate_; }
 
   bool viaPole()  {return viaPole_;}
   
@@ -253,15 +276,35 @@ public:
   string horPointMode() { return hor_point_; }
   bool isHorInterpolate() { return hor_point_ == "INTERPOLATE"; }
 
+  // Retrieve information about one parameter
+  ParamInfo* getParamInfo( ParamMap&, const string& );
+  ParamInfo* getParamInfo( ParamMap&, int, const string& );
+
+  // Handle parameters retrieved from the User Interface
+  string levelSelectionType() { return uiLSType_; }
+  void levelSelectionType( const string& type ) { uiLSType_ = type; }
+
+  int levelCount() { return uiLSCount_; }
+  void levelCount( int count ) { uiLSCount_ = count; }
+
+  vector<double> levelList() { return uiLSList_; }
+  void levelList( vector<double>& );
+
+  bool vLinearScaling() { return uiVLinearScaling_; }
+  void vLinearScaling( bool bvs ) { uiVLinearScaling_ = bvs; }
+
 private:
 
   double GetInterpolatedYValue(int);
 
   double x1_, x2_, y1_, y2_;
   double gridNS_, gridEW_;
-  double PresTop_, PresBot_;
+  double topLevel_, bottomLevel_;
 
-  int nrPoints_, nrLevels_, ntimes_;
+  int nrPoints_;             // number of horizontal points
+  int nInputLevels_;         // number of input data model/pressure levels
+  int nOutputLevels_;        // number of output levels (may be different than nInputLevels_)
+  int ntimes_;               // number of times
   int levType_;              // level type data, e.g., XS_ML/XS_PL/XS_ML_LNSP/XS_ML_GHBC
   bool viaPole_;
   bool haveLNSP_;
@@ -274,13 +317,14 @@ private:
   vector<double> lat_;       // geographical coordinates
   vector<double> lon_;
 
-  // Remove this variable in the future
-  // It is kept for the moment because we need to make further
-  // tests. The idea is that this application should allways give back
-  // the original data values. The only exception is when a conversion
-  // from model level to pressure level is required. In this case an
-  // interpolation scheme is performed
-  bool interpolate_;
+  bool interpolate_;         // vertical interpolation flag
+
+  // Parameters from the User Interface
+  string uiLSType_;          // level selection type: FROM_DATA, COUNT, LEVEL_LIST
+  int uiLSCount_;            // level selection count
+  vector<double> uiLSList_;  // level list
+  bool uiVLinearScaling_;    // vertical scaling: [true=LINEAR, false=LOG]
+
 };
 
 #endif
diff --git a/src/XSection/Vprofile.cc b/src/XSection/Vprofile.cc
index 40d0f96..7934a01 100644
--- a/src/XSection/Vprofile.cc
+++ b/src/XSection/Vprofile.cc
@@ -578,7 +578,7 @@ bool Vprofile::generateSurftype( MvNetCDF& cdf, ApplicationInfo& appInfo, ParamM
    return true;
 }
 
-MvRequest Vprofile::createOutputRequest( ApplicationInfo& appInfo, string netcdfName, ParamInfo* parInfo )
+MvRequest Vprofile::createOutputRequest( ApplicationInfo& appInfo, ParamInfo* parInfo )
 {
    // Create netCDF data request
    // Get output data verb
@@ -591,7 +591,7 @@ MvRequest Vprofile::createOutputRequest( ApplicationInfo& appInfo, string netcdf
       verb = "NETCDF";
 
    MvRequest xs(verb.c_str());
-   xs("PATH") = netcdfName.c_str();
+   xs("PATH") = ncName_.c_str();
    xs("TEMPORARY") = 1;
 
    // Create netCDF output request
@@ -633,7 +633,7 @@ bool Vprofile::generateData ( ApplicationInfo& appInfo, ParamMap &params,
                               MvNetCDF& cdf, MvField&, const string& key )
 {
    // Get parameter info
-   ParamInfo *par = this->getParamInfo(params,key);
+   ParamInfo *par = appInfo.getParamInfo(params,key);
    if ( !par )
       return false;
 
diff --git a/src/XSection/Vprofile.h b/src/XSection/Vprofile.h
index 904e314..658747e 100644
--- a/src/XSection/Vprofile.h
+++ b/src/XSection/Vprofile.h
@@ -52,7 +52,7 @@ public:
    bool getAppParameters( MvRequest&, ApplicationInfo& );
 
    // Create output request
-   MvRequest createOutputRequest( ApplicationInfo&, string, ParamInfo* );
+   MvRequest createOutputRequest( ApplicationInfo&, ParamInfo* );
 
    int computeGeographicalPoints( ApplicationInfo&, MvField* = 0 );
 
diff --git a/src/XSection/Xsect.cc b/src/XSection/Xsect.cc
index fd40b50..4a079d6 100644
--- a/src/XSection/Xsect.cc
+++ b/src/XSection/Xsect.cc
@@ -35,10 +35,10 @@
 
 Xsect::Xsect(const char* kw) :
              MvService(kw),
+             ncName_("toto.nc"),
              ntime_(0)
 {}
 
-
 void Xsect::serve(MvRequest& in,MvRequest& out)
 {
 cout << "request IN" << endl;
@@ -99,15 +99,15 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
    if( appInfo.viaPole() )
       setError( 0, "Xsect line via Pole" );
 
-   // Memory allocation
-   double *xint  = new double [ npoint ];
+   // Allocate memory/initialise auxiliary variables
+   double* xint = new double [ npoint ];
+   ParamMap params;
 
    // First loop: build field keystring and get the Level info.
    // The LNSP matrix data is computed, if it exists, but the other
    // matrices are computed in the second loop.
    boolean isPL = false;
    boolean isML = false;
-   ParamMap params;
    string keystr;
    bool foundU = false, foundV = false, foundW = false;
    int iparam, idate, itime, istep;
@@ -130,7 +130,10 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
       // Check that this field's vital statistics match those of the others
       // - this is important only in the Average application
       if ( !fieldConsistencyCheck(field,north,south,east,west) )
+      {
+         deleteAuxiliaryMemory(xint,params);
          return false;
+      }
 
       // Update level info accordingly
       if( !lev || !strcmp(lev, "0") || field.levelTypeString() == cML_UKMO_ND_STR )
@@ -165,6 +168,7 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
             // in the marslog file. That said, the user should be told, otherwise
             // they stare at  a blank plot!
             setError(1, "Error when filling the values.");
+            deleteAuxiliaryMemory(xint,params);
             return false;
          }
 
@@ -207,24 +211,28 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
       }
    } //end while (first loop)
 
-   // Update INTERPOLATE_VALUES parameter
-//   this->updateInterpolateValues(appInfo);
+   // Update level processing type, i.e. XS_ML/XS_PL/XS_ML_LNSP/XS_ML_GHBC
+   // This function will update an internal flag according to the type of
+   // level from the input data. This information is only available after
+   // the end of the First Loop above.
+   int levType = appInfo.levelType(isML,isPL);
 
-   // Check if fieldset is compatible with the application
-   if ( this->consistencyCheck( params ) == false )
+   // Check if the input fieldset is compatible with the application
+   // and with the parameters given in the UI
+   if ( this->consistencyCheck( params,appInfo ) == false )
    {
-      setError(1,"ERROR: Consistency check failed");
+      setError(1,"ERROR: Fieldset consistency check failed");
+      deleteAuxiliaryMemory(xint,params);
       return false;
    }
 
    // Update/initialize level type info
-   int levType = appInfo.updateLevels(params,isML,isPL);
+   appInfo.updateLevels(params);
    bool modlev = appInfo.levelTypeFlag();
 
-   //IMPORTANT???????????????????
-   // REMOVE THIS CODE LATER
-   if ( appInfo.levelType() == XS_ML_LNSP || appInfo.levelType() == XS_ML_GHBC)
-      appInfo.Interpolate(true);
+   // Set default interpolation flag.
+   // This can be updated later, e.g. velocityValues
+   appInfo.setVerticalInterpolationFlag();
 
    // Update flags
    this->setHorCompFlags(foundU,foundV,foundW);
@@ -236,30 +244,16 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
    if ( this->updateTopBottomLevels( appInfo, params, levType, iter, pBottom, pTop, nlevel ) )
       appInfo.setMinMaxLevels( pBottom, pTop, nlevel );
 
-   // Create a temporary netCDF file
-   string netcdfName(marstmp());
-   MvNetCDF netcdf(netcdfName,'w');
-   if ( !netcdf.isValid() )
-   {
-      setError(1,"ERROR: Could not open netCDF file");
-      return false;
-   }
-
-   // Write netCDF global attributes
-   if ( !this->writeGlobalAttributesNetcdf(netcdf,params,appInfo) )
-      return false;
-
-   // Write initial variables to the netCDF file: levels, time,
-   // geographical coordinates
+   // Create/initialise netCDF structure
+   MvNetCDF netcdf;
    iter.rewind();
    field = iter();
    int ntimes;
-   if ( !this->writeLevelInfoNetcdf(netcdf,appInfo,params,&field,xint) )
-      return false;
-   if ( !this->writeTimeInfoNetcdf(netcdf,params,ntimes) )
-      return false;
-   if ( !this->writeGeoCoordsNetcdf( netcdf, appInfo ) )
+   if ( !this->initialiseNetcdf(netcdf,params,appInfo,ntimes,field,xint) )
+   {
+      deleteAuxiliaryMemory(xint,params);
       return false;
+   }
 
    // Update application info: number of times
    appInfo.NTimes (ntimes);
@@ -322,6 +316,7 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
             // in the marslog file. That said, the user should be told, otherwise
             // they stare at  a blank plot!
             setError(1, "Error when filling the values.");
+            deleteAuxiliaryMemory(xint,params);
             return false;
          }
 
@@ -340,6 +335,7 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
          if ( !generateData(appInfo,params,netcdf,lastField,lastKey) )
          {
             setError(1,"Could not generate NETCDF data: error on fieldset or fieldset not suitable");
+            deleteAuxiliaryMemory(xint,params);
             return false;
          }
          lastNrGenerated = currentGenerated;
@@ -355,6 +351,7 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
       if ( !generateData(appInfo,params,netcdf,lastField,lastKey) )
       {
          setError(1,"Could not generate NETCDF data: error on fieldset or fieldset not suitable");
+         deleteAuxiliaryMemory(xint,params);
          return false;
       }
    }
@@ -363,6 +360,7 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
    if ( ! this->generateExtraData(netcdf,appInfo,params,iter) )
    {
       setError(1,"Could not generate NETCDF extra data");
+      deleteAuxiliaryMemory(xint,params);
       return false;
    }
 
@@ -372,17 +370,15 @@ bool Xsect::processData( MvRequest& data, ApplicationInfo& appInfo, MvRequest& o
    // Get default parameter to be plotted
    ParamInfo* parInfo = plotVariable(appInfo,params);
    if ( !parInfo )
+   {
+      deleteAuxiliaryMemory(xint,params);
       return false;
+   }
 
    // Create output request
-   out = this->createOutputRequest( appInfo, netcdfName, parInfo );
-
-   // Release memory allocation
-   delete [] xint;  xint = 0;
+   out = this->createOutputRequest( appInfo, parInfo );
 
-   // Free memory for parameters
-   for (paramIter = params.begin(); paramIter != params.end(); paramIter++)
-      delete (*paramIter).second;
+   deleteAuxiliaryMemory(xint,params);
 
    return true;
 }
@@ -529,7 +525,6 @@ bool Xsect::getInputParameters( MvRequest& in, MvRequest& data, ApplicationInfo&
 
    // Type of input request is a DATA_DROPPED into a View
    // Get information from the View request
-   double pBottom=0., pTop=0.;
    if ( procType == XS_DATA_DROPPED )
    {
       // Retrieve 'original' request from the View
@@ -573,7 +568,6 @@ bool Xsect::getInputParameters( MvRequest& in, MvRequest& data, ApplicationInfo&
    string actionMode = (const char*)in("_ACTION") ? (const char*)in("_ACTION") : "prepare";
 
    // Save info
-   appInfo.setMinMaxLevels( pBottom, pTop );
    appInfo.actionMode(actionMode);
    appInfo.processType(procType);
 
@@ -650,7 +644,7 @@ MvRequest Xsect::getAppView ( MvRequest& viewRequest )
    return MvRequest();
 }
 
-bool Xsect::consistencyCheck( ParamMap &params )
+bool Xsect::consistencyCheck( ParamMap &params, ApplicationInfo& appInfo )
 {
    // 1) Number of parameters to be processed must be greater than 0
    if (params.size() == 0 )
@@ -670,6 +664,14 @@ bool Xsect::consistencyCheck( ParamMap &params )
       }
    }
 
+   // 3) Options related to the level_selection_type parameters in the
+   // user interface must be compatible to the input fieldset
+   if ( appInfo.levelType() == XS_ML && appInfo.levelSelectionType() != "FROM_DATA" )
+   {
+      setError(1,"ERROR: Invalid value for parameter LEVEL_SELECTION_TYPE. It must be FROM_DATA because the input data contains Model Level fields");
+      return false;
+   }
+
    return true;
 }
 
@@ -811,18 +813,23 @@ bool Xsect::writeGeoCoordsNetcdf( MvNetCDF& cdf, ApplicationInfo& appInfo )
 bool Xsect::contourValues ( ApplicationInfo& appInfo, ParamMap& params,
                             MvNetCDF &cdf, MvField& field, string key )
 {
+   vector<double> y_values;
+   vector<double> cp;
+   if (!appInfo.computeLevelMatrixValues ( params,key,y_values,cp,field ) )
+      return false;
+
    // Get parameter info
    ParamIterator ii = params.find(key);
    ParamInfo *par = (*ii).second;
 
    // Add/update variable to the netCDF
-   int i;
-   int nrLevels = appInfo.NrLevels();
+   int nrLevels = appInfo.outputLevels();
    int nrPoints = appInfo.NrPoints();
    string varname = this->getNetcdfVarname(par->ParamName());
-   MvNcVar* nclevels;
+   string levname = this->getNetcdfLevelVarname(varname);
+   MvNcVar* nclevels = cdf.getVariable(levname);
    MvNcVar* ncv = cdf.getVariable(varname);
-   if ( !ncv )   // Create new variables
+   if ( !ncv || !nclevels )   // Create new variables
    {
       ntime_ = -1;
 
@@ -835,102 +842,45 @@ bool Xsect::contourValues ( ApplicationInfo& appInfo, ParamMap& params,
       values_sdim.push_back(XS_VARLEVEL);
 
       // Create variable 'levels'
-      string levname = getNetcdfLevelVarname(varname);
-      nclevels = cdf.addVariable(levname,ncDouble,values_ndim,values_sdim);
-      nclevels->addAttribute("long_name", "Atmospheric Levels");
-      nclevels->addAttribute("units", "hPa");
-      nclevels->addAttribute("positive", "down");
-
-      // Create variable matrix to be processed
-      values_ndim.push_back(nrPoints);
-      values_sdim.push_back(XS_VARLON);
-      ncv = cdf.addVariable(varname,ncDouble,values_ndim,values_sdim);
-      ncv->addAttribute("long_name", par->ParamLongName().c_str());
-      ncv->addAttribute("units", par->Units().c_str());
-      ncv->addAttribute("_FillValue", XMISSING_VALUE);
-      ncv->addAttribute("title",titleVariable(appInfo,par).c_str());
-   }
-
-   // Compute values
-   vector<double> y_values;
-   double **cp;
-   if( appInfo.levelType() != XS_ML_LNSP && appInfo.levelType() != XS_ML_GHBC )
-   {
-      // Memory allocation
-      cp =  new double* [ nrLevels ];
-      for (i = 0; i < nrLevels; i++)
-         cp[i] = new double [ nrPoints ];
-
-      // Compute level values and interpolate matrix
-      appInfo.computeLevelInfo(par,y_values);
-      appInfo.InterpolateVerticala(cp,par,y_values);
-   }
-   else
-   {
-      if ( appInfo.haveLNSP() )   // handle LNSP
+      if ( !nclevels )
       {
-          // Get LNSP values
-          ParamInfo* parLnsp = this->getParamInfo( appInfo,params,appInfo.LNSP(),key );
-          if ( ! parLnsp )
-          {
-              setError(1,"ERROR: Could not find parameter LNSP");
-              return false;
-          }
-
-          double *splin = appInfo.getOneLevelValues(parLnsp,"1");
-          if ( !splin )  // LNSP not found
-          {
-              setError(1,"ERROR: Could not find LNSP Level values");
-              return false;
-          }
-
-          // Memory allocation
-          cp =  new double* [ nrLevels ];
-          for (i = 0; i < nrLevels; i++)
-              cp[i] = new double [ nrPoints ];
-
-          // Compute level values and interpolate matrix
-          appInfo.computeLevelInfo(par,y_values,splin,field);
-          appInfo.InterpolateVerticalb(field,cp,par,splin,y_values);
+         string levname = getNetcdfLevelVarname(varname);
+         nclevels = cdf.addVariable(levname,ncDouble,values_ndim,values_sdim);
+         nclevels->addAttribute("long_name", "Atmospheric Levels");
+         nclevels->addAttribute("units", "hPa");
+         nclevels->addAttribute("positive", "down");
       }
-      else // handle height-based coordinates
-      {
-         // Get extra values
-         ParamInfo* parGHBC = this->getParamInfo( appInfo,params,appInfo.GHBC(), key );
-         if ( ! parGHBC )
-         {
-            setError(1,"ERROR: Could not find parameter GHBC");
-            return false;
-         }
-
-         // Memory allocation
-         cp =  new double* [ nrLevels ];
-         for (i = 0; i < nrLevels; i++)
-            cp[i] = new double [ nrPoints ];
 
-         // Compute level values and interpolate matrix
-         appInfo.computeLevelInfoGHBC(parGHBC,y_values);
-         appInfo.InterpolateVerticalGHBC(cp,par,parGHBC,y_values);
+      // Create variable matrix to be processed
+      if ( !ncv )
+      {
+         values_ndim.push_back(nrPoints);
+         values_sdim.push_back(XS_VARLON);
+         ncv = cdf.addVariable(varname,ncDouble,values_ndim,values_sdim);
+         ncv->addAttribute("long_name", par->ParamLongName().c_str());
+         ncv->addAttribute("units", par->Units().c_str());
+         ncv->addAttribute("_FillValue", XMISSING_VALUE);
+         ncv->addAttribute("title",titleVariable(appInfo,par).c_str());
       }
    }
 
    // Write level values to tne netCDF file
+   int i;
    ntime_++;
    nclevels->setCurrent(ntime_);
-   double factor = (appInfo.levelType() != XS_ML_LNSP) ? 1. : 100.;
-   for ( i = 0; i < nrLevels ;i++ )
+//   double factor = (appInfo.levelType() != XS_ML_LNSP) ? 1. : 100.;
+   double factor = (appInfo.levelType() == XS_ML) ? 1. : 100.;
+   for ( i = 0; i < nrLevels; i++ )
       y_values[i] /= factor;
 
    nclevels->put(y_values,1,(long)y_values.size());
 
    // Write matrix values to the netCDF file
-   for ( i = 0; i < nrLevels ;i++ )
+   for ( i = 0; i < nrLevels; i++ )
    {
       ncv->setCurrent(ntime_,i);
-      ncv->put(cp[i],1,1,(long)nrPoints);
-      delete [] cp[i];
+      ncv->put(&cp[i*nrPoints],1,1,(long)nrPoints);
    }
-   delete [] cp;
 
    return true;
 }
@@ -942,7 +892,7 @@ bool Xsect::contourValues ( ApplicationInfo& appInfo, ParamMap& params,
 // b) variable name starting with non-alphabetic letter is
 //    replaced by the following scheme: all non-alphabetic
 //    letters are moved to the end, e.g. 10u becomes u_10
-string Xsect::getNetcdfVarname(string name)
+string Xsect::getNetcdfVarname(const string& name)
 {
    // RTTOV specific
    if ( name == "skt" )
@@ -979,46 +929,6 @@ string Xsect::getNetcdfVarname(string name)
    return newname;
 }
 
-ParamInfo* Xsect::getParamInfo( ParamMap &params, string key )
-{
-   // Check if field is valid
-   ParamIterator ii = params.find(key);
-   if ( ii == params.end() )
-   {
-      setError(0,"ERROR: Could not find the requested field (getParamInfo)");
-      return 0;
-   }
-
-   // Get parameter info
-   return (*ii).second;
-}
-
-ParamInfo* Xsect::getParamInfo( ApplicationInfo& appInfo, ParamMap &params, int key, string keyBase )
-{
-   // Build the new key based on keyBase
-   char newKey[60];
-   sprintf(newKey,"p%06d%s",key,keyBase.substr(7,50).c_str() );
-
-   // Get paraminfo
-   ParamInfo* par = this->getParamInfo( params, newKey );
-   if ( par )
-      return par;
-
-   // Special case: if paramInfo not found and key is "extra" (LNSP or GHBC)
-   // then try to find any other "extra" paramInfo (do not use the keyBase info)
-   if ( appInfo.isLNSP(key) || appInfo.isGHBC(key) )
-   {
-      for ( ParamIterator ii = params.begin(); ii != params.end(); ii++ )
-      {
-         par = (*ii).second;
-         if ( par->Parameter() == key )
-            return par;
-      }
-   }
-
-   return par;
-}
-
 bool Xsect::isDataModuleDropped( const char* verb )
 {
    return (verb && (strcmp(verb,"MXSECTION")  == 0 || strcmp(verb,"MXAVERAGE") == 0 ||
@@ -1044,6 +954,99 @@ MvRequest Xsect::createOutputRequest( MvRequest& in)
    return out;
 }
 
+void Xsect::deleteAuxiliaryMemory(double* xint, ParamMap& params)
+{
+   // Delete auxiliary array
+   if (xint)
+   {
+      delete [] xint;
+      xint = 0;
+   }
+
+   // Free memory for parameters
+   for ( ParamIterator paramIter = params.begin(); paramIter != params.end(); paramIter++)
+      delete (*paramIter).second;
+}
+
+bool Xsect::initialiseNetcdf( MvNetCDF& netcdf, ParamMap& params, ApplicationInfo& appInfo, int& ntimes, MvField& field, double* xint )
+{
+   // Create a temporary netCDF file
+   ncName_ = (const char*)marstmp();
+   netcdf.init(ncName_,'w');
+   if ( !netcdf.isValid() )
+   {
+      setError(1,"ERROR: Could not open netCDF file");
+      return false;
+   }
+
+   // Write netCDF global attributes
+   if ( !this->writeGlobalAttributesNetcdf(netcdf,params,appInfo) )
+      return false;
+
+   // Write initial variables to the netCDF file: levels, time,
+   // geographical coordinates
+   if ( !this->writeLevelInfoNetcdf(netcdf,appInfo,params,&field,xint) )
+      return false;
+
+   if ( !this->writeTimeInfoNetcdf(netcdf,params,ntimes) )
+      return false;
+
+   if ( !this->writeGeoCoordsNetcdf( netcdf, appInfo ) )
+      return false;
+
+   return true;
+}
+
+MvNcVar* Xsect::getNetcdfVariable( MvNetCDF& cdf, const string& varname, ApplicationInfo& appInfo, const string& longname, ParamInfo* param )
+{
+   MvNcVar *ncv = cdf.getVariable(varname);
+   if ( !ncv )   // Create new variable
+   {
+      // Initialise dimensions
+      vector<long> values_ndim;
+      values_ndim.push_back(appInfo.NTimes());
+      values_ndim.push_back(appInfo.outputLevels());
+      values_ndim.push_back(appInfo.NrPoints());
+      vector<string> values_sdim;
+      values_sdim.push_back(XS_VARTIME);
+      values_sdim.push_back(XS_VARLEVEL);
+      values_sdim.push_back(XS_VARLON);
+
+      // Create variable
+      ncv = cdf.addVariable(varname,ncDouble,values_ndim, values_sdim);
+      ncv->addAttribute("long_name", longname.c_str());
+      ncv->addAttribute("units", param->Units().c_str());
+      ncv->addAttribute("_FillValue", XMISSING_VALUE);
+      ncv->addAttribute("title",titleVariable(appInfo,param).c_str());
+   }
+
+   return ncv;
+}
+
+MvNcVar* Xsect::getNetcdfVariableLevel( MvNetCDF& cdf, const string& varname, ApplicationInfo& appInfo )
+{
+   MvNcVar *ncv = cdf.getVariable(varname);
+   if ( !ncv )   // Create new variable
+   {
+      // Initialise dimensions
+      vector<long> values_ndim;
+      values_ndim.push_back(appInfo.NTimes());
+      values_ndim.push_back(appInfo.outputLevels());
+      vector<string> values_sdim;
+      values_sdim.push_back(XS_VARTIME);
+      values_sdim.push_back(XS_VARLEVEL);
+
+      // Create variable
+      ncv = cdf.addVariable(varname,ncDouble,values_ndim, values_sdim);
+      ncv->addAttribute("long_name", "Atmospheric Levels");
+      ncv->addAttribute("units", "hPa");
+      ncv->addAttribute("positive", "down");
+      ncv->addAttribute("_FillValue", XMISSING_VALUE);
+   }
+
+   return ncv;
+}
+
 //------------------------------------------------------------------------------
 
 int main(int argc,char **argv)
diff --git a/src/XSection/Xsect.h b/src/XSection/Xsect.h
index 657846c..195bc64 100644
--- a/src/XSection/Xsect.h
+++ b/src/XSection/Xsect.h
@@ -46,9 +46,12 @@ public:
    MvRequest getAppView ( MvRequest& );
 
    // Consistency check
-   bool consistencyCheck( ParamMap& );
+   bool consistencyCheck( ParamMap&, ApplicationInfo& );
 
-   // Write level info to the Netcdf file
+   // Initialise/create netCDF file
+   bool initialiseNetcdf( MvNetCDF&, ParamMap&, ApplicationInfo&, int&, MvField&, double* );
+
+   // Write level info to the Netcdf structure
    virtual bool writeLevelInfoNetcdf ( MvNetCDF&, ApplicationInfo&, ParamMap&, MvField* = 0, double* = 0)
       { return true; }
 
@@ -77,7 +80,7 @@ public:
    virtual bool fillValues( ApplicationInfo&, MvField&, double* ) = 0;
 
    // Create output request using information from the application
-   virtual MvRequest createOutputRequest( ApplicationInfo&, string, ParamInfo* ) = 0;
+   virtual MvRequest createOutputRequest( ApplicationInfo&, ParamInfo* ) = 0;
 
    // Create output request using information from the request
    virtual MvRequest createOutputRequest( MvRequest& );
@@ -85,15 +88,14 @@ public:
    // Compute number and geographical points
    virtual int computeGeographicalPoints( ApplicationInfo&, MvField* = 0 ) = 0;
 
-   // Get Parameter info given the key
-   virtual ParamInfo* getParamInfo( ParamMap&, string );
-   virtual ParamInfo* getParamInfo( ApplicationInfo&, ParamMap&, int, string );
-
 protected:
 
    // Constructor
    Xsect(const char* kw);
 
+   // Destructor
+   ~Xsect() {};
+   
    void getInitialFieldInfo( MvField&, ApplicationInfo&, double&, double&, double&, double& );
    bool updateTopBottomLevels( ApplicationInfo&, ParamMap&, int, MvFieldSetIterator&, double&, double&, int& );
    bool checkCoordinates( double&, double&, double&, double&);
@@ -118,22 +120,35 @@ protected:
    virtual bool fieldConsistencyCheck ( MvField&, ApplicationInfo& ) { return true; }
 
    // Get default variable to be plotted
-   ParamInfo* plotVariable ( ApplicationInfo&, ParamMap& );
+   virtual ParamInfo* plotVariable ( ApplicationInfo&, ParamMap& );
 
    // Get netCDF variable name
-   string getNetcdfVarname(string);
+   virtual string getNetcdfVarname( const string& );
 
    // Get netCDF level variable name
-   string getNetcdfLevelVarname(string& varname)
+   virtual string getNetcdfLevelVarname(string& varname)
       { return varname + "_lev"; }
 
+   // Get netCDF Value and Components variable names
+   virtual string getNetcdfValueVarname()      { return "value";       }
+   virtual string getNetcdfXComponentVarname() { return "x_component"; }
+   virtual string getNetcdfYComponentVarname() { return "y_component"; }
+
+   // Get/create a netCDF variable
+   virtual MvNcVar* getNetcdfVariable( MvNetCDF&, const string&v, ApplicationInfo&, const string&, ParamInfo*);
+   virtual MvNcVar* getNetcdfVariableLevel( MvNetCDF&, const string&v, ApplicationInfo& );
+
    // Check if data module was dropped
    bool isDataModuleDropped( const char* );
 
+   // Free memory
+   void deleteAuxiliaryMemory(double*, ParamMap&);
 
+   // Variables
    MvRequest origReq_; // input request
    string type_;       // application type: MVPROFILE, MXSECTION, MXAVERAGE
    string view_;       // application view: MVPROFILEVIEW, MXSECTIONVIEW, MXAVERAGEVIEW
+   string ncName_;     // netCDF file name
    int ntime_;         // time counter. It assumes that the input data is sorted
                        // by variable and time, e.g. v1t1, v1t2, .. vntm, v2t1, ...
 };
diff --git a/src/libMars/CMakeLists.txt b/src/libMars/CMakeLists.txt
index 4a3cb27..b57a9d0 100644
--- a/src/libMars/CMakeLists.txt
+++ b/src/libMars/CMakeLists.txt
@@ -67,8 +67,9 @@ else()
     add_definitions(-DNOODB)
 endif()
 
-if ( NOT EMOS_FOUND )
+if ( NOT LIBEMOS_FOUND )
     add_definitions(-DNOPPROC)
+    message(FATAL_ERROR "No emoslib found - should not have got this far!")
 endif()
 
 
@@ -107,8 +108,8 @@ ADD_CUSTOM_COMMAND(
 	COMMAND yacc -t ${MARS_SOURCE_PATH}/langy.y\; sed -e s/yy/yy_mars/g < y.tab.c > ${CMAKE_CURRENT_BINARY_DIR}/langy.c
     DEPENDS ${MARS_SOURCE_PATH}/langy.y)
 
-ADD_CUSTOM_TARGET(marsxdr DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/rpcmars.h ${CMAKE_CURRENT_BINARY_DIR}/rpcmars.c)
-ADD_CUSTOM_TARGET(marslex DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/langy.c   ${CMAKE_CURRENT_BINARY_DIR}/langl.c)
+ADD_CUSTOM_TARGET(mvmarsxdr DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/rpcmars.h ${CMAKE_CURRENT_BINARY_DIR}/rpcmars.c)
+ADD_CUSTOM_TARGET(mvmarslex DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/langy.c   ${CMAKE_CURRENT_BINARY_DIR}/langl.c)
 
 ###set( libMars_srcs ${libMars_srcs} PARENT_SCOPE )
 
@@ -122,7 +123,7 @@ ecbuild_add_library( TARGET      MvMars
                      LIBS        ${METVIEW_EXTRA_LIBRARIES}  ${METVIEW_ODB_API_LIBRARIES} ${CURL_LIBRARIES}
                     )
 
-ADD_DEPENDENCIES(MvMars marsxdr marslex)
+ADD_DEPENDENCIES(MvMars mvmarsxdr mvmarslex)
 
 
 ecbuild_add_library( TARGET      macro_api_f90
diff --git a/src/libMarsClient/nfdbbase.c b/src/libMarsClient/nfdbbase.c
index 058c181..b355885 100644
--- a/src/libMarsClient/nfdbbase.c
+++ b/src/libMarsClient/nfdbbase.c
@@ -736,6 +736,8 @@ void request_to_fdb(int ref,request *r,int y2k)
 	const char *stream  = get_value(r,"STREAM",0);
 	const char *leg     = get_value(r,"_LEG_NUMBER",0);
 	boolean stream_enfo = false;
+	boolean stream_enfh = false;
+
 	const char *ignore_wave_fg = getenv("MARS_IGNORE_WAVE_FG_FDB");
 
 
@@ -758,6 +760,9 @@ void request_to_fdb(int ref,request *r,int y2k)
 	if(stream && EQ(stream,"ENFO"))
 		stream_enfo = true;
 
+	if(stream && EQ(stream,"ENFH"))
+		stream_enfh = true;
+
 	/* Override behaviour via environment variable */
 	/* All this code should go once dissemination can handle step ranges for FP */
 	if(mars.no_special_fp)
@@ -781,7 +786,8 @@ void request_to_fdb(int ref,request *r,int y2k)
 
 	if(leg != NULL)
 	{
-		SETVALFDB(&ref,"leg",no_quotes(leg));
+		if( atoi(leg) != 0 )
+			SETVALFDB(&ref,"leg",no_quotes(leg));
 	}
 	else
 	{
@@ -930,7 +936,7 @@ void request_to_fdb(int ref,request *r,int y2k)
 			char npar[7];
 
 			paramtable(q,&par,&table,false);
-			if(table >= 210 || table == 201 || table == 162 || (set_table && table != -1) || (stream_enfo && (table == 171 || table == 173)))
+			if(table >= 210 || table == 201 || table == 162 || (set_table && table != -1) || (stream_enfo && (table == 171 || table == 173)) || (stream_enfh && (table == 151)))
 				sprintf(npar,"%ld%03ld",table,par);
 			else
 				sprintf(npar,"%ld",par);
diff --git a/src/libMarsClient/pproc.c b/src/libMarsClient/pproc.c
index 0233ee8..2991e29 100644
--- a/src/libMarsClient/pproc.c
+++ b/src/libMarsClient/pproc.c
@@ -631,6 +631,9 @@ err vector_postproc(ppbuffer_t *pp, long *nbuffer)
 		char *pufield = (p<q)?pair[p].buffer:pair[q].buffer;
 		char *pvfield = (p<q)?pair[q].buffer:pair[p].buffer;
 
+		size_t u_len = (p<q)?pair[p].len:pair[q].len;
+		size_t v_len = (p<q)?pair[q].len:pair[p].len;
+
 		fortint   out = pp[0].buflen;
 
 		marslog(LOG_DBUG,"Got parameters %d and %d. Calling vector post-processing",p,q);
@@ -658,8 +661,10 @@ err vector_postproc(ppbuffer_t *pp, long *nbuffer)
 		if(mars.use_intuvp && is_wind(p) && (ppdata.derive_uv > 0))
 		{
 			marslog(LOG_DBUG,"MARS_USE_INTUVP set and parameters are U/V. Avoid calling intvect_");
-			memcpy(pp[0].buffer,pufield,pp[0].inlen);
-			memcpy(pp[1].buffer,pvfield,pp[0].inlen);
+			memcpy(pp[0].buffer, pufield, u_len);
+			pp[0].inlen = u_len;
+			memcpy(pp[1].buffer, pvfield, v_len);
+			pp[1].inlen = v_len;
 			out=0;
 			/* ppdata.inter_cnt+=2; */
 			ret=0;
@@ -694,7 +699,8 @@ err vector_postproc(ppbuffer_t *pp, long *nbuffer)
 
 		if(out == 0)
 		{
-			pp[0].outlen = pp[1].outlen = pp[0].inlen;
+			pp[0].outlen = pp[0].inlen;
+			pp[1].outlen = pp[1].inlen;
 		}
 		else {
 			pp[0].outlen = pp[1].outlen = out;
diff --git a/src/libMetview/MvFieldSet.cc b/src/libMetview/MvFieldSet.cc
index 77fae0d..8285da6 100644
--- a/src/libMetview/MvFieldSet.cc
+++ b/src/libMetview/MvFieldSet.cc
@@ -1378,13 +1378,6 @@ bool MvField::isLatLon()
     return mvgrid_->gridType() == cLatLonGrid;
 }
 
-int MvField::scanMode()
-{
-	//gribsec2_ll *s2 = (gribsec2_ll*) &Grib->ksec2[0];
-	//return s2->scan_mode;
-	return mvgrid_->getLong("scanningMode");
-}
-
 int MvField::numberOfLat()
 {
 	//gribsec2_ll *s2 = (gribsec2_ll*) &Grib->ksec2[0];
@@ -1428,9 +1421,6 @@ double MvField::west()
 }
 
 
-const fortint cOctetBit1 = 0x80;
-const fortint cOctetBit2 = 0x40;
-const fortint cOctetBit3 = 0x20;
 
 double MvField::gridNS()
 {
@@ -1439,7 +1429,7 @@ double MvField::gridNS()
 	double computed  = (north() - south() ) / (numberOfLat() - 1);
 
 	//if( (s2->resolution & cOctetBit1) == 0 )  //-- increments not given?
-	if( (mvgrid_->getLong("resolutionAndComponentFlags") & cOctetBit1) == 0 )  //-- increments not given?
+	if( !mvgrid_->getLong("jDirectionIncrementGiven") )  //-- increments not given?
 	  {
 	    return numberOfLat() > 0 ? computed : cValueNotGiven;
 	  }
@@ -1451,7 +1441,7 @@ double MvField::gridNS()
 	  }
 
 	//if( (s2->scan_mode & cOctetBit2) != 0 )  //-- points scan in +j direction
-	if( (mvgrid_->getLong("scanningMode") & cOctetBit2) != 0 ) //-- points scan in +j direction
+	if( mvgrid_->getLong("jScansPositively") != 0 ) //-- points scan in +j direction
 	  {
 	    metadatum = -metadatum;
 	  }
@@ -1467,7 +1457,7 @@ double MvField::gridWE()
 	double computed  = ( east() - west() ) / (numberOfLon() - 1);
 
 	//if( (s2->resolution & cOctetBit1) == 0 )  //-- increments not given?
-	if( (mvgrid_->getLong("resolutionAndComponentFlags") & cOctetBit1) == 0 )  //-- increments not given?
+	if( !mvgrid_->getLong("iDirectionIncrementGiven") )  //-- increments not given?
 	  {
 	    return numberOfLon() > 0 ? computed : cValueNotGiven;
 	  }
@@ -1480,7 +1470,7 @@ double MvField::gridWE()
 	  }
 
 	//if( (s2->scan_mode & cOctetBit1) != 0 )  //-- points scan in -i direction?
-	if( (mvgrid_->getLong("scanningMode") & cOctetBit1) != 0 ) //-- points scan in -i direction
+	if( mvgrid_->getLong("iScansNegatively") != 0 ) //-- points scan in -i direction
 	  {
 	    metadatum = -metadatum;
 	  }
diff --git a/src/libMetview/MvFieldSet.h b/src/libMetview/MvFieldSet.h
index 5ad8fbe..1500c29 100644
--- a/src/libMetview/MvFieldSet.h
+++ b/src/libMetview/MvFieldSet.h
@@ -230,9 +230,6 @@ public:
 	//! Returns the number of grid points in longitude (i) direction
 	int numberOfLon();
 
-	//! Returns "scanning mode" octet (bit field, table 8 in GRIB 1)
-	int scanMode();
-
 	//! Returns the Northern coordinate of the grid area
 	double north();
 
diff --git a/src/libMetview/MvGrid.cc b/src/libMetview/MvGrid.cc
index 08ac51f..2a4eedc 100644
--- a/src/libMetview/MvGrid.cc
+++ b/src/libMetview/MvGrid.cc
@@ -31,10 +31,6 @@ GaussianLatitudes MvGaussianGridBase::gLatitudes_;  // global variable for the c
 const long   cFirstLatInd       =  3; //--  4 in Fortran
 const long   cScanModeInd       = 10; //-- 11 in Fortran (CHECK if new classes added!!!)
 
-const long   cOctetBit1  =  0x80;
-const long   cOctetBit2  =  0x40;
-const long   cOctetBit3  =  0x20;
-
 const double cFullGlobeLimit    = 359.9;
 const double cGridEpsilon       = 5e-5;    //-- 0.05 millidegrees
 const double cToRadians         = M_PI/180.0;
@@ -460,9 +456,11 @@ bool MvGridBase::isEqual( const MvGridBase* mygrid ) const
    //-- WARNING:
    //-- cScanModeInd is the same for all so far implemented grid types (011025/vk)
    //--
-   long scanMod1 = getLong( "scanningMode" );
-   long scanMod2 = mygrid->getLong( "scanningMode" );
-   if( scanMod1 != scanMod2 )
+   long scanModI1 = getLong( "iScansNegatively" );
+   long scanModJ1 = getLong( "jScansPositively" );
+   long scanModI2 = mygrid->getLong( "iScansNegatively" );
+   long scanModJ2 = mygrid->getLong( "jScansPositively" );
+   if ((scanModI1 != scanModI2) || (scanModJ1 != scanModJ2))
       return false;              //-- must have same scanning mode
 
    return true;
@@ -732,11 +730,11 @@ MvLatLonGrid::MvLatLonGrid( field* myfield
        return;
      }
 
-   long scan_mode = getLong("scanningMode");
-   if(   (scan_mode & cOctetBit3)                   //-- adjacent points in j dir are consequtive
-      || (scan_mode & cOctetBit1) )                 //-- points scan in -i dir
+   long jPointsConsecutive = getLong("jPointsAreConsecutive"); //-- adjacent points in j dir are consequtive
+   long iNegative          = getLong("iScansNegatively");      //-- points scan in -i dir
+   if(jPointsConsecutive || iNegative)                 
      {
-       marslog( LOG_EROR, "LatLon grid scanning mode %d not supported", scan_mode );
+       marslog( LOG_EROR, "LatLon grid jPointsConsecutive and iScansNegatively scanning mode not supported");
        field_ = 0;
        return;
      }
@@ -756,8 +754,8 @@ MvLatLonGrid::MvLatLonGrid( field* myfield
    double lon1  = firstLonX();
    double lon9  = lastLonX();
 
-   long resol = getLong("resolutionAndComponentFlags");
-   if( (resol & cOctetBit1) == 0 )      //-- increments not given
+   long incrementsGiven = getLong("iDirectionIncrementGiven");
+   if(!incrementsGiven)      //-- increments not given
      {
 	     dx_ = (horisPoints_ == 1) ? 1 : (lon9-lon1) / (horisPoints_-1.0);
      }
@@ -781,7 +779,7 @@ MvLatLonGrid::MvLatLonGrid( field* myfield
    double lat1 = firstLatY();
    double lat9 = lastLatY();
 
-   if( (resol & cOctetBit1) == 0 )       //-- increments not given
+   if(!incrementsGiven)       //-- increments not given
      {
 	     dy_ =  (horisLines_ == 1) ? 1 : (MAX(lat9,lat1) - MIN(lat9,lat1)) / (horisLines_-1.0);
      }
@@ -802,7 +800,8 @@ MvLatLonGrid::MvLatLonGrid( field* myfield
      }
 
 
-   if( (scan_mode & cOctetBit2) == 0 )     //-- points scan in -j dir
+   long jPositive = getLong("jScansPositively");      //-- points scan in +j dir
+   if(!jPositive )     //-- points scan in -j dir
      {
          dy_ = -dy_;
      }
@@ -810,8 +809,8 @@ MvLatLonGrid::MvLatLonGrid( field* myfield
      {
        dy_ = -dy_;
        marslog( LOG_INFO
-	      , "Ignoring Scanning Mode octet (%d), setting j step to %g"
-	      , (int)scan_mode
+	      , "Ignoring jScansPositively flag (%d), setting j step to %g"
+	      , (int)jPositive
 	      , dy_
 	      );
      }
@@ -1464,22 +1463,22 @@ MvLambertGrid::MvLambertGrid( field* myfield
        return;
      }
 
-   long scanMode = getLong("scanningMode");
-   if(   (scanMode & cOctetBit3)            //-- adjacent points in j dir are consequtive
-      || (scanMode & cOctetBit1) )          //-- points scan in -i dir
-     {
-       marslog( LOG_EROR, "LatLon grid scanning mode %dl not supported", scanMode );
+   long jPointsConsecutive = getLong("jPointsAreConsecutive"); //-- adjacent points in j dir are consequtive
+   long iNegative          = getLong("iScansNegatively");      //-- points scan in -i dir
+   if (jPointsConsecutive || iNegative)                 
+   {
+       marslog( LOG_EROR, "Lambert grid jPointsConsecutive or iScansNegatively not supported" );
        return;
-     }
+   }
 
    dx_        = getDouble("DxInMetres");
    double dy_ = getDouble("DyInMetres");
    if( dy_ != dx_ )
-     {
+   {
        marslog( LOG_EROR, "MvLambertGrid: dx!=dy: not implemented!" );
        field_ = 0;
        return;
-     }
+   }
 
    earthRadius_ = cEarthRadius;
 
@@ -1487,7 +1486,7 @@ MvLambertGrid::MvLambertGrid( field* myfield
    double tanLat2 = getDouble("Latin2InDegrees") * 1000;
    //if( sec2_[cInterSecLat2] != gridTanLat_ ) //-- two latitudes...?
    if( tanLat2 != gridTanLat_ )
-     {
+   {
        //-- The original Fortran code was made only for a projection defined
        //-- by a single tangenting latitude. This is my personal solution
        //-- to "convert" an intersecting projection (two latitudes given) to
@@ -1508,7 +1507,7 @@ MvLambertGrid::MvLambertGrid( field* myfield
        earthRadius_ = cos(delta*cToRadians) * cEarthRadius;
 
        marslog( LOG_WARN, "MvLambertGrid: two tangenting latitudes - Q&D solution!" );
-     }
+   }
 
    earthRadiusPerDx_ = earthRadius_ / dx_;
    cout << "R, dx, R/dx:\t" << earthRadius_ << "\t" << dx_ << "\t" << earthRadiusPerDx_ << endl;
@@ -1693,8 +1692,8 @@ MvIrregularGrid::MvIrregularGrid( field* myfield
       field_ = 0;
    }
 
-   long scanMode = getLong("scanningMode");
-   isSouthToNorthScanning_ = scanMode & cOctetBit2;
+   long jScansPositively = getLong("jScansPositively");
+   isSouthToNorthScanning_ = jScansPositively;
    globalNS_ = true;
    globalEW_ = true;
 
diff --git a/src/libMvQtGui/CMakeLists.txt b/src/libMvQtGui/CMakeLists.txt
index 3a4c5a6..afba8d2 100644
--- a/src/libMvQtGui/CMakeLists.txt
+++ b/src/libMvQtGui/CMakeLists.txt
@@ -86,8 +86,13 @@ if (METVIEW_ODB)
     #######lib_libMvQtGui_a_CPPFLAGS += $(ODB_CPPFLAGS)
 endif()
 
-QT4_WRAP_CPP(libMvQtGui_MOC ${moc_files})
-QT4_ADD_RESOURCES(libMvQtGui_RES edit.qrc examiner.qrc find.qrc keyDialog.qrc mail.qrc window.qrc)
+if(METVIEW_QT5)
+ QT5_WRAP_CPP(libMvQtGui_MOC ${moc_files})
+ QT5_ADD_RESOURCES(libMvQtGui_RES edit.qrc examiner.qrc find.qrc keyDialog.qrc mail.qrc window.qrc)
+else()
+ QT4_WRAP_CPP(libMvQtGui_MOC ${moc_files})
+ QT4_ADD_RESOURCES(libMvQtGui_RES edit.qrc examiner.qrc find.qrc keyDialog.qrc mail.qrc window.qrc)
+endif()
 
 
 
diff --git a/src/libMvQtGui/MvQAbout.cc b/src/libMvQtGui/MvQAbout.cc
index e01d746..52c13eb 100644
--- a/src/libMvQtGui/MvQAbout.cc
+++ b/src/libMvQtGui/MvQAbout.cc
@@ -105,6 +105,12 @@ MvQAbout::MvQAbout(QString title, QString description, Versions version,
 		}
 	}
 	
+	const char *qtv=qVersion();
+    	if(qtv)
+    	{
+             str << "<p><b>Qt version: </b>" + QString(qtv);
+   	}
+	
 	QVBoxLayout *vb=new QVBoxLayout(this);
 	setLayout(vb);
 	
diff --git a/src/libMvQtGui/MvQApplication.h b/src/libMvQtGui/MvQApplication.h
index 2024f23..d6d06c4 100644
--- a/src/libMvQtGui/MvQApplication.h
+++ b/src/libMvQtGui/MvQApplication.h
@@ -10,7 +10,11 @@
 #ifndef MvQApplication_H
 #define MvQApplication_H
 
-#include <QtGui/QApplication>
+#ifdef METVIEW_QT5
+ #include <QtWidgets/QApplication>
+#else
+ #include <QtGui/QApplication>
+#endif
 #include <QWidget>
 
 #include <MvRequest.h>
diff --git a/src/libMvQtGui/MvQDragDrop.cc b/src/libMvQtGui/MvQDragDrop.cc
index 01d0066..75372fe 100644
--- a/src/libMvQtGui/MvQDragDrop.cc
+++ b/src/libMvQtGui/MvQDragDrop.cc
@@ -12,6 +12,7 @@
 //#include <X11/X.h>
 //#include <X11/Xlib.h>
 //#include <X11/Xatom.h>
+#include <QMimeData>
 #include <QByteArray>
 #include <QDataStream>
 #include <QDropEvent>
diff --git a/src/libMvQtGui/MvQFileDialog.cc b/src/libMvQtGui/MvQFileDialog.cc
index 189f66b..10a7310 100644
--- a/src/libMvQtGui/MvQFileDialog.cc
+++ b/src/libMvQtGui/MvQFileDialog.cc
@@ -136,9 +136,10 @@ MvQFileDialog::MvQFileDialog(QString startDir,QString title,QWidget *parent): QF
 	QList<QUrl> urlLst;
 	
 	urlLst << QUrl("file:");
-	
+
+#ifndef METVIEW_QT5	
 	urlLst << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
-	//urlLst << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation));
+#endif
 	
 	if(char *mvDir=getenv("METVIEW_USER_DIRECTORY"))		
   	{ 	
diff --git a/src/libMvQtGui/MvQKeyFilterModel.cc b/src/libMvQtGui/MvQKeyFilterModel.cc
index 77b7c94..d9b4111 100644
--- a/src/libMvQtGui/MvQKeyFilterModel.cc
+++ b/src/libMvQtGui/MvQKeyFilterModel.cc
@@ -163,7 +163,9 @@ void MvQKeyFilterModel::setKeyProfile(MvKeyProfile *prof)
 	setupKeyFilter();
 
 	//Reset the model (views will be notified)
-	reset();
+	//reset();  NOT in Qt 5
+	beginResetModel();
+	endResetModel();
 }
 
 void MvQKeyFilterModel::setupKeyFilter()
@@ -361,7 +363,7 @@ QModelIndex MvQKeyFilterModel::index( int row, int column, const QModelIndex & p
 		return QModelIndex();
 	}
 
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/libMvQtGui/MvQKeyModel.cc b/src/libMvQtGui/MvQKeyModel.cc
index 30335b7..00552b1 100644
--- a/src/libMvQtGui/MvQKeyModel.cc
+++ b/src/libMvQtGui/MvQKeyModel.cc
@@ -259,7 +259,7 @@ QString MvQKeyModel::label(MvKey* key,const int row, const int column,int role )
 
 QModelIndex MvQKeyModel::index( int row, int column, const QModelIndex & /*parent*/ ) const
 {
-   return createIndex(row,column,0);
+   return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/libMvQtGui/MvQKeyProfileModel.cc b/src/libMvQtGui/MvQKeyProfileModel.cc
index 43d6604..7f04315 100644
--- a/src/libMvQtGui/MvQKeyProfileModel.cc
+++ b/src/libMvQtGui/MvQKeyProfileModel.cc
@@ -259,7 +259,7 @@ QModelIndex MvQKeyProfileModel::index( int row, int column, const QModelIndex &
 		return QModelIndex();
 	}
 
-	return createIndex(row,column,0);
+	return createIndex(row,column,(void*)0);
 }
 
 
diff --git a/src/libMvQtGui/MvQKeyProfileTree.cc b/src/libMvQtGui/MvQKeyProfileTree.cc
index 5807aa4..a3258f1 100644
--- a/src/libMvQtGui/MvQKeyProfileTree.cc
+++ b/src/libMvQtGui/MvQKeyProfileTree.cc
@@ -72,13 +72,21 @@ void MvQKeyProfileTree::setEditable(bool b)
 	{	
 		setAcceptDrops(true);
 		setDragDropMode(QAbstractItemView::DropOnly);
+#ifdef METVIEW_QT5		
+		header()->setSectionsMovable(true);
+#else
 		header()->setMovable(true);
+#endif
 	}	
 	else
 	{
 		setAcceptDrops(false);
 		setDragDropMode(QAbstractItemView::NoDragDrop);
-		header()->setMovable(false);	
+#ifdef METVIEW_QT5		
+		header()->setSectionsMovable(false);
+#else
+		header()->setMovable(false);
+#endif
 	}
 }
 
diff --git a/src/libMvQtGui/MvQOdbModel.cc b/src/libMvQtGui/MvQOdbModel.cc
index 640b0b9..7ff2445 100644
--- a/src/libMvQtGui/MvQOdbModel.cc
+++ b/src/libMvQtGui/MvQOdbModel.cc
@@ -24,7 +24,8 @@ void MvQOdbVarModel::setData(QList<MvQOdbVar*> &data)
 	qDebug() << "model size:" << data_.count();
 	
 	//Reset the model (views will be notified)
-	reset();
+	beginResetModel();
+	endResetModel();
 }
 
 
@@ -100,7 +101,7 @@ QModelIndex MvQOdbVarModel::index( int row, int column, const QModelIndex &) con
 		return QModelIndex();
 	}
 
-	return createIndex(row, column, 0); 
+	return createIndex(row, column,static_cast<void*>(0)); 
 }
 
 
@@ -598,7 +599,7 @@ QModelIndex MvQOdbDataModel::index( int row, int column, const QModelIndex & /*p
 		return QModelIndex();
 	}
 	
-	return createIndex(row, column, 0); 
+	return createIndex(row, column, static_cast<void*>(0)); 
 }
 
 
diff --git a/src/libMvQtGui/MvQProfileView.cc b/src/libMvQtGui/MvQProfileView.cc
index 9bd5566..ab04b1d 100644
--- a/src/libMvQtGui/MvQProfileView.cc
+++ b/src/libMvQtGui/MvQProfileView.cc
@@ -30,7 +30,11 @@ MvQNodeItem::MvQNodeItem(MvQProfileItem *prof,bool editable,float yPos) :
   yPos_(yPos)
 {	
   	setFlag(ItemSendsGeometryChanges);
-	setAcceptsHoverEvents(true);
+    #ifdef METVIEW_QT5		
+	    setAcceptHoverEvents(true);
+    #else
+	    setAcceptsHoverEvents(true);
+    #endif
  	setZValue(-1);
 	
 	if(editable_)   
diff --git a/src/libMvQtGui/MvQScmModel.cc b/src/libMvQtGui/MvQScmModel.cc
index 50a1003..2ef3adc 100644
--- a/src/libMvQtGui/MvQScmModel.cc
+++ b/src/libMvQtGui/MvQScmModel.cc
@@ -86,7 +86,7 @@ QModelIndex MvQScmDataModel::index( int row, int column, const QModelIndex & /*p
 		return QModelIndex();
 	}
 	
-	return createIndex(row, column, 0);
+	return createIndex(row, column, (void*)0);
 }
 
 QModelIndex MvQScmDataModel::indexForChange(const MvScmProfileChange& item) const
@@ -101,7 +101,9 @@ QModelIndex MvQScmDataModel::parent( const QModelIndex & /*index */) const
 
 void MvQScmDataModel::reload()
 {
-  	reset();
+  	//reset();
+  	beginResetModel();
+    endResetModel();
 }	
 
 
@@ -248,7 +250,7 @@ QModelIndex MvQScmSurfaceModel::indexForVar(MvScmVar *var, int step, int /*level
 		{
 			if(data_.at(i) == var)
 			{
-				return createIndex(i,0,0); 
+				return createIndex(i,0,(void*)0); 
 			}	
 		}	  			
 	}
@@ -426,7 +428,7 @@ QModelIndex MvQScmProfileModel::indexForVar( MvScmVar *var, int step, int level)
 		{
 			if(data_.at(i) == var)
 			{
-				return createIndex(level,i, 0); 
+				return createIndex(level,i, (void*)0); 
 			}	
 		}	  			
 	}
@@ -460,7 +462,9 @@ MvQScmProfileFilterModel::MvQScmProfileFilterModel(QObject *parent) :
 void MvQScmProfileFilterModel::setShowEditableOnly(bool b)
 {
   	showEditableOnly_=b;
-	reset();
+  	//reset();
+  	beginResetModel();
+    endResetModel();
 }
 
 bool MvQScmProfileFilterModel::filterAcceptsColumn(int sourceColumn,
diff --git a/src/libMvQtGui/MvQStationsWidget.cc b/src/libMvQtGui/MvQStationsWidget.cc
index e398b65..ec69a39 100644
--- a/src/libMvQtGui/MvQStationsWidget.cc
+++ b/src/libMvQtGui/MvQStationsWidget.cc
@@ -150,7 +150,7 @@ QModelIndex MvQStationsModel::index( int row, int column, const QModelIndex & /*
 		return QModelIndex();
 	}
 	
-	return createIndex(row, column, 0);
+	return createIndex(row, column, (void*)0);
 }
 
 QModelIndex MvQStationsModel::parent( const QModelIndex & /*index */) const
diff --git a/src/libMvQtGui/MvQX11Application.h b/src/libMvQtGui/MvQX11Application.h
index f9ef0b0..6bc6a35 100644
--- a/src/libMvQtGui/MvQX11Application.h
+++ b/src/libMvQtGui/MvQX11Application.h
@@ -10,7 +10,11 @@
 #ifndef MvQX11Application_H
 #define MvQX11Application_H
 
-#include <QtGui/QApplication>
+#ifdef METVIEW_QT5
+ #include <QtWidgets/QApplication>
+#else
+ #include <QtGui/QApplication>
+#endif
 #include <QWidget>
 
 #include <MvRequest.h>
diff --git a/src/libMvQtUtil/CMakeLists.txt b/src/libMvQtUtil/CMakeLists.txt
index f929164..2d094ba 100644
--- a/src/libMvQtUtil/CMakeLists.txt
+++ b/src/libMvQtUtil/CMakeLists.txt
@@ -1,8 +1,11 @@
 
 set(header_files_for_moc MvQNetworkAccessManager.h MvQNetworkAccessManager.h )
 
-
-QT4_WRAP_CPP(MvQtUtil_MOC ${header_files_for_moc})
+if(METVIEW_QT5)
+  QT5_WRAP_CPP(MvQtUtil_MOC ${header_files_for_moc})
+else()
+  QT4_WRAP_CPP(MvQtUtil_MOC ${header_files_for_moc})
+endif()
 
 
 set(libMvQtUtil_srcs
diff --git a/src/libMvQtUtil/MvQKeyManager.cc b/src/libMvQtUtil/MvQKeyManager.cc
index 42e966b..eefc35f 100644
--- a/src/libMvQtUtil/MvQKeyManager.cc
+++ b/src/libMvQtUtil/MvQKeyManager.cc
@@ -10,8 +10,13 @@
 #include <QDebug>
 #include <QBuffer>
 #include <QFile>
-#include <QXmlQuery>
-#include <QXmlResultItems>
+#ifdef METVIEW_QT5
+ #include <QtXmlPatterns/QXmlQuery>
+ #include <QtXmlPatterns/QXmlResultItems>
+#else
+ #include <QXmlQuery>
+ #include <QXmlResultItems>
+#endif
 
 #include "MvQKeyManager.h"
 #include "MvQXmlQuery.h"
diff --git a/src/libMvQtUtil/MvQKeyManager.h b/src/libMvQtUtil/MvQKeyManager.h
index 83f6217..14b38d7 100644
--- a/src/libMvQtUtil/MvQKeyManager.h
+++ b/src/libMvQtUtil/MvQKeyManager.h
@@ -17,7 +17,11 @@
 
 #include <QMap>
 #include <QString>
-#include <QXmlQuery>
+#ifdef METVIEW_QT5
+ #include <QtXmlPatterns/QXmlQuery>
+#else
+ #include <QXmlQuery>
+#endif
 
 using namespace std;
 
diff --git a/src/libMvQtUtil/MvQNetworkAccessManager.cc b/src/libMvQtUtil/MvQNetworkAccessManager.cc
index 9a2b47f..9626625 100644
--- a/src/libMvQtUtil/MvQNetworkAccessManager.cc
+++ b/src/libMvQtUtil/MvQNetworkAccessManager.cc
@@ -8,8 +8,13 @@
  ***************************** LICENSE END *************************************/
 
 #include <QDebug>
-#include <QNetworkProxy>
-#include <QNetworkReply>
+#ifdef METVIEW_QT5
+ #include <QtNetwork/QNetworkProxy>
+ #include <QtNetwork/QNetworkReply>
+#else
+ #include <QNetworkProxy>
+ #include <QNetworkReply>
+#endif
 
 #include "MvQNetworkAccessManager.h"
 #include "MvQNetworkProxyFactory.h" 
diff --git a/src/libMvQtUtil/MvQNetworkAccessManager.h b/src/libMvQtUtil/MvQNetworkAccessManager.h
index e0dd1a7..57b36a7 100644
--- a/src/libMvQtUtil/MvQNetworkAccessManager.h
+++ b/src/libMvQtUtil/MvQNetworkAccessManager.h
@@ -10,7 +10,11 @@
 #ifndef MvQNetworkAccessmanager_H
 #define MvQNetworkAccessmanager_H
 
-#include <QNetworkAccessManager>
+#ifdef METVIEW_QT5
+ #include <QtNetwork/QNetworkAccessManager>
+#else
+ #include <QNetworkAccessManager>
+#endif
 #include <QObject>
 #include <QUrl>
 
@@ -31,7 +35,6 @@ protected:
 	QUrl redirectUrl(const QUrl&,const QUrl&) const; 
 
 	QUrl urlRedirectedTo_;
-
 };
 
 #endif
diff --git a/src/libMvQtUtil/MvQNetworkProxyFactory.cc b/src/libMvQtUtil/MvQNetworkProxyFactory.cc
index c43a573..8f9c9d3 100644
--- a/src/libMvQtUtil/MvQNetworkProxyFactory.cc
+++ b/src/libMvQtUtil/MvQNetworkProxyFactory.cc
@@ -42,13 +42,13 @@ void MvQNetworkProxyFactory::updateSettings()
 
 		const char* proxyPort = myPref( "PROXY_PORT" );
 		if(proxyPort)
-			proxy_.setPort(QString::fromAscii(proxyPort).toInt());
+			proxy_.setPort(QString::fromLatin1(proxyPort).toInt());
 
 		const char* noProxy = myPref( "NO_PROXY_FOR" );
 	
 		if(noProxy)
 		{
-			QStringList lst=QString::fromAscii(noProxy).split(",");
+			QStringList lst=QString::fromLatin1(noProxy).split(",");
 			foreach(QString s,lst)
 			{	
 				noProxyLst_ << s.simplified();
diff --git a/src/libMvQtUtil/MvQNetworkProxyFactory.h b/src/libMvQtUtil/MvQNetworkProxyFactory.h
index a1eb5fe..77d8ae5 100644
--- a/src/libMvQtUtil/MvQNetworkProxyFactory.h
+++ b/src/libMvQtUtil/MvQNetworkProxyFactory.h
@@ -10,7 +10,11 @@
 #ifndef MvQNetworkProxyFactory_H
 #define MvQNetworkProxyFactory_H
 
-#include <QNetworkProxyFactory>
+#ifdef METVIEW_QT5
+ #include <QtNetwork/QNetworkProxyFactory>
+#else
+ #include <QNetworkProxyFactory>
+#endif
 #include <QStringList>
 
 class MvQNetworkProxyFactory : public QNetworkProxyFactory
diff --git a/src/libMvQtUtil/MvQVisDefManager.cc b/src/libMvQtUtil/MvQVisDefManager.cc
index a5914b0..732c189 100644
--- a/src/libMvQtUtil/MvQVisDefManager.cc
+++ b/src/libMvQtUtil/MvQVisDefManager.cc
@@ -10,9 +10,13 @@
 #include <QDebug>
 #include <QBuffer>
 #include <QFile>
-#include <QXmlQuery>
-#include <QXmlResultItems>
-
+#ifdef METVIEW_QT5
+ #include <QtXmlPatterns/QXmlQuery>
+ #include <QtXmlPatterns/QXmlResultItems>
+#else
+ #include <QXmlQuery>
+ #include <QXmlResultItems>
+#endif
 #include "MvKeyProfile.h"
 
 #include "MvQXmlQuery.h"
diff --git a/src/libMvQtUtil/MvQXmlQuery.h b/src/libMvQtUtil/MvQXmlQuery.h
index 6c7d04c..af052ea 100644
--- a/src/libMvQtUtil/MvQXmlQuery.h
+++ b/src/libMvQtUtil/MvQXmlQuery.h
@@ -12,9 +12,15 @@
 
 #include <QMap>
 #include <QStringList>
-#include <QXmlQuery>
-#include <QXmlItem>
-#include <QXmlResultItems>
+#ifdef METVIEW_QT5
+ #include <QtXmlPatterns/QXmlQuery>
+ #include <QtXmlPatterns/QXmlItem>
+ #include <QtXmlPatterns/QXmlResultItems>
+#else
+ #include <QXmlQuery>
+ #include <QXmlItem>
+ #include <QXmlResultItems>
+#endif
 
 class MvQXmlQuery : public QXmlQuery
 {
diff --git a/src/uPlot/CMakeLists.txt b/src/uPlot/CMakeLists.txt
index 5b00c64..3d9fb79 100644
--- a/src/uPlot/CMakeLists.txt
+++ b/src/uPlot/CMakeLists.txt
@@ -98,8 +98,13 @@ if(ENABLE_WEATHER_ROOM)
     set(WEATHER_ROOM_MOC_FLAGS -DMETVIEW_WEATHER_ROOM)
 endif()
 
-QT4_WRAP_CPP(common_MOC ${common_moc_files} OPTIONS ${WEATHER_ROOM_MOC_FLAGS})
-QT4_ADD_RESOURCES(common_RES uPlot.qrc)
+if(METVIEW_QT5)
+  QT5_WRAP_CPP(common_MOC ${common_moc_files} OPTIONS ${WEATHER_ROOM_MOC_FLAGS})
+  QT5_ADD_RESOURCES(common_RES uPlot.qrc)
+else()
+  QT4_WRAP_CPP(common_MOC ${common_moc_files} OPTIONS ${WEATHER_ROOM_MOC_FLAGS})
+  QT4_ADD_RESOURCES(common_RES uPlot.qrc)
+endif()
 
 
 
@@ -118,7 +123,11 @@ set(uPlot_srcs
 
 
 if(ENABLE_WEATHER_ROOM)
-    QT4_WRAP_CPP(wr_MOC MvQWeatherRoomDialog.h)
+    if(METVIEW_QT5)
+      QT5_WRAP_CPP(wr_MOC MvQWeatherRoomDialog.h)
+    else()
+      QT4_WRAP_CPP(wr_MOC MvQWeatherRoomDialog.h)
+    endif()
     list(APPEND uPlot_srcs  MvQWeatherRoomDialog.cc ${wr_MOC})
     set(WEATHER_ROOM_FLAGS METVIEW_WEATHER_ROOM)
 endif()
@@ -141,6 +150,10 @@ ecbuild_add_executable( TARGET       uPlot
                         LIBS         ${METVIEW_QT_LIBRARIES} ${STANDARD_METVIEW_LIBS} ${MAGICS_LIBRARIES}  ${METVIEW_ODB_API_LIBRARIES} ${X11_LIBRARIES}
                     )
 
+
+# add this dependency manually because CMake does not pick it up otherwise
+ADD_DEPENDENCIES(uPlot MagPlusShared MagWrapper)
+
 MESSAGE( STATUS "UPLOT CMAKE_INCLUDE_PATH: " ${CMAKE_INCLUDE_PATH} )
 ###nodist_bin_uPlot_SOURCES = ${uPlot_COMMON_QT_SOURCES_nodist} ${uPlot_COMMON_UI_SOURCES_nodist} \
 ###                           uPlot.moc.cpp
@@ -191,13 +204,21 @@ ecbuild_add_executable( TARGET       uPlotBatch
                         LIBS         ${METVIEW_QT_LIBRARIES} ${STANDARD_METVIEW_LIBS} ${MAGICS_LIBRARIES} ${METVIEW_ODB_API_LIBRARIES}
                     )
 
+# add this dependency manually because CMake does not pick it up otherwise
+ADD_DEPENDENCIES(uPlotBatch MagPlusShared MagWrapper)
+
 
 #-------- GeoTool ---------------------------------------------------------------
 
 if(ENABLE_UI)
 
-QT4_WRAP_CPP(geotool_MOC GeoTool.h)
-QT4_ADD_RESOURCES(geotool_RES geoSelect.qrc)
+if(METVIEW_QT5)
+  QT5_WRAP_CPP(geotool_MOC GeoTool.h)
+  QT5_ADD_RESOURCES(geotool_RES geoSelect.qrc)
+else()
+  QT4_WRAP_CPP(geotool_MOC GeoTool.h)
+  QT4_ADD_RESOURCES(geotool_RES geoSelect.qrc)
+endif()
 
 
 set(uPlotGeoTool_srcs
@@ -225,6 +246,10 @@ ecbuild_add_executable( TARGET       GeoTool
                         LIBS         ${METVIEW_QT_LIBRARIES} ${STANDARD_METVIEW_LIBS} ${MAGICS_LIBRARIES}  ${METVIEW_ODB_API_LIBRARIES} ${X11_LIBRARIES}
                     )
 
+# add this dependency manually because CMake does not pick it up otherwise
+ADD_DEPENDENCIES(GeoTool MagPlusShared MagWrapper)
+
+
 set(GeoToolManager_srcs
     GeoToolManager.cc
     )
diff --git a/src/uPlot/CartesianView.cc b/src/uPlot/CartesianView.cc
index b9ae7bd..d26f35b 100644
--- a/src/uPlot/CartesianView.cc
+++ b/src/uPlot/CartesianView.cc
@@ -122,7 +122,7 @@ CartesianView::Drop ( PmContext& context )
       }
 
       MvRequest request = dropRequest.justOneRequest();
-      Cached verb       =  request.getVerb();
+      const char* verb = request.getVerb();
       if ( ObjectList::IsDataUnit ( verb ) == true )
       {
          MvIcon dataUnit = dataBase.InsertDataUnit ( request, Owner().Id() );
@@ -238,17 +238,6 @@ CartesianView::ReplaceAxis ( MvRequest& axisRequest )
      this->UpdateView(newView);
 }
 
-#if 0
-void
-CartesianView::ReplaceTephi ( MvRequest& req )
-{
-     // Add new tephi definition and update the view
-     MvRequest newView = viewRequest_;
-     newView("TEPHIGRAM_GRID") = req;
-     this->UpdateView(newView);
-}
-#endif
-
 // -- METHOD: DecodeDataUnit
 //
 // -- PURPOSE:
diff --git a/src/uPlot/CartesianView.h b/src/uPlot/CartesianView.h
index 265e36a..00618db 100644
--- a/src/uPlot/CartesianView.h
+++ b/src/uPlot/CartesianView.h
@@ -42,84 +42,67 @@ class CartesianView: public PlotModView
 {
    public:
 
-	// Constructor
-	CartesianView( Page&, const MvRequest&, const MvRequest&,
-			const string &haxisName = "HORIZONTAL_AXIS",
-			const string &vaxisName = "VERTICAL_AXIS",
-			const string &viewName  = "cartesianview");
+    // Constructor
+    CartesianView( Page&, const MvRequest&, const MvRequest&,
+                   const string &haxisName = "HORIZONTAL_AXIS",
+                   const string &vaxisName = "VERTICAL_AXIS",
+                   const string &viewName  = "cartesianview"
+                 );
 
-	CartesianView(const CartesianView&);
-	virtual PlotModView *Clone() const { return new CartesianView(*this); }
+    CartesianView(const CartesianView&);
+    virtual PlotModView *Clone() const { return new CartesianView(*this); }
 
-	// Destructor
-	~CartesianView();
+    // Destructor
+    ~CartesianView();
 
-	// Methods overriden from PlotModView class
-	virtual string Name();
+    // Methods overriden from PlotModView class
+    virtual string Name();
 
-	// Update view
-	virtual void UpdateView ( MvRequest& viewRequest);
+    // Update view
+    virtual void UpdateView ( MvRequest& );
 
-	// Replace the current axis ( axis are the background of this view )
-	void ReplaceAxis ( MvRequest& axisRequest );
+    // Replace the current axis ( axis are the background of this view )
+    void ReplaceAxis ( MvRequest& );
 
-	// Replace the current graph
-//	void ReplacePgraph ( MvRequest& pgraphRequest );
+    // Decode the data Unit
+    virtual void DecodeDataUnit ( MvIcon& );
 
-	// Replace area
-	//void ReplaceArea ( const Location&, int=-1 );
+    // Draw the background (axis )
+    virtual void DrawBackground ( ) { };
 
-	// Decode the data Unit
-	virtual void DecodeDataUnit ( MvIcon& dataUnit );
+    // Draw the background (axis )
+    virtual void DrawForeground ( ) { };
 
-	// Draw the background (axis )
-	virtual void DrawBackground ( ) { };
-//	virtual bool EmptyShared() { return false; }
+    virtual void Draw (SubPage*);
 
-	// Draw the background (axis )
-	virtual void DrawForeground ( ) { };
+    // Describe the contents of the view
+    virtual void DescribeYourself ( ObjectInfo& );
 
-	virtual void Draw (SubPage *);
+    void Drop ( PmContext& );
 
-	// Describe the contents of the view
-	virtual void DescribeYourself ( ObjectInfo& description );
+    void DescribeAxis ( ObjectInfo&, MvRequest&, const Cached& );
 
-	void Drop ( PmContext& context );
+    MvIconList InsertDataRequest ( MvRequest& );
 
-	void DescribeAxis ( ObjectInfo& description, MvRequest& axisRequest, const Cached& axisName );
+    virtual bool BackgroundFromData() const { return true; }  
 
-   MvIconList InsertDataRequest ( MvRequest& dropRequest );
-
-	virtual bool BackgroundFromData() const { return true; }  
-
-	// Remove all visdefs when Page::EraseDraw is called. Segments
-	// names does not correspond to visdefs in hierarchy
-	virtual bool EraseAll() { return true; }
+    // Remove all visdefs when Page::EraseDraw is called. Segments
+    // names does not correspond to visdefs in hierarchy
+    virtual bool EraseAll() { return true; }
 
    protected:
 
-     // Update X/Y axes type in the view
-     void  UpdateAxisTypeView ( MvRequest& reqData );
-
-	string hAxisName_, vAxisName_, viewName_;
-//	AxisInfoMap axisInfoMap_;
+    // Update X/Y axes type in the view
+    void  UpdateAxisTypeView ( MvRequest& );
 
-//	void UpdateAxisForAll(MvRequest &givenRequest, SubPage *subpage );
+    string hAxisName_, vAxisName_, viewName_;
 
-//	void HandleAxisData(MvIcon &dataUnit,double,double,double,double);
-
-//	void CheckAxisRequest(MvRequest&,double,double,double,double,bool&,bool&);
-
-//	virtual bool FlipMinMax() { return false; }
-//	virtual void CheckMinMax(double&,double&,double&,double&,AxisInfo&,bool&);
-//	virtual void FindAxis(MvRequest&, MvIconList&,double,double,double,double);
-//	virtual void UpdateAxisInfo();
-	const char * CheckDataRequest(MvIcon &dataUnit,MvIconList &vdList);
-//	void MergeAxisInfo(MvIcon &, MvRequest&, bool);
+    const char* CheckDataRequest(MvIcon&,MvIconList&);
 
    private:
-	// No assignment
-	CartesianView& operator=(const CartesianView&);
+
+    // No assignment
+    CartesianView& operator=(const CartesianView&);
 
 };
 #endif
diff --git a/src/uPlot/CommonXSectView.cc b/src/uPlot/CommonXSectView.cc
index 20aac16..635205d 100644
--- a/src/uPlot/CommonXSectView.cc
+++ b/src/uPlot/CommonXSectView.cc
@@ -52,7 +52,7 @@ CommonXSectView::~CommonXSectView()
 // Synchronous call service. Calls a service and wait its return.
 bool CommonXSectView::CallService(const MvRequest &dataReq, PmContext & context, MvRequest& replyReq)
 {
-    if ( dataReq.getVerb() != GRIB && dataReq.getVerb() != NETCDF )
+    if ( dataReq.getVerb() != GRIB && dataReq.getVerb() != NETCDF && dataReq.getVerb() != BUFR )
         return false;
 
     MvRequest appRequest(ApplicationName().c_str());
@@ -88,10 +88,9 @@ void CommonXSectView::Drop ( PmContext& context )
    MvIconList duList;
    while ( dropRequest )
    {
-      // VisDefs are processed in one single goal. This is because
-      // the processing of a single or a group of visdefs is different.
-      // It is assumed that visdefs always come after a dataunit
-      // (if it exists)
+      // VisDefs are processed in one single goal. This is because the
+      // processing of a single or a group of visdefs is different. It is
+      // assumed that visdefs always come after a dataunit (if it exists)
       MvRequest vdRequestList;
       if ( this->RetrieveVisdefList (dropRequest,vdRequestList) )
       {
@@ -102,13 +101,26 @@ void CommonXSectView::Drop ( PmContext& context )
          if ( !duList.empty() )
             duList.clear();
 
-          if ( !dropRequest ) // no more drops
+         // The drop request has been already advanced
+         if ( !dropRequest ) // no more drops
             break;
       }
 
+      // Process data coming from special Modules (i.e. tag _MODULEID)
+      MvRequest replyRequest;
+
+      if ( this->DropFromModule(dropRequest,replyRequest) )
+      {
+         // Insert reply request to the database
+         duList = this->InsertDataRequest ( replyRequest );
+
+         //  The drop request has been already advanced
+         continue;
+      }
+
       // Process a dataUnit
       MvRequest request = dropRequest.justOneRequest();
-      string verb       =  request.getVerb();
+      string verb = request.getVerb();
       if ( ObjectList::IsDataUnit ( verb.c_str() ) == true )
       {
          // Call the service to process the request
@@ -122,7 +134,6 @@ void CommonXSectView::Drop ( PmContext& context )
          // It calls an external service and waits for its return
          // If returns false, it means that this is just a dataUnit
          // that does not need to be processed by a external service
-         MvRequest replyRequest;
          if ( !CallService(request, context, replyRequest) )
          {
             // Insert the dataunit in the data base at the Page level
@@ -147,7 +158,7 @@ void CommonXSectView::Drop ( PmContext& context )
             //request("_PARENT_DATAUNIT") = 1;
             //this->ParentDataUnitId ( 5 );
 
-            // Insert data request
+            // Insert reply request to the database
             duList = this->InsertDataRequest ( replyRequest );
          }
 
@@ -155,7 +166,7 @@ void CommonXSectView::Drop ( PmContext& context )
          continue;
       }
 
-      // Process other ico
+      // Process other icons
       if ( ObjectList::IsView ( verb.c_str() ) == true )
          this->UpdateView ( request );
 
@@ -194,6 +205,53 @@ void CommonXSectView::Drop ( PmContext& context )
    context.AdvanceToEnd();
 }
 
+bool
+CommonXSectView::DropFromModule ( MvRequest& dropRequest, MvRequest& replyRequest )
+{
+   // If a request comes from a Module, identified by a tag _MODULEID, then group
+   // all the relative requests. These requests should be processed together.
+   // There are two possible set of requests coming from a Module:
+   // A) main verb is NETCDF: this is the case when the Module was called to
+   //    compute the data but not to visualise it. All the relevant visualisation
+   //    requests are under parameter _VISUALISE.
+   // B) others: group all subsequent requests with the same tag id.
+
+   // Process option A
+   if ( (const char*)dropRequest.getVerb() == string("NETCDF") )
+   {
+      replyRequest = dropRequest.getSubrequest("_VISUALISE");
+      dropRequest.advance();  
+      return true;
+   }
+
+   // process option B
+   bool found = false;
+   int moduleId;
+   while ( dropRequest )
+   {
+      if ( !(const char*)dropRequest("_MODULEID") )
+         return found;
+
+      if ( !found )   // found first request
+      {
+         moduleId = (int)dropRequest("_MODULEID");
+         replyRequest.clean();
+         found = true;
+      }
+      else
+      {
+         if ( moduleId != (int)dropRequest("_MODULEID") )
+            return found;
+      }
+
+      // Save request
+      replyRequest += dropRequest.justOneRequest();
+      dropRequest.advance();  
+   }
+
+   return found;
+}
+         
 MvIconList
 CommonXSectView::InsertDataRequest ( MvRequest& dropRequest )
 {
@@ -204,6 +262,7 @@ CommonXSectView::InsertDataRequest ( MvRequest& dropRequest )
 
    // Process the request
    MvIconList duList;
+   MvIconList duListAll;  // store all dataunit processed
    while ( dropRequest )
    {
       // VisDefs are processed in one single goal. This is because the processing
@@ -214,6 +273,11 @@ CommonXSectView::InsertDataRequest ( MvRequest& dropRequest )
       {
          Owner().InsertVisDef (vdRequestList, duList);
 
+         // Clear dataUnitList variable to avoid a possible visdef in the next
+         // iteraction to be associate to an old dataUnit.
+         if ( !duList.empty() )
+            duList.clear();
+
          if ( !dropRequest ) // no more drops
             break;
       }
@@ -228,6 +292,7 @@ CommonXSectView::InsertDataRequest ( MvRequest& dropRequest )
 
          // Add data unit to the output list
          duList.push_back(dataUnit);
+         duListAll.push_back(dataUnit);
 
          // Add information to the SubPage
          DecodeDataUnit ( dataUnit );
@@ -241,12 +306,20 @@ CommonXSectView::InsertDataRequest ( MvRequest& dropRequest )
          }
       }
       else
+      {
          Owner().InsertCommonIcons(req);
 
+         // This request is not a dataUnit. Clear dataUnitList variable
+         // to avoid a possible visdef in the next iteraction to be
+         // associate to an old dataUnit.
+         if ( !duList.empty() )
+            duList.clear();
+      }
+
       dropRequest.advance();
    }
 
-   return duList;
+   return duListAll;
 }
 
 // -- METHOD: DecodeDataUnit
diff --git a/src/uPlot/CommonXSectView.h b/src/uPlot/CommonXSectView.h
index e47fa93..570decb 100644
--- a/src/uPlot/CommonXSectView.h
+++ b/src/uPlot/CommonXSectView.h
@@ -66,21 +66,12 @@ public:
     // Replace the current view
     virtual bool UpdateView () = 0;
 
-    // Replace axis
-    //virtual void ReplaceAxis ( MvRequest&);
-
-    // Replace the current graph;
-    //virtual void ReplacePgraph ( MvRequest& ) {}
-
     // Decode the data Unit
     virtual void DecodeDataUnit ( MvIcon& dataUnit );
 
     // Process a drop
     virtual void Drop ( PmContext& context );
 
-    // Retrieves a list of visdefs
-    //virtual bool RetrieveVisdefList (MvRequest& dropReq, MvRequest& vdReqList);
-
     // Draw the background (axis )
     virtual void DrawBackground ( ) = 0;
 
@@ -97,7 +88,7 @@ public:
                parentDataUnitId_ = parentDataUnitId; 
               }
 
-    int  ParentDataUnitId () { return parentDataUnitId_; }
+    int ParentDataUnitId () { return parentDataUnitId_; }
 
 protected:
 
@@ -116,6 +107,10 @@ protected:
     // Insert a new data request into the page hierarchy
     MvIconList InsertDataRequest ( MvRequest& dropRequest );
 
+    // Get output requests from executing a Module (they all have the
+    // same tag _MODULEID
+    bool DropFromModule ( MvRequest&, MvRequest& );
+
 #if 0
     // Provide Axis information
     void DescribeAxis ( ObjectInfo& description,
diff --git a/src/uPlot/DataObject.cc b/src/uPlot/DataObject.cc
index c7ce859..6a8ccec 100644
--- a/src/uPlot/DataObject.cc
+++ b/src/uPlot/DataObject.cc
@@ -286,44 +286,59 @@ DataObject::EraseDefaultDraw ()
 bool
 DataObject::RetrieveMyVisDefList ( MvIcon& dataUnit, MvIconList& visdefList )
 {
-	bool usingDefault = false;
+   bool usingDefault = false;
 
-	// Retrieve the Icon Data Base
-	MvIconDataBase& dataBase = IconDataBase();
+   // Retrieve the Icon Data Base
+   MvIconDataBase& dataBase = IconDataBase();
 
-	// Retrieve the VisDefs associated to the DataUnit
-	if ( dataBase.RetrieveVisDefList ( dataUnit, visdefList ) )
-	{
-		// Check if there is any valid visdef
-		if ( ObjectList::CheckValidVisDefList ( myRequest_.getVerb(), visdefList ) )
-			return usingDefault;  //found a valid visdef
-	}
+   // Retrieve the VisDefs associated to the DataUnit
+   if ( dataBase.RetrieveVisDefList ( dataUnit, visdefList ) )
+   {
+      // Check if there is any valid visdef
+      if ( ObjectList::CheckValidVisDefList ( myRequest_.getVerb(), visdefList ) )
+         return usingDefault;  //found a valid visdef
+   }
 
-        // Check if there is a parent DataUnit
-	int parentDataUnitId = dataUnit.ParentId();
-	if ( parentDataUnitId )
-	{
-		// There is a parent, look for its Visdefs
-		MvIcon parentDataUnit;
-		//dataBase.RetrieveDataUnit ( parentDataUnitId, parentDataUnit );
+   // Check if there is a parent DataUnit
+   int parentDataUnitId = dataUnit.ParentId();
+   if ( parentDataUnitId )
+   {
+      // There is a parent, look for its Visdefs
+      MvIcon parentDataUnit;
       dataBase.RetrieveIconFromList ( DB_DATAUNIT, parentDataUnitId, parentDataUnit );
-		dataBase.RetrieveVisDefList ( parentDataUnit, visdefList );
+      dataBase.RetrieveVisDefList ( parentDataUnit, visdefList );
 
-		// Check that the parent has a valid visdef for this dataunit
-		if ( ObjectList::CheckValidVisDefList ( myRequest_.getVerb(),visdefList ) )
-			return usingDefault;  //found a valid visdef
-	}
+      // Check that the parent has a valid visdef for this dataunit
+      if ( ObjectList::CheckValidVisDefList ( myRequest_.getVerb(),visdefList ) )
+         return usingDefault;  //found a valid visdef
+   }
+
+   // There is no visdef associated to the dataunit -> get a default visdef.
+   // If the dataunit has a flag indicating a default visdef then apply it (A).
+   // Otherwise, get its default visdef (B).
 
-	// If failed, there is no visdef associated to the data unit
-	// Retrieve the default visdef (it could be either
-	// in the Page, SuperPage or in the Root).
- 	usingDefault = this->DefaultVisDefList ( myRequest_.getVerb(), visdefList );
+   // (A) Verify if the dataunit suggests an specific visdef
+   MvRequest reqAux = dataUnit.Request();
+   if ( (const char*)reqAux("_VISDEF") )
+   {
+      visdefList.clear();
+      MvRequest visdefRequest = ObjectList::UserDefaultRequest ( (const char*)reqAux("_VISDEF") );
+      MvIcon newVisdef (visdefRequest);
+      visdefList.push_back(newVisdef);
+      usingDefault = true;
+   }
+   else
+   {
+      // (B) Retrieve the default visdef (it could be either
+      // in the Page, SuperPage or in the Root).
+      usingDefault = this->DefaultVisDefList ( myRequest_.getVerb(), visdefList );
+   }
 
-	// If it is a default visdef, update some parameters
-	if ( usingDefault )
-		this->UpdateVisDef (dataUnit.Request(),visdefList);
+   // If it is a default visdef, update some parameters
+   if ( usingDefault )
+      this->UpdateVisDef (reqAux,visdefList);
 
-	return usingDefault;
+   return usingDefault;
 }
 
 #if 0
diff --git a/src/uPlot/ExportDialog.cc b/src/uPlot/ExportDialog.cc
index b43c049..aab8493 100644
--- a/src/uPlot/ExportDialog.cc
+++ b/src/uPlot/ExportDialog.cc
@@ -48,7 +48,13 @@ ExportDialog::ExportDialog(int currentFrame, int totalFrames, QWidget *parent) :
     settings.endGroup();
 
     // Set filter options to select which files to be shown
+#ifdef METVIEW_QT5
+    QStringList filters;
+    filters << "All Files (*.*)" << "Images (*.png *.ps *.eps *.jpg *.kml *.gif *.svg *.pdf)";
+    this->setNameFilters(filters);
+#else
     this->setFilter(tr("All Files (*.*);;Images (*.png *.ps *.eps *.jpg *.kml *.gif *.svg *.pdf)"));
+#endif
 
     // Get the main layout
     QGridLayout *mainLayout = static_cast<QGridLayout*>(layout());
diff --git a/src/uPlot/MagPlusService.h b/src/uPlot/MagPlusService.h
index 5db6296..0a71094 100644
--- a/src/uPlot/MagPlusService.h
+++ b/src/uPlot/MagPlusService.h
@@ -60,7 +60,9 @@ public:
 	operator double() const { return (double)request_(name_.c_str(), index_); }
 	operator  string() const { const char* val = request_(name_.c_str(), index_); return (val) ? string(val) : string(""); }
 	operator int() const { return (int)request_(name_.c_str(), index_); }
+	operator long int() const { return (long int)request_(name_.c_str(), index_); }
 	MagParam& operator=(int i) { request_(name_.c_str(), index_) = i; return *this;}
+	MagParam& operator=(long int i) { request_(name_.c_str(), index_) = i; return *this;}
 	MagParam& operator=(string s) { request_(name_.c_str(), index_) = s.c_str(); return *this;}
 	MagParam& operator=(double d) { request_(name_.c_str(), index_) = d; return *this; }
 	void index(int index) { index_ = index; }
diff --git a/src/uPlot/MagicsTranslator.cc b/src/uPlot/MagicsTranslator.cc
index 2ea1fa3..1b2bb8d 100644
--- a/src/uPlot/MagicsTranslator.cc
+++ b/src/uPlot/MagicsTranslator.cc
@@ -721,8 +721,8 @@ void generateSubpageSize(const MvRequest& metviewRequest, MvRequest &magicsReque
 MvRequest
 ThermoTranslator::Execute ( const MvRequest& visdefRequest, const MvRequest& duRequest )
 {
-   // This is a very specific translator. The acceptable thermo data variables
-   // are: t (temperature) and td (dewpoint)
+   // This is a very specific translator. The acceptable thermo data variables are:
+   // t (temperature) and td (dewpoint)
    ensure ( visdefRequest.getVerb() == string("MTHERMO") );
    ensure ( (const char*)duRequest("NETCDF_X_VARIABLE")  );
 
@@ -735,11 +735,39 @@ ThermoTranslator::Execute ( const MvRequest& visdefRequest, const MvRequest& duR
    MvRequest magicsRequest( "MGRAPH" );
    CopySomeParameters(visdefRequest,magicsRequest,"LEGEND");
 
-   // Convert remaining parameters accordingly
+   // Convert remaining parameters accordingly.
+   // There are a few MTHERMO parameters whose default values are different from 
+   // the equivalent MGRAPH parameters.
    if ( svar == string("t") )
+   {
       CopySomeParameters (visdefRequest, magicsRequest, "THERMO_TEMPERATURE", "GRAPH");
+
+      if ( !(const char*)magicsRequest("GRAPH_LINE_COLOUR") )
+          magicsRequest("GRAPH_LINE_COLOUR") = "RED";
+      if ( !(const char*)magicsRequest("GRAPH_LINE_THICKNESS") )
+          magicsRequest("GRAPH_LINE_THICKNESS") = 8;
+      if ( !(const char*)magicsRequest("GRAPH_MISSING_DATA_MODE") )
+          magicsRequest("GRAPH_MISSING_DATA_MODE") = "JOIN";
+      if ( !(const char*)magicsRequest("GRAPH_MISSING_DATA_STYLE") )
+          magicsRequest("GRAPH_MISSING_DATA_STYLE") = "SOLID";
+      if ( !(const char*)magicsRequest("GRAPH_MISSING_DATA_THICKNESS") )
+          magicsRequest("GRAPH_MISSING_DATA_THICKNESS") = 8;
+   }
    else if ( svar == string("td") )
+   {
       CopySomeParameters (visdefRequest, magicsRequest, "THERMO_DEWPOINT", "GRAPH");
+
+      if ( !(const char*)magicsRequest("GRAPH_LINE_STYLE") )
+          magicsRequest("GRAPH_LINE_STYLE") = "DASH";
+      if ( !(const char*)magicsRequest("GRAPH_LINE_COLOUR") )
+          magicsRequest("GRAPH_LINE_COLOUR") = "RED";
+      if ( !(const char*)magicsRequest("GRAPH_LINE_THICKNESS") )
+          magicsRequest("GRAPH_LINE_THICKNESS") = 8;
+      if ( !(const char*)magicsRequest("GRAPH_MISSING_DATA_MODE") )
+          magicsRequest("GRAPH_MISSING_DATA_MODE") = "JOIN";
+      if ( !(const char*)magicsRequest("GRAPH_MISSING_DATA_THICKNESS") )
+          magicsRequest("GRAPH_MISSING_DATA_THICKNESS") = 8;
+   }
    else
    {
       cout << "NETCDF_X_VARIABLE not implemented: " << svar.c_str() << endl;
diff --git a/src/uPlot/MvCallback.hpp b/src/uPlot/MvCallback.hpp
index 3827b85..e1b55a6 100644
--- a/src/uPlot/MvCallback.hpp
+++ b/src/uPlot/MvCallback.hpp
@@ -61,8 +61,8 @@ template <class T>
 class MvCallback: public MvCallbackBase {
 
 	typedef void(T::* Procedure)(MvRequest&);
+    T&        calledObject_;
 	Procedure calledProc_;    
-	T&        calledObject_;
 public:
 
 // -- Constructors
diff --git a/src/uPlot/MvQDataWidget.cc b/src/uPlot/MvQDataWidget.cc
index 65429eb..96fedea 100644
--- a/src/uPlot/MvQDataWidget.cc
+++ b/src/uPlot/MvQDataWidget.cc
@@ -178,7 +178,7 @@ void MvQDataWidget::setCurrentItemForLayerList(MgQLayerItem* item)
 void MvQDataWidget::slotShowContents(int id)
 {
 	MgQLayerItem* layer;
-	int currentId=centralLayout_->currentIndex();
+//	int currentId=centralLayout_->currentIndex();
 		
 	layer=currentLayerFromList();	
 	
diff --git a/src/uPlot/MvQLayerModel.cc b/src/uPlot/MvQLayerModel.cc
index 0bad68c..ff5ce19 100644
--- a/src/uPlot/MvQLayerModel.cc
+++ b/src/uPlot/MvQLayerModel.cc
@@ -687,7 +687,9 @@ void MvQLayerModel::moveLayer(int sourceRow,int targetRow)
 	
 	//layers_[0]->scene()->update();
 
-	reset();	
+		//reset();  NOT in Qt 5
+	beginResetModel();
+	endResetModel();	
 }
 
 string MvQLayerModel::layerId(const QModelIndex& index) 
diff --git a/src/uPlot/MvQZoomStackWidget.cc b/src/uPlot/MvQZoomStackWidget.cc
index 7dcd874..0dd7298 100644
--- a/src/uPlot/MvQZoomStackWidget.cc
+++ b/src/uPlot/MvQZoomStackWidget.cc
@@ -30,7 +30,7 @@ int MvQZoomStackMenuStyle::pixelMetric(PixelMetric metric, const QStyleOption *o
        return QProxyStyle::pixelMetric(metric, option,widget);
 }
     
-
+#ifndef METVIEW_QT5
 int MvQZoomStackMenuPlastiqueStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
 {
         if (metric == PM_SmallIconSize)
@@ -38,6 +38,7 @@ int MvQZoomStackMenuPlastiqueStyle::pixelMetric(PixelMetric metric, const QStyle
  
        return QPlastiqueStyle::pixelMetric(metric, option,widget);
 }
+#endif
 
 //=========================
 //   MvQZoomStackLevel
@@ -324,8 +325,9 @@ MvQZoomStackWidget::MvQZoomStackWidget(MgQPlotScene *scene,QWidget *parent) : QM
 	activeScene_=0;
 	currentPage_=0;
 	skipUpdate_=false;
+#ifndef METVIEW_QT5
 	setStyle(new MvQZoomStackMenuPlastiqueStyle);
-
+#endif
 	connect(this,SIGNAL(triggered(QAction*)),
 		this,SLOT(slotStepTo(QAction*)));
 }
diff --git a/src/uPlot/MvQZoomStackWidget.h b/src/uPlot/MvQZoomStackWidget.h
index 7c60009..0a78e10 100644
--- a/src/uPlot/MvQZoomStackWidget.h
+++ b/src/uPlot/MvQZoomStackWidget.h
@@ -13,7 +13,9 @@
 #include <QImage>
 #include <QMap>
 #include <QMenu>
+#ifndef METVIEW_QT5
 #include <QPlastiqueStyle>
+#endif
 #include <QProxyStyle>
 
 class QAction;
@@ -28,13 +30,15 @@ class MvQZoomStackMenuStyle : public QProxyStyle
         MvQZoomStackMenuStyle(QStyle* style=0) : QProxyStyle(style) {};   
         int pixelMetric(PixelMetric, const QStyleOption *option=0, const QWidget *w=0) const;
 };
-    
+
+#ifndef METVIEW_QT5  
 class MvQZoomStackMenuPlastiqueStyle : public QPlastiqueStyle
 {
     public:
         MvQZoomStackMenuPlastiqueStyle() : QPlastiqueStyle() {};   
         int pixelMetric(PixelMetric, const QStyleOption *option=0, const QWidget *w=0) const;
 };
+#endif
 
 class MvQZoomStackLevel
 {
diff --git a/src/uPlot/ObjectList.cc b/src/uPlot/ObjectList.cc
index 4056ab0..86aa998 100644
--- a/src/uPlot/ObjectList.cc
+++ b/src/uPlot/ObjectList.cc
@@ -898,3 +898,15 @@ ObjectList::IsVisDefBackForeground( const char* verb )
              IsVisDefLegend(verb)
           );
 }
+
+bool
+ObjectList::IsThermoView( const char* verb )
+{
+   return ( verb == THERMOVIEW );
+}
+
+bool
+ObjectList::IsThermoGrid( const char* verb )
+{
+   return ( verb == MTHERMOGRID );
+}
diff --git a/src/uPlot/ObjectList.h b/src/uPlot/ObjectList.h
index 845f916..924e7fc 100644
--- a/src/uPlot/ObjectList.h
+++ b/src/uPlot/ObjectList.h
@@ -112,6 +112,8 @@ public:
    static bool AreCompanions ( const string&, const string& );
    static bool CalledFromMacro ( const MvRequest& );
    static bool IsVisDefBackForeground( const char* );
+   static bool IsThermoView( const char* );
+   static bool IsThermoGrid( const char* );
 
 
    static Cached MacroName ( const Cached& iconClass   );
diff --git a/src/uPlot/PlotModConst.h b/src/uPlot/PlotModConst.h
index 283cc27..499f5f5 100644
--- a/src/uPlot/PlotModConst.h
+++ b/src/uPlot/PlotModConst.h
@@ -31,18 +31,20 @@ const short MAX_LEGENDS_PACKAGE = 5;
 // Data Requests
 static string GRIB      = "GRIB";
 static string NETCDF    = "NETCDF";
+static string BUFR      = "BUFR";
 
 // Page visualization Definitions
-static Cached MCOAST     = "MCOAST";
-static Cached PCOAST     = "PCOAST";
-static string MTEXT      = "MTEXT";
-static string PTEXT      = "PTEXT";
-static string MLEGEND    = "MLEGEND";
-static Cached MAXIS      = "MAXIS";
-static Cached PAXIS      = "PAXIS";
-static Cached ANNOTATION = "ANNOTATION";
-static string MIMPORT    = "MIMPORT";
-static string GEOLAYERS  = "GEOLAYERS";
+static Cached MCOAST       = "MCOAST";
+static Cached PCOAST       = "PCOAST";
+static string MTEXT        = "MTEXT";
+static string PTEXT        = "PTEXT";
+static string MLEGEND      = "MLEGEND";
+static Cached MAXIS        = "MAXIS";
+static Cached PAXIS        = "PAXIS";
+static Cached ANNOTATION   = "ANNOTATION";
+static string MIMPORT      = "MIMPORT";
+static string GEOLAYERS    = "GEOLAYERS";
+static string MTHERMOGRID  = "MTHERMOGRID";
 
 // Data Visualization Definitions
 static Cached MCONT    = "MCONT";
@@ -55,6 +57,7 @@ static Cached MSYMB    = "MSYMB";
 static Cached PSYMB    = "PSYMB";
 static Cached PTACH    = "PTACH";
 static Cached ISOTACHS = "ISOTACHS";
+static string MTHERMO  = "MTHERMO";
 
 // Command Definitions
 static Cached DEVICEDRIVER  = "DEVICE_DRIVER";
@@ -71,6 +74,7 @@ static const string MAPVIEW       = "MAPVIEW";
 static const string GEOVIEW       = "GEOVIEW";
 static const string CARTESIANVIEW = "CARTESIANVIEW";
 static const string DEFAULTVIEW   = "GEOVIEW";
+static const string THERMOVIEW    = "THERMOVIEW";
 
 // Output devices
 static const char* const MVPRINTER       = "PRINTER";
diff --git a/src/uPlot/PlotModView.cc b/src/uPlot/PlotModView.cc
index 037bc14..767712b 100644
--- a/src/uPlot/PlotModView.cc
+++ b/src/uPlot/PlotModView.cc
@@ -335,29 +335,30 @@ void PlotModView::Owner( Page &xx )
 bool
 PlotModView::RetrieveVisdefList (MvRequest& dropRequest, MvRequest& vdRequestList)
 {
-    // Return if this is not a visdef
-    const char* verb = dropRequest.getVerb();
-    if ( !ObjectList::IsVisDef ( verb ) )
-        return false;
+   // Return if this is not a visdef
+   const char* verb = dropRequest.getVerb();
+   if ( !ObjectList::IsVisDef ( verb ) )
+      return false;
 
-    // Get all visdefs
-	vdRequestList.rewind();
-	if (vdRequestList)
-		vdRequestList = empty_request(NULL); // Clean visdef list
+   // Get all visdefs
+   vdRequestList.rewind();
+   if (vdRequestList)
+      vdRequestList = empty_request(NULL); // Clean visdef list
 
-	while ( dropRequest )
-	{
-		// Retrieve visdefs
-        verb = dropRequest.getVerb();
-		if ( ObjectList::IsVisDef ( verb ) )
-		{
-			vdRequestList += dropRequest.justOneRequest();
-			dropRequest.advance();
-		}
-		else break;
-	}
+   while ( dropRequest )
+   {
+      // Retrieve visdefs
+      verb = dropRequest.getVerb();
+      if ( ObjectList::IsVisDef ( verb ) )
+      {
+         vdRequestList += dropRequest.justOneRequest();
+         dropRequest.advance();
+         
+      }
+      else break;
+   }
 
-	return true;
+   return true;
 }
 
 void
diff --git a/src/uPlot/ThermoView.cc b/src/uPlot/ThermoView.cc
index 2d4849a..4b93ac0 100644
--- a/src/uPlot/ThermoView.cc
+++ b/src/uPlot/ThermoView.cc
@@ -57,8 +57,7 @@ ThermoView::ThermoView ( Page& owner,
                          const MvRequest& viewRequest,
                          const MvRequest& setupRequest ):
                               CommonXSectView ( owner, viewRequest, setupRequest ),
-                              type_     ("TEPHIGRAM"),
-                              dataType_ ("GRIB")
+                              type_     ("TEPHIGRAM")
 {
    SetVariables(viewRequest,true);
 }
@@ -66,8 +65,7 @@ ThermoView::ThermoView ( Page& owner,
 ThermoView::ThermoView ( const ThermoView &old ) :
                               CommonXSectView(old)
 {
-   type_     = old.type_;
-   dataType_ = old.dataType_;
+   type_ = old.type_;
 }
 
 string ThermoView::Name()
@@ -168,6 +166,40 @@ bool ThermoView::UpdateView ()
    return true;
 }
 
+void ThermoView::UpdateView ( MvRequest& viewRequest )
+{
+   // Changing to another View is not allowed
+   if ( !ObjectList::IsThermoView( viewRequest.getVerb() ) )
+   {
+      // Changing View is disabled at the moment
+      char text[128];
+      sprintf(text,"Changing View (%s to %s) is currently disabled",viewRequest_.getVerb(),viewRequest.getVerb() );
+      PlotMod::Instance().errorMessage(text);
+   }
+
+   // If the request came from an Application then ignore the new
+   // View definition and use the current View to draw the new plot
+   MvRequest contextReq = viewRequest.getSubrequest("_CONTEXT");
+   if ( contextReq )
+      return;
+
+   // Update the current view
+   // Expand request
+   MvRequest expRequest = ObjectList::ExpandRequest (viewRequest, EXPAND_DEFAULTS);
+
+   // Update request
+   viewRequest_ = expRequest;
+
+   // Indicate that the plotting tree needs to be rebuilt
+   Root::Instance().Refresh(false);
+
+   // Redraw this page
+   //Owner().RedrawIfWindow();
+   //Owner().NotifyObservers();
+
+   //Owner().InitZoomStacks();
+}
+
 void ThermoView::ApplicationInfo( const MvRequest& )
 {
  #if 0
@@ -209,25 +241,30 @@ void ThermoView::ApplicationInfo( const MvRequest& )
 
 void ThermoView::Drop ( PmContext& context )
 {
-   // Before processing the drop, find out if a dataUnit was dropped.
-   // If yes, initializes the type of the ThermoData module to be called.
+   // Before processing the drop (parent's function), check for icon drops
+   // specific to this class:
+   // a) dataUnit: initializes the type of the ThermoData module to be called
+   // b) thermogrid: update the View
    MvRequest dropRequest = context.InRequest();
+   bool first = true;
    while ( dropRequest )
    {
-      //MvRequest req = dropRequest.justOneRequest();
-      string verb =  dropRequest.getVerb();
-      if ( ObjectList::IsDataUnit ( verb.c_str() ) == true )
+      // Data unit
+      string verb = dropRequest.getVerb();
+      if ( first && ObjectList::IsDataUnit ( verb.c_str() ) == true )
+      {
+         MvRequest req = dropRequest.justOneRequest();
+
+         if ( !this->SetThermoType(req) )
+            return;   // suitable thermo type not found
+
+         first = false;
+      }
+      // Thermo grid
+      else if ( ObjectList::IsThermoGrid ( verb.c_str() ) == true )
       {
-         map<string,string>::iterator it;
-         it = DATA_TYPE.find(verb.c_str());
-         if ( it != DATA_TYPE.end()  )
-            dataType_ = it->second;
-         else
-            cout << "ERROR" << endl;
-
-           //dataType_ = mapData(verb);
-         ApplicationName(dataType_.c_str());
-         break;
+         MvRequest req = dropRequest.justOneRequest();
+         this->UpdateThermoGrid ( req );
       }
 
       dropRequest.advance();
@@ -238,3 +275,53 @@ void ThermoView::Drop ( PmContext& context )
 
    return;
 }
+
+void ThermoView::UpdateThermoGrid ( MvRequest& req )
+{
+   // Update new thermo grid definition. The View will be updated later.
+   viewRequest_("THERMO_GRID") = req;
+}
+
+bool ThermoView::SetThermoType( MvRequest& req )
+{
+   string thermoType;
+   string verb = req.getVerb();
+   map<string,string>::iterator it;
+   it = DATA_TYPE.find(verb.c_str());
+   if ( it != DATA_TYPE.end()  )
+      thermoType = it->second;
+   else if ( verb == "NETCDF" )
+   {
+      if ( (const char*)req("_VERB") )
+         thermoType = (const char*)req("_VERB");
+      else if ( (const char*)req("_CLASS") )
+         thermoType = (const char*)req("_CLASS");
+      else
+      {
+         // Thermo type not found
+         char text[128];
+         sprintf( text,"Suitable thermo type not found: %s ",verb.c_str() );
+         PlotMod::Instance().errorMessage(text);
+         return false;
+      }
+   }
+   else if ( verb.find("NETCDF") != std::string::npos )
+   {
+      // The application has been already called to process the data.
+      // These are a set of requests containing the NETCDF_XY_*;
+      // therefore it will be processed withoug calling again the
+      // application. There is no need to set the ApplicationName.
+      return true;
+   }
+   else
+   {
+      // Thermo type not found
+      char text[128];
+      sprintf( text,"Suitable thermo type not found: %s ",verb.c_str() );
+      PlotMod::Instance().errorMessage(text);
+      return false;
+   }
+
+   ApplicationName(thermoType);
+   return true;
+}
diff --git a/src/uPlot/ThermoView.h b/src/uPlot/ThermoView.h
index f1245dc..e4c07a9 100644
--- a/src/uPlot/ThermoView.h
+++ b/src/uPlot/ThermoView.h
@@ -89,10 +89,14 @@ public:
     virtual void SetVariables(const MvRequest&, bool);
 
     // Update view
-   virtual bool UpdateView ();
+   bool UpdateView ();
+   void UpdateView ( MvRequest& );
 
-    // Process a drop
-    virtual void Drop ( PmContext& );
+   // Update thermo grid 
+   void UpdateThermoGrid ( MvRequest& );
+
+   // Process a drop
+   void Drop ( PmContext& );
 
 private:
 
@@ -101,9 +105,10 @@ private:
 
    void ApplicationInfo( const MvRequest& );
 
+   bool SetThermoType( MvRequest& );
+
    // Variable members
    string type_;         // Tephigram, SkewT, Emagram, Stuve
-   string dataType_;     // GRIB, BUFR, ODB
 };
 
 #endif
diff --git a/src/uPlot/uPlotBase.cc b/src/uPlot/uPlotBase.cc
index 1b68a3d..a7a6852 100644
--- a/src/uPlot/uPlotBase.cc
+++ b/src/uPlot/uPlotBase.cc
@@ -1354,13 +1354,13 @@ void uPlotBase::slotBuildContextMenu(const QPoint& globalPos,const QPointF& scen
 
 int uPlotBase::screenResolutionInDpi()
 {	
-	int defaultRes=75;
+	int defaultRes=-1;
   
   	char *mvres=getenv("METVIEW_SCREEN_RESOLUTION");
 	if (mvres)  
 	{
 		int res=QString(mvres).toInt();	
-		if(res > 50 && res < 320)
+		if(res > 50 && res < 400)
 		{
 			  return res;
 		}
diff --git a/test/macros/CMakeLists.txt b/test/macros/CMakeLists.txt
index 574f895..674f7c8 100644
--- a/test/macros/CMakeLists.txt
+++ b/test/macros/CMakeLists.txt
@@ -17,10 +17,15 @@ macro(metview_macro_test)
                      ARGS        -b ${_PAR_MACRO}
                      RESOURCES   ${_PAR_MACRO} ${_PAR_RESOURCES})
 
+    set(all_tests "${all_tests}${_PAR_MACRO} ") # note the spacing
 endmacro()
 
 
 
+set(all_tests) # empty to start with
+
+
+
 if(ENABLE_PLOTTING)
     metview_macro_test(MACRO     HelloWorld.mv
                        RESOURCES set_output.mv ../data/z500.grb)
@@ -64,3 +69,14 @@ if(ENABLE_MARS)
     metview_macro_test(MACRO      MarsAccess.mv
                        RESOURCES  ../data/10U_GG.grb )
 endif()
+
+
+# generate a script which can be used to run the tests on the installed version
+set(METVIEW_COMMAND "${CMAKE_INSTALL_PREFIX}/bin/${METVIEW_SCRIPT}")
+set(TESTS_DIR       "${CMAKE_CURRENT_BINARY_DIR}")
+configure_file(post_install_tests.sh.in ${CMAKE_CURRENT_BINARY_DIR}/metview_post_install_tests.sh @ONLY)
+
+install( FILES ${CMAKE_CURRENT_BINARY_DIR}/metview_post_install_tests.sh 
+         DESTINATION ${MV_BIN_DIR}
+         PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
+
diff --git a/test/macros/post_install_tests.sh.in b/test/macros/post_install_tests.sh.in
new file mode 100755
index 0000000..ff4258d
--- /dev/null
+++ b/test/macros/post_install_tests.sh.in
@@ -0,0 +1,30 @@
+#!/bin/sh
+# Run the tests on the installed version of Metview
+# -------------------------------------------------
+
+set -ea
+
+tests="@all_tests@"
+
+METVIEW_COMMAND="@METVIEW_COMMAND@"
+TESTS_DIR="@TESTS_DIR@"
+
+if [ ! -f ${METVIEW_COMMAND} ] 
+then
+    echo "Command '${METVIEW_COMMAND}' does not exist"
+    exit 1
+fi
+
+
+for test in $tests
+do
+    run="${METVIEW_COMMAND} -b ${TESTS_DIR}/$test"
+    echo $run
+    ${run}
+    echo "Returns $?"
+done
+
+
+# if we got this far, then all tests must have succeeded
+echo "ALL TESTS PASSED"
+echo ""

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/metview.git



More information about the debian-science-commits mailing list