diff --git a/CMake/CTestCustom.cmake.in b/CMake/CTestCustom.cmake.in
index 612027d6e5c8fd494e34aea7afede597568d6d00..a2416c69f341f60e37c060ce71168ad0adfa2051 100644
--- a/CMake/CTestCustom.cmake.in
+++ b/CMake/CTestCustom.cmake.in
@@ -38,9 +38,11 @@
 #----------------------------------------------------------------------
 
 set(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1000000)
-set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS 300)
 set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS 50)
 
+if(NOT DEFINED CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS)
+  set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS 300)
+endif()
 
 set(CTEST_CUSTOM_COVERAGE_EXCLUDE
  ${CTEST_CUSTOM_COVERAGE_EXCLUDE}
@@ -86,6 +88,7 @@ set(CTEST_CUSTOM_WARNING_EXCEPTION
   # Ignore clang's summary warning, assuming prior text has matched some
   # other warning expression:
   "[0-9,]+ warnings? generated."
+  "cl...Command.line.warning.D9025"
   ".*include.opencv2.*warning.*"
   ".*include.opencv2.*note.*"
   ".*include.kml.*warning.*"
diff --git a/CMake/FindGLEW.cmake b/CMake/FindGLEW.cmake
index c54e3656c7f7844cb52d8cfa1b15258c515fa9b3..243191dbd57e5d53d680c74fa7f697f4e6b13f60 100644
--- a/CMake/FindGLEW.cmake
+++ b/CMake/FindGLEW.cmake
@@ -28,54 +28,33 @@
 #
 # Try to find GLEW library and include path.
 # Once done this will define
+#rewritten for OTB by Rashad Kanavath
 #
 # GLEW_FOUND
 # GLEW_INCLUDE_PATH
 # GLEW_LIBRARY
 #
 
-IF (WIN32)
-	FIND_PATH( GLEW_INCLUDE_DIR GL/glew.h
-		$ENV{PROGRAMFILES}/GLEW/include
-		${GLEW_ROOT_DIR}/include
-		DOC "The directory where GL/glew.h resides")
+find_path(
+  GLEW_INCLUDE_DIR GL/glew.h
+  DOC "The directory where GL/glew.h resides"
+  )
 
-    FIND_LIBRARY( GLEW_LIBRARY
-        NAMES glew GLEW glew32 glew32s
-        PATHS
-        $ENV{PROGRAMFILES}/GLEW/lib
-        ${GLEW_ROOT_DIR}/lib
-        ${PROJECT_SOURCE_DIR}/src/nvgl/glew/bin
-        ${PROJECT_SOURCE_DIR}/src/nvgl/glew/lib
-        DOC "The GLEW library")
-ELSE (WIN32)
-	FIND_PATH( GLEW_INCLUDE_DIR GL/glew.h
-		/usr/include
-		/usr/local/include
-		/sw/include
-		/opt/local/include
-		${GLEW_ROOT_DIR}/include
-		DOC "The directory where GL/glew.h resides")
+if(WIN32)
+  set(GLEW_LIB_NAMES glew GLEW glew32 glew32s)
+else()
+  set(GLEW_LIB_NAMES libGLEW GLEW)
+endif()
 
-	# Prefer the static library.
-	FIND_LIBRARY( GLEW_LIBRARY
-		NAMES libGLEW.so GLEW
-		PATHS
-		/usr/lib64
-		/usr/lib
-		/usr/local/lib64
-		/usr/local/lib
-		/sw/lib
-		/opt/local/lib
-		${GLEW_ROOT_DIR}/lib
-		DOC "The GLEW library")
-ENDIF (WIN32)
+FIND_LIBRARY( GLEW_LIBRARY
+  NAMES ${GLEW_LIB_NAMES}
+  DOC "The GLEW library")
 
-SET(GLEW_FOUND "NO")
-IF (GLEW_INCLUDE_DIR AND GLEW_LIBRARY)
-	SET(GLEW_LIBRARIES ${GLEW_LIBRARY})
-	SET(GLEW_FOUND "YES")
-ENDIF ()
+set(GLEW_FOUND FALSE)
+if (GLEW_INCLUDE_DIR AND GLEW_LIBRARY)
+  set(GLEW_LIBRARIES ${GLEW_LIBRARY})
+  set(GLEW_FOUND TRUE)
+endif()
 
 INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLEW
diff --git a/CMake/FindGLFW.cmake b/CMake/FindGLFW.cmake
index 3f4c29ef713aeed6e7f4b65673065bb49f4f4141..2accc1c780a5fdceef6297d059c405ab6b3dc57a 100644
--- a/CMake/FindGLFW.cmake
+++ b/CMake/FindGLFW.cmake
@@ -80,4 +80,4 @@ ENDIF()
 INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLFW
                                   REQUIRED_VARS GLFW_LIBRARY GLFW_INCLUDE_DIR
-                                  VERSION_VAR GLFW_VERSION_STRING)
\ No newline at end of file
+                                  VERSION_VAR GLFW_VERSION_STRING)
diff --git a/CMake/FindLibKML.cmake b/CMake/FindLibKML.cmake
index bb3136e4639ed4e7f7809de53bff8af21ae9a8dc..0a3706d38892f403921ef69eb540c63cead12694 100644
--- a/CMake/FindLibKML.cmake
+++ b/CMake/FindLibKML.cmake
@@ -31,55 +31,35 @@ if( LIBKML_INCLUDE_DIR )
     set( LibKML_FIND_QUIETLY TRUE )
 endif()
 
-find_path( LIBKML_INCLUDE_DIR kml/dom.h )
+find_path( LIBKML_INCLUDE_DIR       kml/dom.h )
+find_library( LIBKML_BASE_LIBRARY   NAMES kmlbase )
+find_library( LIBKML_DOM_LIBRARY    NAMES kmldom )
+find_library( LIBKML_ENGINE_LIBRARY NAMES kmlengine )
 
-find_library( LIBKML_BASE_LIBRARY
-              NAMES kmlbase )
-
-# TODO : add HINTS derived from path of LIBKML_BASE_LIBRARY
-find_library( LIBKML_CONVENIENCE_LIBRARY
-              NAMES kmlconvenience )
-find_library( LIBKML_DOM_LIBRARY
-              NAMES kmldom )
-find_library( LIBKML_ENGINE_LIBRARY
-              NAMES kmlengine )
-find_library( LIBKML_REGIONATOR_LIBRARY
-              NAMES kmlregionator )
-find_library( LIBKML_XSD_LIBRARY
-              NAMES kmlxsd )
-find_library( LIBKML_MINIZIP_LIBRARY
-              NAMES minizip )
-
-mark_as_advanced(   LIBKML_INCLUDE_DIR
-                    LIBKML_BASE_LIBRARY
-                    LIBKML_CONVENIENCE_LIBRARY
-                    LIBKML_DOM_LIBRARY
-                    LIBKML_ENGINE_LIBRARY
-                    LIBKML_REGIONATOR_LIBRARY
-                    LIBKML_XSD_LIBRARY
-                    LIBKML_MINIZIP_LIBRARY )
+mark_as_advanced(
+  LIBKML_INCLUDE_DIR
+  LIBKML_BASE_LIBRARY
+  LIBKML_DOM_LIBRARY
+  LIBKML_ENGINE_LIBRARY
+  )
 
 # handle the QUIETLY and REQUIRED arguments and set LIBKML_FOUND to TRUE if
 # all listed variables are TRUE
 include( FindPackageHandleStandardArgs )
-FIND_PACKAGE_HANDLE_STANDARD_ARGS( LibKML DEFAULT_MSG
-                                    LIBKML_BASE_LIBRARY
-                                    LIBKML_CONVENIENCE_LIBRARY
-                                    LIBKML_DOM_LIBRARY
-                                    LIBKML_ENGINE_LIBRARY
-                                    LIBKML_REGIONATOR_LIBRARY
-                                    LIBKML_XSD_LIBRARY
-                                    LIBKML_MINIZIP_LIBRARY
-                                    LIBKML_INCLUDE_DIR
-                                     )
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(
+  LibKML
+  DEFAULT_MSG
+  LIBKML_INCLUDE_DIR
+  LIBKML_BASE_LIBRARY
+  LIBKML_DOM_LIBRARY
+  LIBKML_ENGINE_LIBRARY
+  )
 
 if(LIBKML_FOUND)
   set(LIBKML_INCLUDE_DIRS ${LIBKML_INCLUDE_DIR})
-  set(LIBKML_LIBRARIES ${LIBKML_BASE_LIBRARY}
-                       ${LIBKML_CONVENIENCE_LIBRARY}
-                       ${LIBKML_DOM_LIBRARY}
-                       ${LIBKML_ENGINE_LIBRARY}
-                       ${LIBKML_REGIONATOR_LIBRARY}
-                       ${LIBKML_XSD_LIBRARY}
-                       ${LIBKML_MINIZIP_LIBRARY})
+  set(LIBKML_LIBRARIES
+    ${LIBKML_BASE_LIBRARY}
+    ${LIBKML_DOM_LIBRARY}
+    ${LIBKML_ENGINE_LIBRARY}
+    )
 endif()
diff --git a/CMake/FindLibSVM.cmake b/CMake/FindLibSVM.cmake
index cc15db682271e70994459569eb590b6d0e241900..93b2c9d126f4b7abe7aa89fb0d7a92fa40bc4f76 100644
--- a/CMake/FindLibSVM.cmake
+++ b/CMake/FindLibSVM.cmake
@@ -14,7 +14,7 @@
 #  LIBSVM_MINOR_VERSION - minor version
 #  LIBSVM_PATCH_VERSION - patch version
 #  LIBSVM_VERSION_STRING - version (ex. 2.9.0)
-#  LIBSVM_ROOT_DIR - root dir (ex. /usr/local)
+#  LIBSVM_ROOT_DIR - libsvm install directory
 
 #=============================================================================
 # Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
diff --git a/CMake/FindOpenThreads.cmake b/CMake/FindOpenThreads.cmake
index e57dff2ce667c6dceec96a49d55f011a0926877d..2462dbfb27cf1a0ed154e961ffcf637a346ccb5e 100644
--- a/CMake/FindOpenThreads.cmake
+++ b/CMake/FindOpenThreads.cmake
@@ -58,23 +58,9 @@
 # standard install paths.
 # Explicit -DVAR=value arguments should still be able to override everything.
 
-find_path(OPENTHREADS_INCLUDE_DIR OpenThreads/Thread
-    HINTS
-        # enough environment variables?
-        $ENV{OPENTHREADS_INCLUDE_DIR}
-        $ENV{OPENTHREADS_DIR}
-        $ENV{OSG_INCLUDE_DIR}
-        $ENV{OSG_DIR}
-        $ENV{OSGDIR}
-        $ENV{OpenThreads_ROOT}
-        $ENV{OSG_ROOT}
-    PATHS
-        /sw # Fink
-        /opt/local # DarwinPorts
-        /opt/csw # Blastwave
-        /opt
-        /usr/freeware
-    PATH_SUFFIXES include
+find_path(
+  OPENTHREADS_INCLUDE_DIR OpenThreads/Thread
+  PATH_SUFFIXES include
 )
 mark_as_advanced(OPENTHREADS_INCLUDE_DIR)
 
@@ -95,41 +81,12 @@ endif()
 
 find_library(OPENTHREADS_LIBRARY
     NAMES OpenThreads OpenThreadsWin32
-    HINTS
-        $ENV{OPENTHREADS_LIBRARY_DIR}
-        $ENV{OPENTHREADS_DIR}
-        $ENV{OSG_LIBRARY_DIR}
-        $ENV{OSG_DIR}
-        $ENV{OSGDIR}
-        $ENV{OpenThreads_ROOT}
-        $ENV{OSG_ROOT}
-    PATHS
-        /sw
-        /opt/local
-        /opt/csw
-        /opt
-        /usr/freeware
     PATH_SUFFIXES lib64 lib
 )
 mark_as_advanced(OPENTHREADS_LIBRARY)
 
 find_library(OPENTHREADS_LIBRARY_DEBUG
     NAMES OpenThreadsd OpenThreadsWin32d
-    HINTS
-        $ENV{OPENTHREADS_DEBUG_LIBRARY_DIR}
-        $ENV{OPENTHREADS_LIBRARY_DIR}
-        $ENV{OPENTHREADS_DIR}
-        $ENV{OSG_LIBRARY_DIR}
-        $ENV{OSG_DIR}
-        $ENV{OSGDIR}
-        $ENV{OpenThreads_ROOT}
-        $ENV{OSG_ROOT}
-    PATHS
-        /sw
-        /opt/local
-        /opt/csw
-        /opt
-        /usr/freeware
     PATH_SUFFIXES lib64 lib
 )
 mark_as_advanced(OPENTHREADS_LIBRARY_DEBUG)
diff --git a/CMake/FindQwt.cmake b/CMake/FindQwt.cmake
index d0c0e9a1b7a6811f1cc8e9ed24d80f3bea45765e..1c37f55eb89e8d34a759448e4fb60f7976943186 100644
--- a/CMake/FindQwt.cmake
+++ b/CMake/FindQwt.cmake
@@ -31,7 +31,7 @@
 #  QWT_MINOR_VERSION - minor version
 #  QWT_PATCH_VERSION - patch version
 #  QWT_VERSION_STRING - version (ex. 5.2.1)
-#  QWT_ROOT_DIR - root dir (ex. /usr/local)
+#  QWT_ROOT_DIR - root dir
 
 #=============================================================================
 # Copyright 2010-2013, Julien Schueller
diff --git a/CMake/FindShark.cmake b/CMake/FindShark.cmake
index 7dced6bb432c256b17cafd6bd3394bea97bac4e8..59bef138f730718a535ef984deace363cf4f8a47 100644
--- a/CMake/FindShark.cmake
+++ b/CMake/FindShark.cmake
@@ -55,12 +55,9 @@ find_library( SHARK_LIBRARY
 
 mark_as_advanced( SHARK_INCLUDE_DIR  SHARK_LIBRARY )
 
-find_package( Boost 1.48.0 REQUIRED QUIET COMPONENTS
-	system date_time filesystem
-	program_options serialization thread
-	unit_test_framework
-	)
-
+find_package( Boost 1.48.0 REQUIRED QUIET
+  COMPONENTS serialization
+  )
 if(NOT Boost_FOUND)
   message(FATAL_ERROR "Please make sure Boost 1.48.0 is installed on your system")
 endif()
@@ -107,28 +104,12 @@ string(REGEX MATCH
   "#define.SHARK_USE_OPENMP"
   SHARK_USE_OPENMP_matched "${SHARK_H_CONTENTS}")
 
-#this variable is added in cache but not used now
-# you can use it to see if shark installation has openMP
-# later if needed in other places..
-set(SHARK_USE_OPENMP FALSE CACHE BOOL "shark is built with OpenMP")
 if(SHARK_USE_OPENMP_matched)
-  set(SHARK_USE_OPENMP TRUE CACHE BOOL "shark is built with OpenMP" FORCE)
-endif()
-
-if(SHARK_USE_OPENMP)
-  message(STATUS "Shark is built with OpenMP: SHARK_USE_OPENMP = TRUE")
-  find_package(OpenMP REQUIRED QUIET)
-  if(OPENMP_FOUND)
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
-    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
-  else()
-    message(FATAL_ERROR "Your shark libraries are compiled with it OpenMP")
-    set(SHARK_FOUND FALSE)
+  if(NOT OTB_USE_OPENMP)
+    message(WARNING "Shark library is built with OpenMP and you have OTB_USE_OPENMP set to OFF.")
   endif()
-else()
-  message(STATUS "Shark is built without OpenMP: SHARK_USE_OPENMP = FALSE")
 endif()
+
 INCLUDE(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Shark
   REQUIRED_VARS SHARK_LIBRARY SHARK_INCLUDE_DIR
diff --git a/CMake/OTBCheckSSEFeatures.cmake b/CMake/OTBCheckSSEFeatures.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..a7c67ed7de4f8274c379f86af8663f85630793c3
--- /dev/null
+++ b/CMake/OTBCheckSSEFeatures.cmake
@@ -0,0 +1,63 @@
+function(check_sse_features sse_flags )
+  include(CheckCXXSourceRuns)
+  include(CheckCXXCompilerFlag)
+
+  set(${sse_flags} "0" PARENT_SCOPE)
+  # For apple assume sse2 is on for all intel builds, check for 64 and 32 bit versions
+  if(APPLE)
+      message(STATUS "For apple assume sse2 is on for all intel builds")
+    return()
+  endif()
+  set(sse_flags_detected)
+  if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_CLANG)
+    set(CMAKE_REQUIRED_FLAGS "-msse2")
+    set(sse_flags_detected "-msse2 -mfpmath=sse")
+  elseif(MSVC AND NOT CMAKE_CL_64)
+    set(CMAKE_REQUIRED_FLAGS "/arch:SSE2")
+    set(sse_flags_detected "/arch:SSE2")
+  endif()
+
+  check_cxx_source_runs("
+    #include <emmintrin.h>
+    int main ()
+    {
+     __m128d a, b;
+     double vals[2] = {0};
+     a = _mm_loadu_pd (vals);
+     b = _mm_add_pd (a,a);
+     _mm_storeu_pd (vals,b);
+     return (0);
+    }"
+    HAVE_SSE2_EXTENSIONS)
+
+  if(HAVE_SSE2_EXTENSIONS)
+    set(${sse_flags} "${sse_flags_detected}" PARENT_SCOPE)
+    return()
+  endif()
+
+  if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_CLANG)
+    set(CMAKE_REQUIRED_FLAGS "-msse")
+    set(sse_flags_detected "-msse -mfpmath=sse")
+  elseif(MSVC AND NOT CMAKE_CL_64)
+    set(CMAKE_REQUIRED_FLAGS "/arch:SSE")
+    set(sse_flags_detected "/arch:SSE")
+  endif()
+
+  check_cxx_source_runs("
+    #include <xmmintrin.h>
+    int main()
+    {
+        __m128 a, b;
+        float vals[4] = {0};
+        a = _mm_loadu_ps(vals);
+        b = a;
+        b = _mm_add_ps(a,b);
+        _mm_storeu_ps(vals,b);
+        return 0;
+    }" HAVE_SSE_EXTENSIONS)
+
+  if(HAVE_SSE_EXTENSIONS)
+    set(${sse_flags} "${sse_flags_detected}" PARENT_SCOPE)
+    return()
+  endif()
+endfunction() #check_sse_features
diff --git a/CMake/OTBConfig.cmake.in b/CMake/OTBConfig.cmake.in
index d0361832e47f1967ca2d18dbd22edbcf1ad6bb02..fcaed33779c658840d652a672a42d3d1cd785f2f 100644
--- a/CMake/OTBConfig.cmake.in
+++ b/CMake/OTBConfig.cmake.in
@@ -26,6 +26,11 @@
 # to load OTB's settings for an external project.
 @OTB_CONFIG_CODE@
 
+set(CMAKE_CXX_STANDARD 14)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+#RK: TODO: add sse2, see4, see4.1, openmp flags
+
 # The C and C++ flags added by OTB to the cmake-configured flags.
 set(OTB_REQUIRED_C_FLAGS "@OTB_REQUIRED_C_FLAGS@")
 set(OTB_REQUIRED_CXX_FLAGS "@OTB_REQUIRED_CXX_FLAGS@")
@@ -39,12 +44,24 @@ set(OTB_VERSION_PATCH "@OTB_VERSION_PATCH@")
 # OTB's CMake directory with modules OTB uses.
 set(OTB_CMAKE_DIR "@OTB_CONFIG_CMAKE_DIR@")
 
+# OTB uses OPENMP
+set(OTB_USE_OPENMP "@OTB_USE_OPENMP@")
+
+# OTB uses SSE optim
+set(OTB_USE_SSE_FLAGS "@OTB_USE_SSE_FLAGS@")
+
+# use Find*.cmake files included in OTB package for external dependencies. (OpenCV, GDAL etc..)
+set(CMAKE_MODULE_PATH ${OTB_CMAKE_DIR} ${CMAKE_MODULE_PATH})
+
 # The location of the UseOTB.cmake file.
 set(OTB_USE_FILE "@OTB_USE_FILE@")
 
 # Whether OTB was built with shared libraries.
 set(OTB_BUILD_SHARED "@BUILD_SHARED_LIBS@")
 
+# Default value for WINDOWS_EXPORT_ALL_SYMBOLS target property
+set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS "@OTB_CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS@")
+
 # List of available OTB modules.
 set(OTB_MODULES_ENABLED "@OTB_CONFIG_MODULES_ENABLED@")
 
diff --git a/CMake/OTBModuleEnablement.cmake b/CMake/OTBModuleEnablement.cmake
index 749a3b375f109c24c8050f4d4384a7a06f5b99f7..4ec34d94df5315c4381769b3c33a380358163a86 100644
--- a/CMake/OTBModuleEnablement.cmake
+++ b/CMake/OTBModuleEnablement.cmake
@@ -157,14 +157,18 @@ macro(otb_module_enable otb-module _needed_by)
   endif()
   if(NOT ${otb-module}_ENABLED)
     set(${otb-module}_ENABLED 1)
-    foreach(dep IN LISTS OTB_MODULE_${otb-module}_DEPENDS)
-      otb_module_enable(${dep} ${otb-module})
-    endforeach()
-    foreach(dep IN LISTS OTB_MODULE_${otb-module}_OPTIONAL_DEPENDS)
-      otb_module_enable(${dep} ${otb-module})
-    endforeach()
-    if(${otb-module}_TESTED_BY AND (OTB_BUILD_DEFAULT_MODULES OR OTB_BUILD_ALL_MODULES_FOR_TESTS OR Module_${otb-module}))
-      otb_module_enable(${${otb-module}_TESTED_BY} "")
+    # if this module has an ACTIVATION_OPTION=OFF, don't bother enable its dependencies
+    if(NOT (OTB_MODULE_${otb-module}_ACTIVATION_OPTION
+     AND NOT ${OTB_MODULE_${otb-module}_ACTIVATION_OPTION}))
+      foreach(dep IN LISTS OTB_MODULE_${otb-module}_DEPENDS)
+        otb_module_enable(${dep} ${otb-module})
+      endforeach()
+      foreach(dep IN LISTS OTB_MODULE_${otb-module}_OPTIONAL_DEPENDS)
+        otb_module_enable(${dep} ${otb-module})
+      endforeach()
+      if(${otb-module}_TESTED_BY AND (OTB_BUILD_DEFAULT_MODULES OR OTB_BUILD_ALL_MODULES_FOR_TESTS OR Module_${otb-module}))
+        otb_module_enable(${${otb-module}_TESTED_BY} "")
+      endif()
     endif()
   endif()
 endmacro()
diff --git a/CMake/OTBSetStandardCompilerFlags.cmake b/CMake/OTBSetStandardCompilerFlags.cmake
index 1d6d5fe51868db0778c318e405ccfca3c8a9ff13..d2495d4a0756a73bf0f4edd1fffe251cbdb4a636 100644
--- a/CMake/OTBSetStandardCompilerFlags.cmake
+++ b/CMake/OTBSetStandardCompilerFlags.cmake
@@ -209,6 +209,9 @@ macro(check_compiler_platform_flags)
         set(CMAKE_EXE_LINKER_FLAGS "-Wl,--enable-auto-import")
       endif()
     else()
+      if(MSVC)
+        set(OTB_REQUIRED_LINK_FLAGS "${OTB_REQUIRED_LINK_FLAGS} /MANIFEST:NO")
+      endif()
       # if CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS is on, then
       # BUILD_SHARED_LIBS works as it would on other systems
       if(NOT CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS)
@@ -232,35 +235,11 @@ macro(check_compiler_platform_flags)
       ("${CMAKE_CXX_COMPILER_VERSION}" VERSION_GREATER "4.8" AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9") ))
       set(OTB_REQUIRED_CXX_FLAGS "${OTB_REQUIRED_CXX_FLAGS} -Wno-array-bounds")
     endif()
+  endif()
 
-   if(APPLE)
-     option(OTB_USE_64BITS_APPLE_TRUNCATION_WARNING "Turn on warnings on 64bits to 32bits truncations." OFF)
-     mark_as_advanced(OTB_USE_64BITS_APPLE_TRUNCATION_WARNING)
-
-     execute_process(COMMAND "${CMAKE_C_COMPILER}" --version
-       OUTPUT_VARIABLE _version ERROR_VARIABLE _version)
-
-     # -fopenmp breaks compiling the HDF5 library in shared library mode
-     # on the OS X platform -- at least with gcc 4.2 from Xcode.
-     set(compile_flag_lists CMAKE_C_FLAGS CMAKE_CXX_FLAGS
-       CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_MINSIZEREL
-       CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO
-       CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL
-       CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO)
-     foreach(listname ${compile_flag_lists})
-       if("${${listname}}" MATCHES ".*-fopenmp.*")
-         string(REPLACE "-fopenmp" "" tmpFlags "${${listname}}")
-         set(${listname} "${tmpFlags}")
-         message("-fopenmp causes incorrect compliation of HDF, removing from ${listname}")
-       endif()
-     endforeach()
-   endif()
-
-   # gcc must have -msse2 option to enable sse2 support
-   if(VNL_CONFIG_ENABLE_SSE2 OR VNL_CONFIG_ENABLE_SSE2_ROUNDING)
-     set(OTB_REQUIRED_CXX_FLAGS "${OTB_REQUIRED_CXX_FLAGS} -msse2")
-   endif()
-
+  if(APPLE)
+    option(OTB_USE_64BITS_APPLE_TRUNCATION_WARNING "Turn on warnings on 64bits to 32bits truncations." OFF)
+    mark_as_advanced(OTB_USE_64BITS_APPLE_TRUNCATION_WARNING)
   endif()
 
   #-----------------------------------------------------------------------------
@@ -293,6 +272,36 @@ macro(check_compiler_platform_flags)
     set(OTB_REQUIRED_LINK_FLAGS "${OTB_REQUIRED_LINK_FLAGS} -mthreads")
   endif()
 
+  if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined")
+    set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,--no-undefined")
+    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--no-undefined")
+    set(OTB_REQUIRED_LINK_FLAGS "${OTB_REQUIRED_LINK_FLAGS} -Wl,--no-undefined")
+  endif()
+
+  # check for OpenMP
+  if(OTB_USE_OPENMP)
+    message(STATUS "OpenMP support requested with OTB_USE_OPENMP=${OTB_USE_OPENMP}")
+    find_package(OpenMP QUIET)
+  endif()
+  if(OPENMP_FOUND)
+    message(STATUS "Adding '${OpenMP_CXX_FLAGS}' to OTB_REQUIRED_CXX_FLAGS ")
+    set(OTB_REQUIRED_CXX_FLAGS "${OTB_REQUIRED_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+    if(OpenMP_EXE_LINKER_FLAGS)
+      set(OTB_REQUIRED_LINK_FLAGS "${OTB_REQUIRED_LINK_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
+    endif()
+  endif()
+
+  set(OTB_SSE_FLAGS)
+  if(OTB_USE_SSE_FLAGS)
+    message(STATUS "SIMD extensions requested with OTB_USE_SSE_FLAGS=${OTB_USE_SSE_FLAGS}")
+    include(OTBCheckSSEFeatures)
+    check_sse_features(OTB_SSE_FLAGS)
+    if(OTB_SSE_FLAGS)
+      message(STATUS "Adding '${OTB_SSE_FLAGS}' to OTB_REQUIRED_CXX_FLAGS")
+      set(OTB_REQUIRED_CXX_FLAGS "${OTB_REQUIRED_CXX_FLAGS} ${OTB_SSE_FLAGS}")
+    endif()
+  endif()
 
   #-----------------------------------------------------------------------------
   # The frename-registers option does not work due to a bug in the gnu compiler.
@@ -300,6 +309,7 @@ macro(check_compiler_platform_flags)
   # will be produced.  This is first documented in the gcc4 man page.
   if(CMAKE_COMPILER_IS_GNUCXX)
     set(ALL_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS} ${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
+    #TODO: list(REMOVE_DUPLICATES ALL_FLAGS)
     separate_arguments(ALL_FLAGS)
     foreach(COMP_OPTION ${ALL_FLAGS})
       if("${COMP_OPTION}" STREQUAL "-frename-registers")
@@ -349,4 +359,4 @@ macro(set_linker_stack_size_flag exe_target requested_stack_size)
   elseif(MINGW)
     set_target_properties(${exe_target} PROPERTIES LINK_FLAGS "-Wl,--stack,${requested_stack_size}")
   endif()
-endmacro()
\ No newline at end of file
+endmacro()
diff --git a/CMake/otbcli.bat.in b/CMake/otbcli.bat.in
index 165d8338726754d5f7188bc7ae3ae3e52a41685d..3016c022e474338576c20cea114da8662d247045 100644
--- a/CMake/otbcli.bat.in
+++ b/CMake/otbcli.bat.in
@@ -21,8 +21,8 @@ if exist %CURRENT_SCRIPT_DIR%..\@OTB_INSTALL_APP_DIR_NATIVE@ (
 )
 
 ::set GDAL_DATA, EPSG_CSV and update PATH
-if exist %CURRENT_SCRIPT_DIR%\..\otbenv.cmd (
-    call %CURRENT_SCRIPT_DIR%\..\otbenv.cmd
+if exist %CURRENT_SCRIPT_DIR%\..\otbenv.bat (
+    call %CURRENT_SCRIPT_DIR%\..\otbenv.bat
 )
 
 set LC_NUMERIC=C
diff --git a/CMake/otbcli.sh.in b/CMake/otbcli.sh.in
index 3026dad88730fcaca2543bff9e97c5db66a85c6a..65bec6865398591429712c71c636bed7b1abdeb6 100644
--- a/CMake/otbcli.sh.in
+++ b/CMake/otbcli.sh.in
@@ -16,15 +16,6 @@ else
   OTB_CLI_LAUNCHER=otbApplicationLauncherCommandLine
 fi
 
-# works for install tree
-if [ -d "$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@" ]
-then
-  OTB_APPLICATION_PATH=$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@:$OTB_APPLICATION_PATH
-fi
-
-# export it to make it available to otbApplicationLauncherCommandLine environment
-export OTB_APPLICATION_PATH
-
 # avoid numerical issues caused by locale
 export LC_NUMERIC=C
 
@@ -32,6 +23,13 @@ export LC_NUMERIC=C
 # Note that OTB_APPLICATION_PATH is reset here.
 if [ -f "$CURRENT_SCRIPT_DIR/../otbenv.profile" ]; then
     . "$CURRENT_SCRIPT_DIR/../otbenv.profile"
+else
+    # works for install tree
+    if [ -d "$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@" ]; then
+	OTB_APPLICATION_PATH=$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@:$OTB_APPLICATION_PATH
+    fi
+    # export it to make it available to otbApplicationLauncherCommandLine environment
+    export OTB_APPLICATION_PATH
 fi
 
 # start the application
diff --git a/CMake/otbgui.bat.in b/CMake/otbgui.bat.in
index c02e16ebf88e53714c73d4f8f93269be7961e65e..a450ce7881e68eff1a4d718155d1c7e63149fe82 100644
--- a/CMake/otbgui.bat.in
+++ b/CMake/otbgui.bat.in
@@ -22,6 +22,11 @@ if exist %CURRENT_SCRIPT_DIR%../@OTB_INSTALL_APP_DIR@ (
 
 set LC_NUMERIC=C
 
+::set GDAL_DATA, EPSG_CSV and update PATH
+if exist %CURRENT_SCRIPT_DIR%\..\otbenv.bat (
+    call %CURRENT_SCRIPT_DIR%\..\otbenv.bat
+)
+
 :: start the application
 %OTB_GUI_LAUNCHER% %*
 endlocal
diff --git a/CMake/otbgui.sh.in b/CMake/otbgui.sh.in
index 5f6354a75ced0919941e7012083e02cda4696a4c..8633efad8cb9097ab3caf34b9c80a91a18f129d7 100644
--- a/CMake/otbgui.sh.in
+++ b/CMake/otbgui.sh.in
@@ -16,21 +16,19 @@ else
   OTB_GUI_LAUNCHER=otbApplicationLauncherQt
 fi
 
-# use the default install tree path for applications
-if [ -d "$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@" ]
-then
-  OTB_APPLICATION_PATH=$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@:$OTB_APPLICATION_PATH
-fi
-
-# export it to make it available to otbApplicationLauncherCommandLine environment
-export OTB_APPLICATION_PATH
-
 # avoid numerical issues caused by locale
 export LC_NUMERIC=C
 
 # Export GDAL_DATA, EPSG_CSV
 if [ -f "$CURRENT_SCRIPT_DIR/../otbenv.profile" ]; then
     . "$CURRENT_SCRIPT_DIR/../otbenv.profile"
+else
+    # use the default install tree path for applications
+    if [ -d "$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@" ]; then
+	OTB_APPLICATION_PATH=$CURRENT_SCRIPT_DIR/../@OTB_INSTALL_APP_DIR@:$OTB_APPLICATION_PATH
+    fi
+    # export it to make it available to otbApplicationLauncherCommandLine environment
+    export OTB_APPLICATION_PATH
 fi
 
 # start the application
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2380ec3d2599cda6ae1aa49294f947761987e8f1..31310a07f0d1b869ac0f5809d5b8f2b6081c0aab 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -99,7 +99,7 @@ find_path(OTB_DATA_ROOT
   NAMES README-OTB-Data
   HINTS $ENV{OTB_DATA_ROOT} ${OTB_SOURCE_DIR}/../OTB-Data
 )
-mark_as_advanced(OTB_DATA_ROOT)
+#mark_as_advanced(OTB_DATA_ROOT)
 
 if(OTB_DATA_ROOT)
   repository_status(${OTB_DATA_ROOT} OTB_DATA_GIT_STATUS_MESSAGE)
@@ -213,10 +213,12 @@ endif()
 option(OTB_USE_DEPRECATED "Turn on the use and test of deprecated classes" OFF)
 mark_as_advanced(OTB_USE_DEPRECATED)
 
+option(OTB_USE_OPENMP "Add openmp compiler and linker flags" OFF)
+option(OTB_USE_SSE_FLAGS "Enable SIMD optimizations (hardware dependent)." ON)
 #-----------------------------------------------------------------------------
 # SHOW_ALL_MSG_DEBUG option
 option(OTB_SHOW_ALL_MSG_DEBUG "Show all debug messages (very verbose)" OFF)
-mark_as_advanced(OTB_SHOW_ALL_MSG_DEBUG)
+#mark_as_advanced(OTB_SHOW_ALL_MSG_DEBUG)
 
 include(OTBSetStandardCompilerFlags)
 #---------------------------------------------------------------
@@ -504,6 +506,8 @@ foreach(otb_option
     OTB_WRAP_PYTHON
     OTB_WRAP_JAVA
     OTB_DATA_ROOT
+    OTB_USE_OPENMP
+    OTB_USE_SSE_FLAGS
     )
     get_white_spaces("${otb_option}" spaces)
   message("${otb_option} ${spaces} = ${${otb_option}}")
diff --git a/Documentation/Cookbook/Scripts/otbGenerateWrappersRstDoc.py b/Documentation/Cookbook/Scripts/otbGenerateWrappersRstDoc.py
index aee544f9151f4deed65bb6f6bfecba1010b89269..59019e33e2a0a35c32134412512a82bbae52ab54 100755
--- a/Documentation/Cookbook/Scripts/otbGenerateWrappersRstDoc.py
+++ b/Documentation/Cookbook/Scripts/otbGenerateWrappersRstDoc.py
@@ -27,6 +27,12 @@ def ConvertString(s):
     s = s.replace('*','\*')
     return s
 
+def ConvertToLineBlock(s):
+    '''Convert a string into a line bloc (prefix with |) '''
+    s = s.strip()
+    s = s.replace('*','\*')
+    s = "  | " + s.replace('\n','\n  | ')
+    return s
 
 def EncloseString(s):
     if not s.startswith("\"") :
@@ -484,7 +490,7 @@ def ApplicationToRst(appname):
         output += "These additional resources can be useful for further information: " + linesep
         # hlink="<http://www.readthedocs.org/" + ConvertString(app.GetDocSeeAlso()) + ".html>`_ "
         # output += linesep + "`" + ConvertString(app.GetDocSeeAlso()) + " " + hlink + linesep + linesep
-        output += linesep + ConvertString(app.GetDocSeeAlso()) + linesep + linesep
+        output += ConvertToLineBlock(app.GetDocSeeAlso()) + linesep + linesep
 
     return output
 
@@ -507,7 +513,7 @@ def GenerateRstForApplications():
     allApps = None
     try:
         allApps = otbApplication.Registry.GetAvailableApplications( )
-    except e:
+    except:
         print 'error in otbApplication.Registry.GetAvailableApplications()'
         sys.exit(1)
 
diff --git a/Documentation/SoftwareGuide/Latex/Classification.tex b/Documentation/SoftwareGuide/Latex/Classification.tex
index fc255644fb110ecb3103750e46838a703649f86e..90e4b41d462b8f717722d811ffcf49a5cd8bad7f 100644
--- a/Documentation/SoftwareGuide/Latex/Classification.tex
+++ b/Documentation/SoftwareGuide/Latex/Classification.tex
@@ -64,197 +64,116 @@ properties than the image to classify, in order to build a classification model.
 %to other OTB libraries (edit the \code{TARGET\_LINK\_LIBRARIES} to add them),
 %for example OTBLearning, OTBMarkov.
 
-\section{Unsupervised classification}
-
-\subsection{K-Means Classification}
-\label{sec:KMeansClassifier}
-
-\subsubsection{Simple version}
-\ifitkFullVersion
-\input{ScalarImageKmeansClassifier.tex}
-\fi
-\ifitkFullVersion
-\input{ScalarImageKmeansModelEstimator.tex}
-\fi
-
-\subsubsection{General approach}
-\ifitkFullVersion
-\input{KMeansImageClassificationExample.tex}
-\fi
-
-\subsubsection{k-d Tree Based k-Means Clustering}
-\label{sec:KdTreeBasedKMeansClustering}
-\ifitkFullVersion
-\input{KdTreeBasedKMeansClustering.tex}
-\fi
-
-\subsection{Kohonen's Self Organizing Map}
-\label{sec:SOM}
-\input{Kohonen}
-%%%1. Construction SOM
-\subsubsection{Building a color table}
-\label{sec:SOMColorTable}
-\input{SOMExample}
-\subsubsection{SOM Classification}
-\label{sec:SOMClassification}
-\input{SOMClassifierExample}
-
-\subsubsection{Multi-band, streamed classification}
-
-\ifitkFullVersion
-\input{SOMImageClassificationExample.tex}
-\fi
-
-%%%2. Lecture SOM et ensemble de vecteurs autre image pour construire
-%%%ActivationMAP 
-
-%\subsection{Bayesian classification}
-
-\subsection{Bayesian Plug-In Classifier}
-\label{sec:BayesianPluginClassifier}
-
-\ifitkFullVersion 
-\input{BayesianPluginClassifier.tex}
-\fi
-
-
-\subsection{Expectation Maximization Mixture Model Estimation}
-\label{sec:ExpectationMaximizationMixtureModelEstimation}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\section{Machine Learning Framework}
 
-\ifitkFullVersion 
-\input{ExpectationMaximizationMixtureModelEstimator.tex}
-\fi
-
-
-
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsection{Statistical Segmentations}
-\label{sec:StatisticalSegmentations}
-
-%\subsection{Markov Random Fields}
+\subsection{Machine learning models}
+\label{sec:MLGenericFramework}
 
-\subsubsection{Stochastic Expectation Maximization}
-\label{sec:SEM}
+The OTB classification is implemented as a generic Machine Learning
+framework, supporting several possible machine learning libraries as backends.
+The base class \doxygen{otb}{MachineLearningModel} defines this framework.
+As of now libSVM (the machine learning library historically integrated in OTB),
+machine learning methods of OpenCV library (\cite{opencv_library}) and also
+Shark machine learning library (\cite{shark_library}) are available. Both
+supervised and unsupervised classifiers are supported in the framework.
 
-The Stochastic Expectation Maximization (SEM) approach is a stochastic 
-version of the EM mixture estimation seen on
-section~\ref{sec:ExpectationMaximizationMixtureModelEstimation}. It has been 
-introduced by \cite{CeDi95} to prevent convergence of the EM approach from
-local minima. It avoids the analytical maximization issued by integrating a
-stochastic sampling procedure in the estimation process. It induces an almost
-sure (a.s.) convergence to the algorithm.
+The current list of classifiers available through the same generic interface within the OTB is:
 
-From the initial two step formulation of the EM mixture estimation, the SEM
-may be decomposed into 3 steps:
-\begin{enumerate}
-\item \textbf{E-step}, calculates the expected membership values for each 
-measurement vector to each classes.
-\item \textbf{S-step}, performs a stochastic sampling of the membership vector
-to each classes, according to the membership values computed in the E-step.
-\item \textbf{M-step}, updates the parameters of the membership probabilities
-(parameters to be defined through the class
-\subdoxygen{itk}{Statistics}{ModelComponentBase} and its inherited classes).
-\end{enumerate}
-The implementation of the SEM has been turned to a contextual SEM in the sense
-where the evaluation of the membership parameters is conditioned to
-membership values of the spatial neighborhood of each pixels.
+\begin{itemize}
+  \item \textbf{LibSVM}: Support Vector Machines classifier based on libSVM.
+  \item \textbf{SVM}: Support Vector Machines classifier based on OpenCV, itself based on libSVM.
+  \item \textbf{Bayes}: Normal Bayes classifier based on OpenCV.
+  \item \textbf{Boost}: Boost classifier based on OpenCV.
+  \item \textbf{DT}: Decision Tree classifier based on OpenCV.
+  \item \textbf{RF}: Random Forests classifier based on the Random Trees in OpenCV.
+  \item \textbf{GBT}: Gradient Boosted Tree classifier based on OpenCV (removed in version 3).
+  \item \textbf{KNN}: K-Nearest Neighbors classifier based on OpenCV.
+  \item \textbf{ANN}: Artificial Neural Network classifier based on OpenCV.
+  \item \textbf{SharkRF} : Random Forests classifier based on Shark.
+  \item \textbf{SharkKM} : KMeans unsupervised classifier based on Shark.
+\end{itemize}
 
-\ifitkFullVersion 
-\input{SEMModelEstimatorExample.tex}
-\fi
+These models have a common interface, with the following major functions:
+\begin{itemize}
+  \item \code{SetInputListSample(InputListSampleType *in)} : set the list of input samples
+  \item \code{SetTargetListSample(TargetListSampleType *in)} : set the list of target samples
+  \item \code{Train()} : train the model based on input samples
+  \item \code{Save(...)} : saves the model to file
+  \item \code{Load(...)} : load a model from file
+  \item \code{Predict(...)} : predict a target value for an input sample
+  \item \code{PredictBatch(...)} : prediction on a list of input samples
+\end{itemize}
 
+The \code{PredictBatch(...)} function can be multi-threaded when
+called either from a multi-threaded filter, or from a single location. In
+the later case, it creates several threads using OpenMP.
+There is a factory mechanism on top of the model class (see
+\doxygen{otb}{MachineLearningModelFactory}). Given an input file,
+the static function \code{CreateMachineLearningModel(...)} is able
+to instanciate a model of the right type.
 
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+For unsupervised models, the target samples \textbf{still have to be set}. They
+won't be used so you can fill a ListSample with zeros.
 
-\subsection{Classification using Markov Random Fields}
-\label{sec:MarkovRandomField}
+%-------------------------------------------------------------------------------
+\subsection{Training a model}
 
-Markov Random Fields are probabilistic models that use the statistical
-dependency between
-pixels in a neighborhood to infeer the value of a give pixel.
+The models are trained from a list of input samples, stored in a
+\subdoxygen{itk}{Statistics}{ListSample}. For supervised classifiers, they
+also need a list of targets associated to each input sample. Whatever the
+source of samples, it has to be converted into a \code{ListSample} before
+being fed into the model.
 
-\subsubsection{ITK framework}
-\label{sec:MarkovRandomFieldITK}
-The
-\subdoxygen{itk}{Statistics}{MRFImageFilter} uses the maximum a posteriori (MAP)
-estimates for modeling the MRF. The object traverses the data set and uses the
-model generated by the Mahalanobis distance classifier to get the the distance
-between each pixel in the data set to a set of known classes, updates the
-distances by evaluating the influence of its neighboring pixels (based on a MRF
-model) and finally, classifies each pixel to the class which has the minimum
-distance to that pixel (taking the neighborhood influence under consideration).
-The energy function minimization is done using the iterated conditional modes
-(ICM) algorithm \cite{Besag1986}.
+Then, model-specific parameters can be set. And finally, the \code{Train()}
+method starts the learning step. Once the model is trained it can be saved
+to file using the function \code{Save()}. The following examples show how
+to do that.
 
-\ifitkFullVersion
-\input{ScalarImageMarkovRandomField1.tex}
-\fi 
+\input{TrainMachineLearningModelFromSamplesExample.tex}
 
-\subsubsection{OTB framework}
-\label{sec:MarkovRandomFieldOTB}
-The ITK approach was considered not to be flexible enough for some
-remote sensing applications. Therefore, we decided to implement our
-own framework.
-\index{Markov}
+\input{TrainMachineLearningModelFromImagesExample.tex}
 
-\begin{figure}[th]
-  \centering
-  \includegraphics[width=0.7\textwidth]{MarkovFramework.eps}
-  \itkcaption[OTB Markov Framework]{OTB Markov Framework.}
-  \label{fig:markovFramework}
-\end{figure}
+%-------------------------------------------------------------------------------
+\subsection{Prediction of a model}
 
-\index{Markov!Classification}
-\ifitkFullVersion
-\input{MarkovClassification1Example.tex}
-\fi 
+For the prediction step, the usual process is to:
+\begin{itemize}
+\item Load an existing model from a file.
+\item Convert the data to predict into a \code{ListSample}.
+\item Run the \code{PredictBatch(...)} function.
+\end{itemize}
 
-\index{Markov!Classification}
-\ifitkFullVersion
-\input{MarkovClassification2Example.tex}
-\fi 
+There is an image filter that perform this step on a whole image, supporting
+streaming and multi-threading: \doxygen{otb}{ImageClassificationFilter}.
 
-\index{Markov!Classification}
 \ifitkFullVersion
-\input{MarkovClassification3Example.tex}
-\fi 
+\input{SupervisedImageClassificationExample.tex}
+\fi
 
-\index{Markov!Regularization}
-\ifitkFullVersion
-\input{MarkovRegularizationExample.tex}
-\fi 
+%-------------------------------------------------------------------------------
+\subsection{Integration in applications}
 
+The classifiers are integrated in several OTB Applications. There is a base
+class that provides an easy access to all the classifiers:
+\subdoxygen{otb}{Wrapper}{LearningApplicationBase}. As each machine learning
+model has a specific set of parameters, the base class
+\code{LearningApplicationBase} knows how to expose each type of classifier with
+its dedicated parameters (a task that is a bit tedious so we want to implement
+it only once). The \code{DoInit()} method creates a choice parameter named
+\code{classifier} which contains the different supported classifiers along
+with their parameters.
 
+The function \code{Train(...)} provide an easy way to train the selected
+classifier, with the corresponding parameters, and save the model to file.
 
+On the other hand, the function \code{Classify(...)} allows to load a model
+from file and apply it on a list of samples.
 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Supervised classification}
 
-\subsection{Generic machine learning framework}
-\label{sec:MLGenericFramework}
-
-The OTB supervised classification is implemented as a generic Machine Learning
-framework, supporting several possible machine learning libraries as backends.
-As of now libSVM (the machine learning library historically integrated in OTB),
-machine learning methods of OpenCV library (\cite{opencv_library}) and also
-Shark machine learning library (\cite{shark_library}) are available.
-
-The current list of classifiers available through the same generic interface within the OTB is:
-
-\begin{itemize}
-  \item \textbf{LibSVM}: Support Vector Machines classifier based on libSVM.
-  \item \textbf{SVM}: Support Vector Machines classifier based on OpenCV, itself based on libSVM.
-  \item \textbf{Bayes}: Normal Bayes classifier based on OpenCV.
-  \item \textbf{Boost}: Boost classifier based on OpenCV.
-  \item \textbf{DT}: Decision Tree classifier based on OpenCV.
-  \item \textbf{RF}: Random Forests classifier based on the Random Trees in OpenCV.
-  \item \textbf{GBT}: Gradient Boosted Tree classifier based on OpenCV.
-  \item \textbf{KNN}: K-Nearest Neighbors classifier based on OpenCV.
-  \item \textbf{ANN}: Artificial Neural Network classifier based on OpenCV.
-\end{itemize}
-
-
-\subsection{An example of supervised classification method: Support Vector Machines}
+\subsection{Support Vector Machines}
 \label{sec:SupportVectorMachines}
 
 \subsubsection{SVM general description}
@@ -371,33 +290,35 @@ is the one that we use, the final decision is taken by choosing the
 class which is most often selected by the whole set of SVM.
 
 
+%-------------------------------------------------------------------------------
+\subsection{Shark Random Forests}
 
-\subsection{Learning from samples}
-\label{ssec:LearningFromSamples}
-\input{TrainMachineLearningModelFromSamplesExample.tex}
-
-\subsection{Learning from images}
-\label{ssec:LearningFromImages}
-\input{TrainMachineLearningModelFromImagesExample.tex}
-
-%\subsection{Image Classification}
-%\label{sec:ImageClassification}
-%\input{SVMImageEstimatorClassificationMultiExample}
-
-
-\subsection{Multi-band, streamed classification}
-
-\ifitkFullVersion
-\input{SupervisedImageClassificationExample.tex}
-\fi
-
+The Random Forests algorithm is also available in OTB machine learning
+framework. This model builds a set of decision trees. Each tree may not give
+a reliable prediction, but taking them together, they form a robust classifier.
+The prediction of this model is the mode of the predictions of individual trees.
 
+There are two implementations: one in OpenCV and the other on in
+Shark. The Shark implementation has a noteworthy advantage: the training step
+is parallel. It uses the following parameters:
+\begin{itemize}
+\item The number of trees to train
+\item The number of random attributes to investigate at each node
+\item The maximum node size to decide a split
+\item The ratio of the original training dataset to use as the out of bag sample
+\end{itemize}
 
+Except these specific parameter, its usage is exactly the same as the other
+machine learning models (such as the SVM model).
 
-\subsection{Generic Kernel SVM}
+%-------------------------------------------------------------------------------
+\subsection{Generic Kernel SVM (deprecated)}
 OTB has developed a specific interface for user-defined kernels. However, the 
-following functions use a deprecated OTB interface. A function 
-$k(\cdot,\cdot)$ is considered to be a kernel when:
+following functions use a deprecated OTB interface. The code source for these
+Generic Kernels has been removed from the official repository. It is now
+available as a remote module: \href{https://github.com/jmichel-otb/GKSVM}{GKSVM}.
+
+A function $k(\cdot,\cdot)$ is considered to be a kernel when:
 \begin{align}\label{eqMercer}
         \forall g(\cdot) \in {\cal L}^2(\mathbbm{R}^n) \quad & \text{so 
 that} \quad
@@ -428,7 +349,7 @@ with:
 \end{verbatim}
 This simple example shows that the classical dot product is already 
 implemented
-into \subdoxygen{otb}{GenericKernelFunctorBase}{dot()} as a protected
+into \code{otb::GenericKernelFunctorBase::dot()} as a protected
 function.
 \item The \code{Update()} function which synchronizes local variables and 
 their
@@ -438,16 +359,16 @@ the way to use it.
 
 Some pre-defined generic kernels have already been implemented in OTB:
 \begin{itemize}
-\item \doxygen{otb}{MixturePolyRBFKernelFunctor} which implements a 
+\item \code{otb::MixturePolyRBFKernelFunctor} which implements a 
 linear mixture
 of a polynomial and a RBF kernel;
-\item \doxygen{otb}{NonGaussianRBFKernelFunctor} which implements a non
+\item \code{otb::NonGaussianRBFKernelFunctor} which implements a non
 gaussian RBF kernel;
-\item \doxygen{otb}{SpectralAngleKernelFunctor}, a kernel that integrates
+\item \code{otb::SpectralAngleKernelFunctor}, a kernel that integrates
 the Spectral Angle, instead of the Euclidean distance, into an inverse 
 multiquadric kernel.
 This kernel may be appropriated when using multispectral data.
-\item \doxygen{otb}{ChangeProfileKernelFunctor}, a kernel which is
+\item \code{otb::ChangeProfileKernelFunctor}, a kernel which is
 dedicated to the supervized classification of the multiscale change profile
 presented in section \ref{sec:KullbackLeiblerProfile}.
 \end{itemize}
@@ -465,8 +386,185 @@ presented in section \ref{sec:KullbackLeiblerProfile}.
 \fi
 
 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\section{Unsupervised classification}
+
+\subsection{K-Means Classification}
+\label{sec:KMeansClassifier}
+
+\subsubsection{Shark version}
+
+The KMeans algorithm has been implemented in Shark library, and has been
+wrapped in the OTB machine learning framework. It is the first unsupervised
+algorithm in this framework. It can be used in the same way as other machine
+learning models. Remember that even if unsupervised model don't use a label
+information on the samples, the target ListSample still has to be set in
+\code{MachineLearningModel}. A ListSample filled with zeros can be used.
+
+This model uses a hard clustering model with the following parameters:
+\begin{itemize}
+\item The maximum number of iterations
+\item The number of centroids (K)
+\item An option to normalize input samples
+\end{itemize}
+
+As with Shark Random Forests, the training step is parallel.
+
+\subsubsection{Simple version}
+\ifitkFullVersion
+\input{ScalarImageKmeansClassifier.tex}
+\fi
+\ifitkFullVersion
+\input{ScalarImageKmeansModelEstimator.tex}
+\fi
+
+\subsubsection{General approach}
+\ifitkFullVersion
+\input{KMeansImageClassificationExample.tex}
+\fi
+
+\subsubsection{k-d Tree Based k-Means Clustering}
+\label{sec:KdTreeBasedKMeansClustering}
+\ifitkFullVersion
+\input{KdTreeBasedKMeansClustering.tex}
+\fi
+%-------------------------------------------------------------------------------
+\subsection{Kohonen's Self Organizing Map}
+\label{sec:SOM}
+\input{Kohonen}
+%%%1. Construction SOM
+\subsubsection{Building a color table}
+\label{sec:SOMColorTable}
+\input{SOMExample}
+\subsubsection{SOM Classification}
+\label{sec:SOMClassification}
+\input{SOMClassifierExample}
+
+\subsubsection{Multi-band, streamed classification}
+
+\ifitkFullVersion
+\input{SOMImageClassificationExample.tex}
+\fi
+
+%%%2. Lecture SOM et ensemble de vecteurs autre image pour construire
+%%%ActivationMAP 
+
+%\subsection{Bayesian classification}
+%-------------------------------------------------------------------------------
+\subsection{Bayesian Plug-In Classifier}
+\label{sec:BayesianPluginClassifier}
+
+\ifitkFullVersion
+\input{BayesianPluginClassifier.tex}
+\fi
+
+%-------------------------------------------------------------------------------
+\subsection{Expectation Maximization Mixture Model Estimation}
+\label{sec:ExpectationMaximizationMixtureModelEstimation}
+
+\ifitkFullVersion
+\input{ExpectationMaximizationMixtureModelEstimator.tex}
+\fi
+
+
+
 
+%-------------------------------------------------------------------------------
+\subsection{Statistical Segmentations}
+\label{sec:StatisticalSegmentations}
 
+%\subsection{Markov Random Fields}
+
+\subsubsection{Stochastic Expectation Maximization}
+\label{sec:SEM}
+
+The Stochastic Expectation Maximization (SEM) approach is a stochastic 
+version of the EM mixture estimation seen on
+section~\ref{sec:ExpectationMaximizationMixtureModelEstimation}. It has been 
+introduced by \cite{CeDi95} to prevent convergence of the EM approach from
+local minima. It avoids the analytical maximization issued by integrating a
+stochastic sampling procedure in the estimation process. It induces an almost
+sure (a.s.) convergence to the algorithm.
+
+From the initial two step formulation of the EM mixture estimation, the SEM
+may be decomposed into 3 steps:
+\begin{enumerate}
+\item \textbf{E-step}, calculates the expected membership values for each 
+measurement vector to each classes.
+\item \textbf{S-step}, performs a stochastic sampling of the membership vector
+to each classes, according to the membership values computed in the E-step.
+\item \textbf{M-step}, updates the parameters of the membership probabilities
+(parameters to be defined through the class
+\subdoxygen{itk}{Statistics}{ModelComponentBase} and its inherited classes).
+\end{enumerate}
+The implementation of the SEM has been turned to a contextual SEM in the sense
+where the evaluation of the membership parameters is conditioned to
+membership values of the spatial neighborhood of each pixels.
+
+\ifitkFullVersion
+\input{SEMModelEstimatorExample.tex}
+\fi
+
+%-------------------------------------------------------------------------------
+\subsection{Classification using Markov Random Fields}
+\label{sec:MarkovRandomField}
+
+Markov Random Fields are probabilistic models that use the statistical
+dependency between
+pixels in a neighborhood to infeer the value of a give pixel.
+
+\subsubsection{ITK framework}
+\label{sec:MarkovRandomFieldITK}
+The
+\subdoxygen{itk}{Statistics}{MRFImageFilter} uses the maximum a posteriori (MAP)
+estimates for modeling the MRF. The object traverses the data set and uses the
+model generated by the Mahalanobis distance classifier to get the the distance
+between each pixel in the data set to a set of known classes, updates the
+distances by evaluating the influence of its neighboring pixels (based on a MRF
+model) and finally, classifies each pixel to the class which has the minimum
+distance to that pixel (taking the neighborhood influence under consideration).
+The energy function minimization is done using the iterated conditional modes
+(ICM) algorithm \cite{Besag1986}.
+
+\ifitkFullVersion
+\input{ScalarImageMarkovRandomField1.tex}
+\fi
+
+\subsubsection{OTB framework}
+\label{sec:MarkovRandomFieldOTB}
+The ITK approach was considered not to be flexible enough for some
+remote sensing applications. Therefore, we decided to implement our
+own framework.
+\index{Markov}
+
+\begin{figure}[th]
+  \centering
+  \includegraphics[width=0.7\textwidth]{MarkovFramework.eps}
+  \itkcaption[OTB Markov Framework]{OTB Markov Framework.}
+  \label{fig:markovFramework}
+\end{figure}
+
+\index{Markov!Classification}
+\ifitkFullVersion
+\input{MarkovClassification1Example.tex}
+\fi
+
+\index{Markov!Classification}
+\ifitkFullVersion
+\input{MarkovClassification2Example.tex}
+\fi
+
+\index{Markov!Classification}
+\ifitkFullVersion
+\input{MarkovClassification3Example.tex}
+\fi
+
+\index{Markov!Regularization}
+\ifitkFullVersion
+\input{MarkovRegularizationExample.tex}
+\fi
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Fusion of Classification maps}
 
 \subsection{General approach of image fusion}
@@ -476,7 +574,7 @@ fuse several classification maps coming from different classification methods
 classification maps combines them in a more robust and precise one. Two methods are 
 available in the OTB: the majority voting and the Demspter Shafer framework.
 
-
+%-------------------------------------------------------------------------------
 \subsection{Majority voting}
 \subsubsection{General description}
 For each input pixel, the Majority Voting method consists in choosing the more 
@@ -489,7 +587,7 @@ the fused output image.
 \input{MajorityVotingFusionOfClassificationMapsExample.tex}
 \fi
 
-
+%-------------------------------------------------------------------------------
 \subsection{Dempster Shafer}
 
 \subsubsection{General description}
@@ -527,7 +625,7 @@ algorithm is available in the following OTB Wiki page:
 \fi
 
 
-
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Classification map regularization}
 
 %\subsection{Regularization by neighborhood-based majority voting}
diff --git a/Documentation/SoftwareGuide/Latex/ImageRegistration.tex b/Documentation/SoftwareGuide/Latex/ImageRegistration.tex
index 16d28a686326fc9d753fef6b56dcd0beb0d432f8..06c0f909466dab79bd10813ca06a140acfe0266c 100644
--- a/Documentation/SoftwareGuide/Latex/ImageRegistration.tex
+++ b/Documentation/SoftwareGuide/Latex/ImageRegistration.tex
@@ -502,9 +502,9 @@ describe the main characteristics of such transforms.
 
 %% The first case can be solved with a closed form solution when we are dealing
 %% with a Rigid or an Affine Transform~\cite{Horn1987}. This is done in ITK with
-%% the class \doxygen{LandmarkBasedTransformInitializer}. If we are interested in
+%% the class \doxygen{itk}{LandmarkBasedTransformInitializer}. If we are interested in
 %% a deformable Transformation then the problem can be solved with the
-%% \doxygen{KernelTransform} family of classes, which includes Thin Plate Splines
+%% \doxygen{itk}{KernelTransform} family of classes, which includes Thin Plate Splines
 %% among others~\cite{Rohr2001}. In both circumstances, the availability o f
 %% correspondences between the points make possible to apply a straight forward
 %% solution to the problem.
diff --git a/Documentation/SoftwareGuide/Latex/Optimizers.tex b/Documentation/SoftwareGuide/Latex/Optimizers.tex
index bc59c6845db754d067be0d22ba2a1e8dd2cee31b..eb865a56fb50a7f50b2f72c37e08191e1d007355 100644
--- a/Documentation/SoftwareGuide/Latex/Optimizers.tex
+++ b/Documentation/SoftwareGuide/Latex/Optimizers.tex
@@ -118,7 +118,7 @@ optimizer in \code{netlib}. Details on this optimizer can be found
 in~\cite{Byrd1995,Zhu1997} (\doxygen{itk}{LBFGSBOptimizer}).
 
 \item \textbf{One Plus One Evolutionary}: Strategy that simulates the
-biological evolution of a set of samples in the search space (\doxygen{itk}{OnePlusOneEvolutionaryOptimizer.}). Details on this optimizer can be
+biological evolution of a set of samples in the search space (\doxygen{itk}{OnePlusOneEvolutionaryOptimizer}). Details on this optimizer can be
 found in~\cite{Styner2000}.
 
 \item \textbf{Regular Step Gradient Descent}: Advances parameters in the
diff --git a/Documentation/SoftwareGuide/Latex/WriteAnApplication.tex b/Documentation/SoftwareGuide/Latex/WriteAnApplication.tex
index f019cba0774c7460ea73be2d85277e7296443fc0..b4029d13e7dce361ba0a43fb1e5c4306fd3d3cf0 100644
--- a/Documentation/SoftwareGuide/Latex/WriteAnApplication.tex
+++ b/Documentation/SoftwareGuide/Latex/WriteAnApplication.tex
@@ -30,7 +30,7 @@ divisions (see section \ref{sec:appParam}).
 
 \section{Architecture of the class}
 \label{sec:appArchitecture}
-Every application derive from the class \doxygen{otb}{Wrapper::Application}. An 
+Every application derive from the class \subdoxygen{otb}{Wrapper}{Application}. An 
 application can't be templated. It must contain the standard class typedefs and
 a call to the \code{OTB\_APPLICATION\_EXPORT} macro.
 
@@ -53,8 +53,8 @@ contain the following actions:
   \item Fill the documentation and give an example
   \item Declare all the parameters
   \item Define the documentation link:
-    \item for contrib application use SetDocLink("\textit{docLink}") function defined in \doxygen{otb}{Wrapper::Application}
-    \item for official application use SetOfficialDocLink() function defined in \doxygen{otb}{Wrapper::Application}
+    \item for contrib application use SetDocLink("\textit{docLink}") function defined in \subdoxygen{otb}{Wrapper}{Application}
+    \item for official application use SetOfficialDocLink() function defined in \subdoxygen{otb}{Wrapper}{Application}
 \end{itemize}
 
 
@@ -97,7 +97,7 @@ created and updated.
 \subsection{Parameters selection}
 \label{sec:appParam}
 In the new application framework, every input, output or parameter derive from 
-\doxygen{otb}{Wrapper::Parameter}. The application engine supplies the following 
+\subdoxygen{otb}{Wrapper}{Parameter}. The application engine supplies the following 
 types of parameters:
 \begin{itemize}
   \item \code{ParameterType\_Empty} : parameter without value (can be used to represent 
@@ -136,7 +136,7 @@ can be used to set a parameter optional or test if the user has modified the par
 are created in the \code{DoInit()} method, then the framework will set their value (either by parsing the 
 command line or reading the graphical user interface). The \code{DoExecute()} method is called when all 
 mandatory parameters have been given a value, which can be obtained with "Get" methods defined in 
-\doxygen{otb}{Wrapper::Application}. Parameters are set mandatory (or not) using \code{MandatoryOn(key)} method (\code{MandatoryOff(key)}).
+\subdoxygen{otb}{Wrapper}{Application}. Parameters are set mandatory (or not) using \code{MandatoryOn(key)} method (\code{MandatoryOff(key)}).
 
 Some functions are specific to numeric parameters, such as \code{SetMinimumParameterIntValue(key,value)}
 or \code{SetMaximumParameterFloatValue(key,value)}. By default, numeric parameters are treated as inputs.
@@ -158,7 +158,7 @@ that you want to chain in order to build a third application C. Rather than writ
 the code of A and B, you would like to re-use applications A and B. This plain example will be
 re-used in this section for explanations.
 
-A dedicated class \doxygen{otb}{Wrapper::CompositeApplication} has been added to create such applications.
+A dedicated class \subdoxygen{otb}{Wrapper}{CompositeApplication} has been added to create such applications.
 If you derive this class to implement application C, you will be able to create a composite application.
 
 \subsection{Creating internal applications}
diff --git a/Documentation/SoftwareGuide/SoftwareGuideConfiguration.tex.in b/Documentation/SoftwareGuide/SoftwareGuideConfiguration.tex.in
index 02868b264c65bf63aac1c3cb7c802772b1e72efc..22bd0cb1bad7d83d5e714fd11fbb266630a4a895 100644
--- a/Documentation/SoftwareGuide/SoftwareGuideConfiguration.tex.in
+++ b/Documentation/SoftwareGuide/SoftwareGuideConfiguration.tex.in
@@ -11,12 +11,17 @@
 }{
 \href{http://www.orfeo-toolbox.org/doxygen/class#1_1_1#2.html}{\code{#1::#2}}
 }{
-\href{http://www.itk.org/Doxygen46/html/class#1_1_1#2.html}{\code{#1::#2}}
+\href{http://www.itk.org/Doxygen/html/class#1_1_1#2.html}{\code{#1::#2}}
 }}
 
 % Define command to make reference to on-line Doxygen documentation
 \newcommand{\subdoxygen}[3]{
-\href{http://www.orfeo-toolbox.org/doxygen/class#1_1_1#2_1_1#3.html}{\code{#1::#2::#3}}}  
+\ifthenelse{ \equal{#1}{otb}
+}{
+\href{http://www.orfeo-toolbox.org/doxygen/class#1_1_1#2_1_1#3.html}{\code{#1::#2::#3}}
+}{
+\href{http://www.itk.org/Doxygen/html/class#1_1_1#2_1_1#3.html}{\code{#1::#2::#3}}
+}}
 
 % Define command for the standard comment introducing classes with similar functionalities
 \newcommand{\relatedClasses}{
diff --git a/Examples/Application/ApplicationExample.cxx b/Examples/Application/ApplicationExample.cxx
index 698c7d612219f770edd0e0fb7b533eef1c7a1260..007a204635ef56046dc0aa9fc4e11b2b43100619 100644
--- a/Examples/Application/ApplicationExample.cxx
+++ b/Examples/Application/ApplicationExample.cxx
@@ -28,7 +28,7 @@
 
 //  Software Guide : BeginLatex
 // This example illustrates the creation of an application.
-// A new application is a class, which derives from \doxygen{otb}{Wrapper::Application} class.
+// A new application is a class, which derives from \subdoxygen{otb}{Wrapper}{Application} class.
 // We start by including the needed header files.
 //
 //  Software Guide : EndLatex
@@ -147,7 +147,7 @@ private:
     // Software Guide : BeginLatex
     // Application parameters declaration is done using \code{AddParameter()} method.
     // \code{AddParameter()} requires Parameter type, its name and description.
-    // \doxygen{otb}{Wrapper::Application} class contains methods to set parameters characteristics.
+    // \subdoxygen{otb}{Wrapper}{Application} class contains methods to set parameters characteristics.
     // Software Guide : EndLatex
 
     //  Software Guide : BeginCodeSnippet
diff --git a/Examples/Classification/BayesianPluginClassifier.cxx b/Examples/Classification/BayesianPluginClassifier.cxx
index 792b68265f945c49827459db3e2919a47022c286..fa5d0c764af7bb3930a5d89dc867b57f61af03db 100644
--- a/Examples/Classification/BayesianPluginClassifier.cxx
+++ b/Examples/Classification/BayesianPluginClassifier.cxx
@@ -32,7 +32,7 @@
 // all the components of the classifier system and the data flow. This system
 // differs with the previous k-means clustering algorithms in several
 // ways. The biggest difference is that this classifier uses the
-// \subdoxygen{itk}{Statistics}{itkGaussianMembershipFunction} as membership functions
+// \subdoxygen{itk}{Statistics}{GaussianMembershipFunction} as membership functions
 // instead of the \subdoxygen{itk}{Statistics}{EuclideanDistanceMetric}. Since the
 // membership function is different, the membership function requires a
 // different set of parameters, mean vectors and covariance matrices. We
diff --git a/Examples/Classification/ExpectationMaximizationMixtureModelEstimator.cxx b/Examples/Classification/ExpectationMaximizationMixtureModelEstimator.cxx
index 3d16c589b8d645d41525513399908c83d4262e7b..63067f669fb86903b1f0f6cd3555b3681b24de9d 100644
--- a/Examples/Classification/ExpectationMaximizationMixtureModelEstimator.cxx
+++ b/Examples/Classification/ExpectationMaximizationMixtureModelEstimator.cxx
@@ -74,7 +74,7 @@
 // class assumes that such type of components.
 //
 // In the following example we use the \subdoxygen{itk}{Statistics}{ListSample} as
-// the sample (test and training). The \subdoxygen{itk}{Vector} is our measurement
+// the sample (test and training). The \doxygen{itk}{Vector} is our measurement
 // vector class. To store measurement vectors into two separate sample
 // container, we use the \subdoxygen{itk}{Statistics}{Subsample} objects.
 //
diff --git a/Examples/DataRepresentation/Image/ImageListExample.cxx b/Examples/DataRepresentation/Image/ImageListExample.cxx
index 81f21bc1f8ca4775d553b0085150d7cb6c682cff..d2f09626c149085c3bb2a39b845ec616d94f5daf 100644
--- a/Examples/DataRepresentation/Image/ImageListExample.cxx
+++ b/Examples/DataRepresentation/Image/ImageListExample.cxx
@@ -21,7 +21,7 @@
 
 //  Software Guide : BeginLatex
 //
-//  This example illustrates the use of the \subdoxygen{otb}{ImageList}
+//  This example illustrates the use of the \doxygen{otb}{ImageList}
 //  class. This class provides the functionnalities needed in order to
 //  integrate image lists as data objects into the OTB
 //  pipeline. Indeed, if a \code{std::list< ImageType >} was used, the
@@ -29,10 +29,10 @@
 //  effects.
 //
 //  In this example, we will only present the basic operations which
-//  can be applied on an \subdoxygen{otb}{ImageList} object.
+//  can be applied on an \doxygen{otb}{ImageList} object.
 //
 //  The first thing required to read an image from a file is to include
-//  the header file of the \subdoxygen{otb}{ImageFileReader} class.
+//  the header file of the \doxygen{otb}{ImageFileReader} class.
 //
 //  Software Guide : EndLatex
 
@@ -70,7 +70,7 @@ int main(int itkNotUsed(argc), char * argv[])
 // Software Guide : BeginLatex
 //
 // We can now define the type for the image list. The
-// \subdoxygen{otb}{ImageList} class is templated over the type of image
+// \doxygen{otb}{ImageList} class is templated over the type of image
 // contained in it. This means that all images in a list must have the
 // same type.
 //
@@ -146,7 +146,7 @@ int main(int itkNotUsed(argc), char * argv[])
 //
 // Also, iterator classes are defined in order to have an efficient
 // mean of moving through the list. Finally, the
-// \subdoxygen{otb}{ImageListToImageListFilter} is provided in order
+// \doxygen{otb}{ImageListToImageListFilter} is provided in order
 // to implement filter which operate on image lists and produce image lists.
 // Software Guide : EndLatex
 
diff --git a/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx b/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx
index 7e730b27f26eca50f284d3ece4ff3ddd516a926d..97fb63f85d0dc0fc792d737ffe35ef6c1c7a6d8e 100644
--- a/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx
+++ b/Examples/DisparityMap/FineRegistrationImageFilterExample.cxx
@@ -125,7 +125,7 @@ int main(int argc, char** argv)
 
   // Software Guide : BeginLatex
   //
-  // Now, we declare and instantiate the \doxygen{otb}{FineCorrelationImageFilter} which is going to perform the registration:
+  // Now, we declare and instantiate the \doxygen{otb}{FineRegistrationImageFilter} which is going to perform the registration:
   //
   // Software Guide : EndLatex
 
@@ -188,7 +188,7 @@ int main(int argc, char** argv)
 
   // Software Guide : BeginLatex
   //
-  // The default matching metric used by the \doxygen{FineRegistrationImageFilter} is standard correlation.
+  // The default matching metric used by the \doxygen{otb}{FineRegistrationImageFilter} is standard correlation.
   // However, we may also use any other image-to-image metric provided by ITK. For instance, here is how we
   // would use the \doxygen{itk}{MutualInformationImageToImageMetric} (do not forget to include the proper header).
   //
diff --git a/Examples/FeatureExtraction/ExtractSegmentsExample.cxx b/Examples/FeatureExtraction/ExtractSegmentsExample.cxx
index 7fc0b46b094373b680ec6ad2f236e49b105a5b33..4e4a3706a247275de236e6a6ff5b5959094af837 100644
--- a/Examples/FeatureExtraction/ExtractSegmentsExample.cxx
+++ b/Examples/FeatureExtraction/ExtractSegmentsExample.cxx
@@ -99,7 +99,7 @@ int main(int argc, char * argv[])
 
   //  Software Guide : BeginLatex
   //
-  //  An \doxygen{ImageFileReader} class is also instantiated in order to read
+  //  An \doxygen{otb}{ImageFileReader} class is also instantiated in order to read
   //  image data from a file.
   //
   //  Software Guide : EndLatex
@@ -110,7 +110,7 @@ int main(int argc, char * argv[])
 
   //  Software Guide : BeginLatex
   //
-  // An \doxygen{ImageFileWriter} is instantiated in order to write the
+  // An \doxygen{otb}{ImageFileWriter} is instantiated in order to write the
   // output image to a file.
   //
   //  Software Guide : EndLatex
diff --git a/Examples/FeatureExtraction/LineSegmentDetectorExample.cxx b/Examples/FeatureExtraction/LineSegmentDetectorExample.cxx
index c1277a2c47ad86cba315c0b512ffee30ac989528..0cfac191b53c3e14cba9ca8df3dfe8d0dbe1d781 100644
--- a/Examples/FeatureExtraction/LineSegmentDetectorExample.cxx
+++ b/Examples/FeatureExtraction/LineSegmentDetectorExample.cxx
@@ -156,7 +156,7 @@ int main(int argc, char * argv[])
   //
   // Before calling the \code{Update()} method of the writer in order to
   // trigger the pipeline execution, we call the
-  // \doxygen{GenerateOutputInformation()} of the reader, so the LSD
+  // \code{GenerateOutputInformation()} of the reader, so the LSD
   // filter gets the information about image size and spacing.
   //
   // Software Guide : EndLatex
diff --git a/Examples/FeatureExtraction/RightAngleDetectionExample.cxx b/Examples/FeatureExtraction/RightAngleDetectionExample.cxx
index 5d7fa92df2b736d780ef931c91bbdc0cc06d468d..04eaaf308ad0151cca3ff9ea8185cd2976fc0689 100644
--- a/Examples/FeatureExtraction/RightAngleDetectionExample.cxx
+++ b/Examples/FeatureExtraction/RightAngleDetectionExample.cxx
@@ -194,7 +194,7 @@ int main(int argc, char * argv[])
   //
   // Before calling the \code{Update()} method of the writer in order to
   // trigger the pipeline execution, we call the
-  // \doxygen{GenerateOutputInformation()} of the reader, so the
+  // \code{GenerateOutputInformation()} of the reader, so the
   // filter gets the information about image size and spacing.
   //
   // Software Guide : EndLatex
diff --git a/Examples/FeatureExtraction/TouziEdgeDetectorExample.cxx b/Examples/FeatureExtraction/TouziEdgeDetectorExample.cxx
index df67b6b9b6521668822c85527c028d17240d9ecb..a68817f104594edb28fe69144dcb8d26d05b84dc 100644
--- a/Examples/FeatureExtraction/TouziEdgeDetectorExample.cxx
+++ b/Examples/FeatureExtraction/TouziEdgeDetectorExample.cxx
@@ -105,7 +105,7 @@ int main(int argc, char * argv[])
 
   //  Software Guide : BeginLatex
   //
-  //  An \doxygen{ImageFileReader} class is also instantiated in order to read
+  //  An \doxygen{otb}{ImageFileReader} class is also instantiated in order to read
   //  image data from a file.
   //
   //  Software Guide : EndLatex
@@ -116,7 +116,7 @@ int main(int argc, char * argv[])
 
   //  Software Guide : BeginLatex
   //
-  // An \doxygen{ImageFileWriter} is instantiated in order to write the
+  // An \doxygen{otb}{ImageFileWriter} is instantiated in order to write the
   // output image to a file.
   //
   //  Software Guide : EndLatex
diff --git a/Examples/Iterators/ImageSliceIteratorWithIndex.cxx b/Examples/Iterators/ImageSliceIteratorWithIndex.cxx
index 1e4d4bfce4fb14b7ebb8f4e9a113ba3af8ce8258..1c7976d96f8a0f22e648a9a955d7866a66ba016c 100644
--- a/Examples/Iterators/ImageSliceIteratorWithIndex.cxx
+++ b/Examples/Iterators/ImageSliceIteratorWithIndex.cxx
@@ -24,8 +24,8 @@
 //
 // \index{Iterators!and image slices}
 //
-// The \doxygen{ImageSliceIteratorWithIndex} class is an extension of
-// \doxygen{ImageLinearIteratorWithIndex} from iteration along lines to
+// The \doxygen{itk}{ImageSliceIteratorWithIndex} class is an extension of
+// \doxygen{itk}{ImageLinearIteratorWithIndex} from iteration along lines to
 // iteration along both lines \emph{and planes} in an image.
 // A \emph{slice} is a 2D
 // plane spanned by two vectors pointing along orthogonal coordinate axes.  The
diff --git a/Examples/Iterators/NeighborhoodIterators5.cxx b/Examples/Iterators/NeighborhoodIterators5.cxx
index f3792036a1c160923ec3ae8823a6606e4d70792b..b182309bf8f2845a57cdcb6ec2fe8429823c8333 100644
--- a/Examples/Iterators/NeighborhoodIterators5.cxx
+++ b/Examples/Iterators/NeighborhoodIterators5.cxx
@@ -46,9 +46,9 @@
 // 2, stride = 3, end = 8)}, that represents the neighborhood offsets $(1,
 // -1)$, $(1, 0)$, $(1, 1)$ (see Figure~\ref{fig:NeighborhoodIteratorFig2}). If we
 // pass this slice as an extra argument to the
-// \doxygen{NeighborhoodInnerProduct} function, then the inner product is taken
+// \doxygen{itk}{NeighborhoodInnerProduct} function, then the inner product is taken
 // only along that slice.  This ``sliced'' inner product with a 1D
-// \doxygen{DerivativeOperator} gives the desired derivative.
+// \doxygen{itk}{DerivativeOperator} gives the desired derivative.
 //
 // The previous separable Gaussian filtering example can be rewritten using
 // slices and slice-based inner products.  In general, slice-based processing
@@ -57,7 +57,7 @@
 // Section~\ref{sec:NeighborhoodExample4} becomes impractical or inefficient.
 // Good examples of slice-based neighborhood processing can be found in any of
 // the ND anisotropic diffusion function objects, such as
-// \doxygen{CurvatureNDAnisotropicDiffusionFunction}.
+// \doxygen{itk}{CurvatureNDAnisotropicDiffusionFunction}.
 //
 // Software Guide : EndLatex
 
diff --git a/Examples/Learning/SEMModelEstimatorExample.cxx b/Examples/Learning/SEMModelEstimatorExample.cxx
index e13d2e659d88bf498447e242405fcb13d13af18e..65ec4960477aef75eff45c0653e45cc550a4d71f 100644
--- a/Examples/Learning/SEMModelEstimatorExample.cxx
+++ b/Examples/Learning/SEMModelEstimatorExample.cxx
@@ -32,11 +32,11 @@
 // \doxygen{otb}{SEMClassifier}. This class performs a stochastic version
 // of the EM algorithm, but instead of inheriting from
 // \doxygen{itk}{ExpectationMaximizationMixtureModelEstimator}, we chose to
-// inherit from \subdoxygen{itk}{Statistics}{ListSample< TSample >},
+// inherit from \subdoxygen{itk}{Statistics}{ListSample},
 // in the same way as \doxygen{otb}{SVMClassifier}.
 //
 // The program begins with \doxygen{otb}{VectorImage} and outputs
-// \doxygen{itb}{Image}. Then appropriate header files have to be included:
+// \doxygen{otb}{Image}. Then appropriate header files have to be included:
 //
 // Software Guide : EndLatex
 
@@ -144,7 +144,7 @@ int main(int argc, char * argv[])
 // When an initial segmentation is available, the classifier may use it
 // as image (of type \code{OutputImageType}) or as a
 // \doxygen{itk}{SampleClassifier} result (of type
-// \subdoxygen{itk}{Statistics}{MembershipSample< SampleType >}).
+// \subdoxygen{itk}{Statistics}{MembershipSample}).
 //  Software Guide : EndLatex
 
 //  Software Guide : BeginCodeSnippet
@@ -205,7 +205,7 @@ int main(int argc, char * argv[])
 //  Software Guide : BeginLatex
 //
 //  The segmentation may outputs a result of type
-// \subdoxygen{itk}{Statistics}{MembershipSample< SampleType >} as it is the
+// \subdoxygen{itk}{Statistics}{MembershipSample} as it is the
 // case for the \doxygen{otb}{SVMClassifier}. But when using
 // \code{GetOutputImage} the output is directly an Image.
 //
diff --git a/Examples/Learning/SOMClassifierExample.cxx b/Examples/Learning/SOMClassifierExample.cxx
index d1681051e359e773286fc129d3a833cd991d4c94..cbd6f2d31e3643f431dd1c565165d6f3d77ee3a0 100644
--- a/Examples/Learning/SOMClassifierExample.cxx
+++ b/Examples/Learning/SOMClassifierExample.cxx
@@ -77,7 +77,7 @@ int main(int argc, char* argv[])
 // As for the SOM learning step, we must define the types for the
 // \code{otb::SOMMap}, and therefore, also for the distance to be
 // used. We will also define the type for the SOM reader, which is
-// actually an \subdoxygen{otb}{ImageFileReader} which the appropriate
+// actually an \doxygen{otb}{ImageFileReader} which the appropriate
 // image type.
 //
 //  Software Guide : EndLatex
@@ -94,7 +94,7 @@ int main(int argc, char* argv[])
 //  Software Guide : BeginLatex
 //
 //  The classification will be performed by the
-//  \subdoxygen{otb}{SOMClassifier}, which, as most of the
+//  \doxygen{otb}{SOMClassifier}, which, as most of the
 //  classifiers, works on
 //  \subdoxygen{itk}{Statistics}{ListSample}s. In order to be able
 //  to perform an image classification, we will need to use the
@@ -218,7 +218,7 @@ int main(int argc, char* argv[])
 //
 //  Software Guide : BeginLatex
 //
-//  We also declare an \subdoxygen{itk}{ImageRegionIterator} in order
+//  We also declare an \doxygen{itk}{ImageRegionIterator} in order
 //  to fill the output image with the class labels.
 //
 //  Software Guide : EndLatex
diff --git a/Examples/Learning/SOMExample.cxx b/Examples/Learning/SOMExample.cxx
index 9f9d164e942f2c0a5af26d40dd295e75a84cbcf7..814214c4935de5c9701917f9a993422cdf793fc2 100644
--- a/Examples/Learning/SOMExample.cxx
+++ b/Examples/Learning/SOMExample.cxx
@@ -118,7 +118,7 @@ int main(int itkNotUsed(argc), char* argv[])
 //
 //  Software Guide : BeginLatex
 //
-// We can now define the type for the map. The \subdoxygen{otb}{SOMMap}
+// We can now define the type for the map. The \doxygen{otb}{SOMMap}
 // class is templated over the neuron type -- \code{PixelType} here
 // --, the distance type and the number of dimensions. Note that the
 // number of dimensions of the map could be different from the one of
diff --git a/Examples/Segmentation/VectorConfidenceConnected.cxx b/Examples/Segmentation/VectorConfidenceConnected.cxx
index 357577cb68e2c0577b09acd4ae9c97f92489e397..3e4fa502838288f5065efb5378c47fcb0ac46ed7 100644
--- a/Examples/Segmentation/VectorConfidenceConnected.cxx
+++ b/Examples/Segmentation/VectorConfidenceConnected.cxx
@@ -42,12 +42,13 @@
 //  This example illustrates the use of the confidence connected concept
 //  applied to images with vector pixel types. The confidence connected
 //  algorithm is implemented for vector images in the class
-//  \doxygen{VectorConfidenceConnected}. The basic difference between the
+//  \doxygen{itk}{VectorConfidenceConnectedImageFilter}. The basic difference
+//  between the
 //  scalar and vector version is that the vector version uses the covariance
 //  matrix instead of a variance, and a vector mean instead of a scalar mean.
 //  The membership of a vector pixel value to the region is measured using the
 //  Mahalanobis distance as implemented in the class
-//  \subdoxygen{Statistics}{MahalanobisDistanceThresholdImageFunction}.
+//  \subdoxygen{itk}{Statistics}{MahalanobisDistanceThresholdImageFunction}.
 //
 //  Software Guide : EndLatex
 
@@ -108,7 +109,7 @@ int main( int argc, char *argv[] )
   //  Software Guide : BeginLatex
   //
   //  We now declare the type of the region growing filter. In this case it
-  //  is the \doxygen{VectorConfidenceConnectedImageFilter}.
+  //  is the \doxygen{itk}{VectorConfidenceConnectedImageFilter}.
   //
   //  Software Guide : EndLatex
 
@@ -211,7 +212,7 @@ int main( int argc, char *argv[] )
   //  anatomical structure to be segmented. A small neighborhood around the
   //  seed point will be used to compute the initial mean and standard
   //  deviation for the inclusion criterion. The seed is passed in the form
-  //  of a \doxygen{Index} to the \code{SetSeed()} method.
+  //  of a \doxygen{itk}{Index} to the \code{SetSeed()} method.
   //
   //  \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetSeed()}
   //  \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetInitialNeighborhoodRadius()}
diff --git a/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx b/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
index fa7886b540351b0d095f0ae64970943b4e09c799..e61faf0608761bb35f9e6fa8a105b6232b035c9d 100644
--- a/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
+++ b/Examples/Simulation/LAIAndPROSAILToSensorResponse.cxx
@@ -422,7 +422,7 @@ protected:
 // Software Guide : BeginLatex
 //
 // \code{TernaryFunctorImageFilterWithNBands} class is defined here.
-// This class inherits form \doxygen{itk::TernaryFunctorImageFilter} with additional nuber of band parameters.
+// This class inherits form \doxygen{itk}{TernaryFunctorImageFilter} with additional nuber of band parameters.
 // It's implementation is done to process Label, LAI, and mask image with Simulation functor.
 // Software Guide : EndLatex
 
@@ -595,7 +595,7 @@ int main(int argc, char *argv[])
   // Software Guide : BeginLatex
   //
   // Acquisition parameters are loaded using text file. A detailed definition of acquisition parameters can
-  // be found in class \doxygen{SailModel}.
+  // be found in class \doxygen{otb}{SailModel}.
   //
   // Software Guide : EndLatex
 
diff --git a/Modules/Adapters/GdalAdapters/include/otbOGRVersionProxy.h b/Modules/Adapters/GdalAdapters/include/otbOGRVersionProxy.h
index 12c94cd02c047bc2034a67cefd64c2b70fbd8227..7fdc308413d2a912eba471b90fe74576e1ef5310 100644
--- a/Modules/Adapters/GdalAdapters/include/otbOGRVersionProxy.h
+++ b/Modules/Adapters/GdalAdapters/include/otbOGRVersionProxy.h
@@ -44,6 +44,8 @@ class OGRDataSource;
 class OGRSFDriver;
 #endif
 
+class OGRFeature;
+
 #include "OTBGdalAdaptersExport.h"
 
 namespace otb
@@ -212,6 +214,15 @@ OTBGdalAdapters_EXPORT bool IsOFTInteger64(OGRFieldType type);
   OTBGdalAdapters_EXPORT
   std::vector<std::string> GetAvailableDriversAsStringVector();
 
+  /**
+   * Returns true if the field 'index' is set and not-null in the given feature
+   *
+   * Before gdal 2.2, it calls OGRFeature::IsFieldSet().
+   * After gdal 2.2, it calls OGRFeature::IsFieldSetAndNotNull()
+   */
+   OTBGdalAdapters_EXPORT
+   bool IsFieldSetAndNotNull(OGRFeature *feat, int index);
+
 }
 }
 } // end namespace otb
diff --git a/Modules/Adapters/GdalAdapters/src/CMakeLists.txt b/Modules/Adapters/GdalAdapters/src/CMakeLists.txt
index 95a01673319b92719b860e2d4da2ed755d7b1ca1..4ba50ff1e286f05842703510931bffec1d5f0f21 100644
--- a/Modules/Adapters/GdalAdapters/src/CMakeLists.txt
+++ b/Modules/Adapters/GdalAdapters/src/CMakeLists.txt
@@ -28,14 +28,9 @@ set(OTBGdalAdapters_SRC
   otbOGRDriversInit.cxx
   otbGeometriesToGeometriesFilter.cxx
   otbOGRDataSourceWrapper.cxx
+  otbOGRVersionProxy.cxx
   )
 
-if(OTB_USE_GDAL_20)
-  set(OTBGdalAdapters_SRC ${OTBGdalAdapters_SRC} otbOGRVersionProxy2x.cxx)
-else(Otb_use_gdal_20)
-  set(OTBGdalAdapters_SRC ${OTBGdalAdapters_SRC} otbOGRVersionProxy1x.cxx)
-endif(OTB_USE_GDAL_20)
-
 add_library(OTBGdalAdapters ${OTBGdalAdapters_SRC})
 target_link_libraries(OTBGdalAdapters 
   ${OTBBoost_LIBRARIES}
diff --git a/Modules/Adapters/GdalAdapters/src/otbOGRFieldWrapper.cxx b/Modules/Adapters/GdalAdapters/src/otbOGRFieldWrapper.cxx
index 3b54c06c60d1041f5837f1c46a7b22bb4387713f..49f95f053546c6f59190ef88ae6d28cee0f19110 100644
--- a/Modules/Adapters/GdalAdapters/src/otbOGRFieldWrapper.cxx
+++ b/Modules/Adapters/GdalAdapters/src/otbOGRFieldWrapper.cxx
@@ -37,6 +37,7 @@
 #endif
 #include "otbOGRFeatureWrapper.h"
 #include "otbJoinContainer.h"
+#include "otbOGRVersionProxy.h"
 #include <boost/array.hpp>
 /*===========================================================================*/
 /*===========================[ Static Assertions ]===========================*/
@@ -166,7 +167,7 @@ std::ostream & otb::ogr::Field::UncheckedPrintSelf(
 
 bool otb::ogr::Field::UncheckedHasBeenSet() const
 {
-  return m_Feature->IsFieldSet(m_index);
+  return otb::ogr::version_proxy::IsFieldSetAndNotNull(m_Feature.get(), m_index);
 }
 
 void otb::ogr::Field::UncheckedUnset() const
diff --git a/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy2x.cxx b/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy.cxx
similarity index 62%
rename from Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy2x.cxx
rename to Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy.cxx
index 2ca46ae46a00029da877f3b16ef6e03739fea4fc..22b7a612ca3f7f557eeed7abe2da3c2e1d047fe9 100644
--- a/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy2x.cxx
+++ b/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy.cxx
@@ -20,15 +20,26 @@
 
 #include "otbOGRVersionProxy.h"
 
+#include "itkMacro.h"
+
 #if defined(__GNUC__) || defined(__clang__)
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wshadow"
+#if GDAL_VERSION_NUM<2000000
+#include "ogrsf_frmts.h"
+#else
 #include "gdal_priv.h"
+#endif
+#include "ogr_feature.h"
 #pragma GCC diagnostic pop
 #else
+#if GDAL_VERSION_NUM<2000000
+#include "ogrsf_frmts.h"
+#else
 #include "gdal_priv.h"
 #endif
-
+#include "ogr_feature.h"
+#endif // __GNUC__ || __clang__
 
 namespace otb
 {
@@ -37,24 +48,48 @@ namespace ogr
 namespace version_proxy
 {
 
+/*-------------------------[GDAL v2 API change]-------------------------------*/
 OTBGdalAdapters_EXPORT bool IsOFTInteger64(OGRFieldType type)
 {
+#if GDAL_VERSION_NUM<2000000
+  (void)type;
+  return false;
+#else
   return type == OFTInteger64;
+#endif
 }
 
+
 GDALDatasetType * Open(const char * filename, bool readOnly)
 {
+#if GDAL_VERSION_NUM<2000000
+  return OGRSFDriverRegistrar::Open(filename,!readOnly);
+#else
   return (GDALDatasetType *)GDALOpenEx(filename, (readOnly? GDAL_OF_READONLY : GDAL_OF_UPDATE) | GDAL_OF_VECTOR,NULL,NULL,NULL);
+#endif
 }
 
 void Close(GDALDatasetType * dataset)
 {
+#if GDAL_VERSION_NUM<2000000
+  OGRDataSource::DestroyDataSource(dataset);
+#else
   GDALClose(dataset);
+#endif
 }
 
 GDALDatasetType * Create(GDALDriverType * driver, const char * name)
 {
+#if GDAL_VERSION_NUM<2000000
+  GDALDatasetType * ds = driver->CreateDataSource(name);
+
+  if(ds)
+    ds->SetDriver(driver);
+
+  return ds;
+#else
   return driver->Create(name,0,0,0,GDT_Unknown,NULL);
+#endif
 }
 
 bool Delete(const char * name)
@@ -67,31 +102,50 @@ bool Delete(const char * name)
     poDriver = poDS->GetDriver();
     Close(poDS);
     }
-
+#if GDAL_VERSION_NUM<2000000
+  if(poDriver && poDriver->TestCapability(ODrCDeleteDataSource))
+    {
+    OGRErr ret = poDriver->DeleteDataSource(name);
+    return (ret == OGRERR_NONE);
+    }
+#else
   if(poDriver)
     {
     OGRErr ret = poDriver->Delete(name);
-
     return (ret == OGRERR_NONE);
     }
+#endif
   return false;
 }
 
 GDALDriverType *  GetDriverByName(const char * name)
 {
+#if GDAL_VERSION_NUM<2000000
+  return OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(name);
+#else
   return GetGDALDriverManager()->GetDriverByName(name);
+#endif
 }
 
 std::string GetDatasetClassName()
 {
+#if GDAL_VERSION_NUM<2000000
+  return std::string("OGRDataSource");
+#else
   return std::string("GDALDataset");
+#endif
 }
 
 std::string GetDriverClassName()
 {
+#if GDAL_VERSION_NUM<2000000
+  return std::string("OGRSFDriver");
+#else
   return std::string("GDALDriver");
+#endif
 }
 
+#if GDAL_VERSION_NUM>=2000000
 namespace raii
 {
 // This class is used in the next function, so as to prevent any
@@ -118,11 +172,14 @@ private:
   char ** m_P;
 };
 }
+#endif
 
 std::vector<std::string> GetFileListAsStringVector(GDALDatasetType * dataset)
 {
   std::vector<std::string> ret;
-
+#if GDAL_VERSION_NUM<2000000
+  ret.push_back(std::string(dataset->GetName()));
+#else
   raii::CharPPCapsule capsule(dataset->GetFileList());
 
   std::string files_str="";
@@ -136,35 +193,62 @@ std::vector<std::string> GetFileListAsStringVector(GDALDatasetType * dataset)
       ++i;
       }
     }
+#endif
   return ret;
 }
 
 bool SyncToDisk(GDALDatasetType * dataset)
 {
+#if GDAL_VERSION_NUM<2000000
+  const OGRErr res= dataset->SyncToDisk();
+  return (res == OGRERR_NONE);
+#else
   dataset->FlushCache();
-
   return true;
+#endif
 }
 
 std::vector<std::string> GetAvailableDriversAsStringVector()
 {
   std::vector<std::string> ret;
+#if GDAL_VERSION_NUM<2000000
+  int nbDrivers = OGRSFDriverRegistrar::GetRegistrar()->GetDriverCount();
 
+  for(int i = 0; i < nbDrivers;++i)
+    {
+    ret.push_back(OGRSFDriverRegistrar::GetRegistrar()->GetDriver(i)->GetName());
+    }
+#else
   int nbDrivers = GetGDALDriverManager()->GetDriverCount();
 
   for(int i = 0; i < nbDrivers;++i)
     {
     ret.push_back(GDALGetDriverShortName(GetGDALDriverManager()->GetDriver(i)));
     }
-
+#endif
   return ret;
 }
 
 std::string GetDriverNameFromDataSource(const GDALDatasetType * ds)
 {
+#if GDAL_VERSION_NUM<2000000
+  return std::string(const_cast<GDALDatasetType *>(ds)->GetDriver()->GetName());
+#else
   return std::string(const_cast<GDALDatasetType *>(ds)->GetDriverName());
+#endif
+}
+
+/*----------------------[GDAL 2.2 change on IsFieldSet()]---------------------*/
+bool IsFieldSetAndNotNull(OGRFeature *feat, int index)
+{
+#if GDAL_VERSION_NUM<2020000
+  return feat->IsFieldSet(index);
+#else
+  return feat->IsFieldSetAndNotNull(index);
+#endif
 }
 
 }
 }
 } // end namespace
+
diff --git a/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy1x.cxx b/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy1x.cxx
deleted file mode 100644
index 47c915342349732a594d0a5360c1ecd8bfe1ae5e..0000000000000000000000000000000000000000
--- a/Modules/Adapters/GdalAdapters/src/otbOGRVersionProxy1x.cxx
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
- *
- * This file is part of Orfeo Toolbox
- *
- *     https://www.orfeo-toolbox.org/
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "otbOGRVersionProxy.h"
-
-#include "itkMacro.h"
-
-#if defined(__GNUC__) || defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wshadow"
-#include "ogrsf_frmts.h"
-#pragma GCC diagnostic pop
-#else
-#include "ogrsf_frmts.h"
-#endif
-
-namespace otb
-{
-namespace ogr
-{
-namespace version_proxy
-{
-
-OTBGdalAdapters_EXPORT bool IsOFTInteger64(OGRFieldType itkNotUsed(type))
-{
-  return false;
-}
-
-
-GDALDatasetType * Open(const char * filename, bool readOnly)
-{
-  return OGRSFDriverRegistrar::Open(filename,!readOnly);
-}
-
-void Close(GDALDatasetType * dataset)
-{
-  OGRDataSource::DestroyDataSource(dataset);
-}
-
-GDALDatasetType * Create(GDALDriverType * driver, const char * name)
-{
-  GDALDatasetType * ds = driver->CreateDataSource(name);
-
-  if(ds)
-    ds->SetDriver(driver);
-
-  return ds;
-}
-
-bool Delete(const char * name)
-{
-  // Open dataset
-  GDALDatasetType * poDS = Open(name,false);
-  GDALDriverType * poDriver = ITK_NULLPTR;
-  if(poDS)
-    {
-    poDriver = poDS->GetDriver();
-    Close(poDS);
-    }
-
-  if(poDriver && poDriver->TestCapability(ODrCDeleteDataSource))
-    {
-
-    OGRErr ret = poDriver->DeleteDataSource(name);
-    return (ret == OGRERR_NONE);
-    }
-
-  return false;
-}
-
-GDALDriverType *  GetDriverByName(const char * name)
-{
-  return OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(name);
-}
-
-std::string GetDatasetClassName()
-{
-  return std::string("OGRDataSource");
-}
-
-std::string GetDriverClassName()
-{
-  return std::string("OGRSFDriver");
-}
-
-std::vector<std::string> GetFileListAsStringVector(GDALDatasetType * dataset)
-{
-  std::vector<std::string> ret;
-
-  ret.push_back(std::string(dataset->GetName()));
-
-  return ret;
-}
-
-bool SyncToDisk(GDALDatasetType * dataset)
-{
-  const OGRErr res= dataset->SyncToDisk();
-
-  return (res == OGRERR_NONE);
-}
-
-std::vector<std::string> GetAvailableDriversAsStringVector()
-{
-  std::vector<std::string> ret;
-
-  int nbDrivers = OGRSFDriverRegistrar::GetRegistrar()->GetDriverCount();
-
-  for(int i = 0; i < nbDrivers;++i)
-    {
-    ret.push_back(OGRSFDriverRegistrar::GetRegistrar()->GetDriver(i)->GetName());
-    }
-
-  return ret;
-}
-
-std::string GetDriverNameFromDataSource(const GDALDatasetType * ds)
-{
-  return std::string(const_cast<GDALDatasetType *>(ds)->GetDriver()->GetName());
-}
-
-}
-}
-} // end namespace
diff --git a/Modules/Applications/AppChangeDetection/app/otbMultivariateAlterationDetector.cxx b/Modules/Applications/AppChangeDetection/app/otbMultivariateAlterationDetector.cxx
index c54940788ca5b0684e436f635d02fe07d92346f4..668930e92202047b758e168f77eb37f22c381620 100644
--- a/Modules/Applications/AppChangeDetection/app/otbMultivariateAlterationDetector.cxx
+++ b/Modules/Applications/AppChangeDetection/app/otbMultivariateAlterationDetector.cxx
@@ -46,58 +46,59 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("MultivariateAlterationDetector");
-    SetDescription("Multivariate Alteration Detector");
+    SetDescription("Change detection by Multivariate Alteration Detector (MAD) algorithm");
 
     // Documentation
-    SetDocName("Multivariate alteration detector");
-    SetDocLongDescription("This application detects change between two given images.");
-    SetDocLimitations("None");
+    SetDocName("Multivariate Alteration Detector");
+    SetDocLongDescription("This application performs change detection between two multispectral"
+                          " images using the Multivariate Alteration Detector (MAD) [1]"
+                          " algorithm.\n\n"
+                          "The MAD algorithm produces a set of N change maps (where N is the"
+                          " maximum number of bands in first and second input images), with the"
+                          " following properties:\n"
+                          " - Change maps are differences of a pair of linear combinations of "
+                          " bands from image 1 and bands from image 2 chosen to maximize the "
+                          " correlation, \n"
+                          " - Each change map is orthogonal to the others.\n"
+                          " \n"
+                          "This is a statistical method which can handle different modalities"
+                          " and even different bands and number of bands between images. \n"
+                          " \n"
+                          "The application will output all change maps into a single multiband"
+                          " image. If numbers of bands in image 1 and 2 are equal, then change"
+                          " maps are sorted by increasing correlation. If number of bands is"
+                          " different, the change maps are sorted by decreasing correlation. \n"
+                          " \n"
+                          "The application will also print the following information:\n"
+                          "- Mean1 and Mean2 which are the mean values of bands for both input"
+                          " images,\n"
+                          "- V1 and V2 which are the two linear transform that are applied to"
+                          " input image 1 and input image 2 to build the change map,\n"
+                          "- Rho, the vector of correlation associated to each change map.\n"
+                          " \n"
+                          "The OTB filter used in this application has been implemented from the"
+                          " Matlab code kindly made available by the authors here [2]. Both cases"
+                          " (same and different number of bands) have been validated"
+                          " by comparing the output image to the output produced by the Matlab "
+                          " code, and the reference images for testing have been generated from "
+                          " the Matlab code using Octave." );
+
+                          
+    SetDocLimitations("Input images 1 and 2 should share exactly the same origin, spacing, size, and projection if any.");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" This filter implements the Multivariate Alteration Detector, based "
-                  " on the following work: \n"
-                  " A. A. Nielsen and K. Conradsen, Multivariate alteration detection"
-                  " (mad) in multispectral, bi-temporal image data: a new approach to"
-                  " change detection studies, Remote Sens. Environ., vol. 64,"
-                  " pp. 1-19, (1998) \n"
-                  " \n"
-                  " Multivariate Alteration Detector takes two images as inputs and "
-                  " produce a set of N change maps as a VectorImage (where N is the "
-                  " maximum of number of bands in first and second image) with the "
-                  " following properties: \n"
-                  " - Change maps are differences of a pair of linear combinations of "
-                  " bands from image 1 and bands from image 2 chosen to maximize the "
-                  " correlation. \n"
-                  " - Each change map is orthogonal to the others. \n"
-                  " \n"
-                  " This is a statistical method which can handle different modalities "
-                  " and even different bands and number of bands between images. \n"
-                  " \n"
-                  " If numbers of bands in image 1 and 2 are equal, then change maps "
-                  " are sorted by increasing correlation. If number of bands is "
-                  " different, the change maps are sorted by decreasing correlation. \n"
-                  " \n"
-                  " The GetV1() and GetV2() methods allow retrieving the linear "
-                  " combinations used to generate the Mad change maps as a vnl_matrix of "
-                  " double, and the GetRho() method allows retrieving the correlation "
-                  " associated to each Mad change maps as a vnl_vector. \n"
-                  " \n"
-                  " This filter has been implemented from the Matlab code kindly made "
-                  " available by the authors here: \n"
-                  " http://www2.imm.dtu.dk/~aa/software.html \n"
-                  " \n"
-                  " Both cases (same and different number of bands) have been validated "
-                  " by comparing the output image to the output produced by the Matlab "
-                  " code, and the reference images for testing have been generated from "
-                  " the Matlab code using Octave." );
-
-    AddDocTag(Tags::FeatureExtraction);
+    SetDocSeeAlso("[1] Nielsen, A. A., & Conradsen, K. (1997). Multivariate alteration"
+                  "detection (MAD) in multispectral, bi-temporal image data: A new"
+                  "approach to change detection studies.\n"
+                  "[2] http://www2.imm.dtu.dk/~aa/software.html");
+
+    AddDocTag(Tags::ChangeDetection);
 
     AddParameter(ParameterType_InputImage,  "in1", "Input Image 1");
-    SetParameterDescription("in1","Image which describe initial state of the scene.");
+    SetParameterDescription("in1","Multiband image of the scene before perturbations");
     AddParameter(ParameterType_InputImage,  "in2", "Input Image 2");
-    SetParameterDescription("in2","Image which describe scene after perturbations.");
+    SetParameterDescription("in2","Mutliband image of the scene after perturbations.");
     AddParameter(ParameterType_OutputImage, "out", "Change Map");
-    SetParameterDescription("out","Image of detected changes.");
+    SetParameterDescription("out","Multiband image containing change maps. Each map will be in range [-1,1], so a floating point output type is advised.");
 
     AddRAMParameter();
 
diff --git a/Modules/Applications/AppClassification/app/CMakeLists.txt b/Modules/Applications/AppClassification/app/CMakeLists.txt
index 881f0b600f27b359744915784e84d334885d984f..cfa104e5902c882cb2634b2f9269b8f86b54bd14 100644
--- a/Modules/Applications/AppClassification/app/CMakeLists.txt
+++ b/Modules/Applications/AppClassification/app/CMakeLists.txt
@@ -149,3 +149,6 @@ otb_create_application(
   NAME           VectorClassifier
   SOURCES        otbVectorClassifier.cxx
   LINK_LIBRARIES ${${otb-module}_LIBRARIES})
+
+# Mantis-1427 : temporary fix
+add_dependencies(${otb-module}-all otbapp_ImageEnvelope)
diff --git a/Modules/Applications/AppClassification/app/otbComputeImagesStatistics.cxx b/Modules/Applications/AppClassification/app/otbComputeImagesStatistics.cxx
index fbb8bef4b1d27b6b4ea6739a02d018f6e4f8d745..0956eb7a0068264402c218687efd3c89feacfc76 100644
--- a/Modules/Applications/AppClassification/app/otbComputeImagesStatistics.cxx
+++ b/Modules/Applications/AppClassification/app/otbComputeImagesStatistics.cxx
@@ -48,12 +48,19 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("ComputeImagesStatistics");
-    SetDescription("Computes global mean and standard deviation for each band from a set of images and optionally saves the results in an XML file.");
     SetDocName("Compute Images second order statistics");
-    SetDocLongDescription("This application computes a global mean and standard deviation for each band of a set of images and optionally saves the results in an XML file. The output XML is intended to be used an input for the TrainImagesClassifier application to normalize samples before learning.");
-    SetDocLimitations("Each image of the set must contain the same bands as the others (i.e. same types, in the same order).");
+    SetDescription("Computes global mean and standard deviation for each band "
+      "from a set of images and optionally saves the results in an XML file.");
+    SetDocLongDescription("This application computes a global mean and standard deviation "
+      "for each band of a set of images and optionally saves the results in an XML file."
+      " The output XML is intended to be used an input "
+      "for the TrainImagesClassifier application to normalize samples before learning. "
+      "You can also normalize the image with the XML file in the ImageClassifier application.");
+
+    SetDocLimitations("Each image of the set must contain the same bands as the others"
+                      " (i.e. same types, in the same order).");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso("Documentation of the TrainImagesClassifier application.");
+    SetDocSeeAlso("Documentation of the TrainImagesClassifier and ImageClassifier application.");
 
     AddDocTag(Tags::Learning);
     AddDocTag(Tags::Analysis);
diff --git a/Modules/Applications/AppClassification/app/otbFusionOfClassifications.cxx b/Modules/Applications/AppClassification/app/otbFusionOfClassifications.cxx
index 15c821e9b090661314c066b678fa1651a61886bf..b31ae21c16d927de64135bdd47b1f07ebb9d595e 100644
--- a/Modules/Applications/AppClassification/app/otbFusionOfClassifications.cxx
+++ b/Modules/Applications/AppClassification/app/otbFusionOfClassifications.cxx
@@ -108,7 +108,7 @@ private:
         "confusion matrix file for the Dempster Shafer fusion.\n"
         "  - Input pixels with the NODATA label are not handled in the fusion of classification maps. Moreover, pixels for which all the input classifiers are set to NODATA "
         "keep this value in the output fused image.\n"
-        "  - In case of number of votes equality, the UNDECIDED label is attributed to the pixel.\n");
+        "  - In case of number of votes equality, the UNDECIDED label is attributed to the pixel.");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso("ImageClassifier application");
diff --git a/Modules/Applications/AppClassification/app/otbImageClassifier.cxx b/Modules/Applications/AppClassification/app/otbImageClassifier.cxx
index 47ba61e9b705da15b83794d55ecb3be5284a569c..1f94d2714355e37db5137cfd85d3de72b3927e57 100644
--- a/Modules/Applications/AppClassification/app/otbImageClassifier.cxx
+++ b/Modules/Applications/AppClassification/app/otbImageClassifier.cxx
@@ -50,7 +50,8 @@ public:
   itkTypeMacro(ImageClassifier, otb::Application);
 
   /** Filters typedef */
-  typedef UInt16ImageType                                                                      OutputImageType;
+  //typedef UInt16ImageType                                                                    OutputImageType;
+  typedef Int32ImageType                                                                       OutputImageType;
   typedef UInt8ImageType                                                                       MaskImageType;
   typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType>                   MeasurementType;
   typedef otb::StatisticsXMLFileReader<MeasurementType>                                        StatisticsReader;
@@ -79,7 +80,7 @@ private:
 
     // Documentation
     SetDocName("Image Classification");
-    SetDocLongDescription("This application performs an image classification based on a model file produced by the TrainImagesClassifier application. Pixels of the output image will contain the class labels decided by the classifier (maximal class label = 65535). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be classified. The remaining of pixels will be given the label 0 in the output image.");
+    SetDocLongDescription("This application performs an image classification based on a model file produced by the TrainImagesClassifier application. Pixels of the output image will contain the class labels decided by the classifier (maximal class label = 65535). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be classified. By default, the remaining of pixels will be given the label 0 in the output image.");
 
     SetDocLimitations("The input image must have the same type, order and number of bands than the images used to produce the statistics file and the SVM model file. If a statistics file was used during training by the TrainImagesClassifier, it is mandatory to use the same statistics file for classification. If an input mask is used, its size must match the input image size.");
     SetDocAuthors("OTB-Team");
@@ -101,6 +102,15 @@ private:
     SetParameterDescription("imstat", "A XML file containing mean and standard deviation to center and reduce samples before classification (produced by ComputeImagesStatistics application).");
     MandatoryOff("imstat");
 
+    AddParameter(ParameterType_Int, "nodatalabel", "Label mask value");
+    SetParameterDescription("nodatalabel", "By default, "
+      "hidden pixels will have the assigned label 0 in the output image. "
+      "It's possible to define the label mask by another value, "
+      "but be careful to not take a label from another class (max. 65535).");
+
+    SetDefaultParameterInt("nodatalabel", 0);
+    MandatoryOff("nodatalabel");
+
     AddParameter(ParameterType_OutputImage, "out",  "Output Image");
     SetParameterDescription( "out", "Output image containing class labels");
     SetDefaultOutputPixelType( "out", ImagePixelType_uint8);
@@ -165,6 +175,8 @@ private:
     m_ClassificationFilter = ClassificationFilterType::New();
     m_ClassificationFilter->SetModel(m_Model);
 
+    m_ClassificationFilter->SetDefaultLabel(GetParameterInt("nodatalabel"));
+
     // Normalize input image if asked
     if(IsParameterEnabled("imstat")  )
       {
diff --git a/Modules/Applications/AppClassification/app/otbKMeansClassification.cxx b/Modules/Applications/AppClassification/app/otbKMeansClassification.cxx
index 36eeb318fadd983426556b41c0336d21a0366448..173daeec99126cd7cf288890d5c6d009b3a41b71 100644
--- a/Modules/Applications/AppClassification/app/otbKMeansClassification.cxx
+++ b/Modules/Applications/AppClassification/app/otbKMeansClassification.cxx
@@ -18,536 +18,500 @@
  * limitations under the License.
  */
 
-
-#include "otbWrapperApplication.h"
+#include "otbWrapperCompositeApplication.h"
 #include "otbWrapperApplicationFactory.h"
 
-#include "otbVectorImage.h"
-#include "otbStreamingTraits.h"
-#include "itkImageRegionConstIterator.h"
-#include "itkListSample.h"
-#include "itkWeightedCentroidKdTreeGenerator.h"
-#include "itkKdTreeBasedKmeansEstimator.h"
-#include "otbStreamingShrinkImageFilter.h"
-#include "otbChangeLabelImageFilter.h"
-#include "otbRAMDrivenStrippedStreamingManager.h"
-
-#include "otbChangeLabelImageFilter.h"
-#include "itkLabelToRGBImageFilter.h"
-#include "otbReliefColormapFunctor.h"
-#include "itkScalarToRGBColormapImageFilter.h"
-
+#include "otbOGRDataToSamplePositionFilter.h"
 
 namespace otb
 {
-
-
 namespace Wrapper
 {
 
-namespace Functor
-{
-template <class TSample, class TLabel> class KMeansFunctor
-{
-public:
-  /** operator */
-  TLabel operator ()(const TSample& sample) const
-  {
-    typename CentroidMapType::const_iterator it = m_CentroidsMap.begin();
-
-    if (it == m_CentroidsMap.end())
-      {
-      return 0;
-      }
-
-    TLabel resp = it->first;
-    double minDist = m_Distance->Evaluate(sample, it->second);
-    ++it;
-
-    while (it != m_CentroidsMap.end())
-      {
-      double dist = m_Distance->Evaluate(sample, it->second);
-
-      if (dist < minDist)
-        {
-        resp = it->first;
-        minDist = dist;
-        }
-      ++it;
-      }
-    return resp;
-  }
-
-  /** Add a new centroid */
-  void AddCentroid(const TLabel& label, const TSample& centroid)
-  {
-    m_CentroidsMap[label] = centroid;
-  }
-
-  /** Constructor */
-  KMeansFunctor() : m_CentroidsMap(), m_Distance()
-  {
-    m_Distance = DistanceType::New();
-  }
-
-  bool operator !=(const KMeansFunctor& other) const
-  {
-    return m_CentroidsMap != other.m_CentroidsMap;
-  }
-
-private:
-  typedef std::map<TLabel, TSample>                   CentroidMapType;
-  typedef itk::Statistics::EuclideanDistanceMetric<TSample> DistanceType;
-
-  CentroidMapType m_CentroidsMap;
-  typename DistanceType::Pointer m_Distance;
-};
-}
-
-
-typedef FloatImageType::PixelType PixelType;
-typedef UInt16ImageType   LabeledImageType;
-
-typedef UInt16VectorImageType       VectorImageType;
-typedef VectorImageType::PixelType  VectorPixelType;
-typedef UInt8RGBImageType           RGBImageType;
-typedef RGBImageType::PixelType     RGBPixelType;
-
-
-typedef LabeledImageType::PixelType LabelType;
-
-
-typedef FloatVectorImageType::PixelType                               SampleType;
-typedef itk::Statistics::ListSample<SampleType> ListSampleType;
-typedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType;
-typedef TreeGeneratorType::KdTreeType TreeType;
-typedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType;
-typedef RAMDrivenStrippedStreamingManager<FloatVectorImageType> RAMDrivenStrippedStreamingManagerType;
-
-
-typedef itk::ImageRegionConstIterator<FloatVectorImageType> IteratorType;
-typedef itk::ImageRegionConstIterator<UInt8ImageType> LabeledIteratorType;
-
-typedef otb::StreamingShrinkImageFilter<FloatVectorImageType,
-     FloatVectorImageType>              ImageSamplingFilterType;
-
-typedef otb::StreamingShrinkImageFilter<UInt8ImageType,
-    UInt8ImageType>              MaskSamplingFilterType;
-typedef Functor::KMeansFunctor<SampleType, LabelType> KMeansFunctorType;
-typedef itk::UnaryFunctorImageFilter<FloatVectorImageType,
-    LabeledImageType, KMeansFunctorType>     KMeansFilterType;
-
-
-// Manual label LUT
- typedef otb::ChangeLabelImageFilter
- <LabeledImageType, VectorImageType>    ChangeLabelFilterType;
-
- // Continuous LUT mapping
-  typedef itk::ScalarToRGBColormapImageFilter<LabeledImageType, RGBImageType>      ColorMapFilterType;
-
-
-  typedef otb::Functor::ReliefColormapFunctor
-   <LabelType, RGBPixelType>           ReliefColorMapFunctorType;
-
-  typedef otb::ImageMetadataInterfaceBase ImageMetadataInterfaceType;
-
-
-class KMeansClassification: public Application
+class KMeansApplicationBase : public CompositeApplication
 {
 public:
   /** Standard class typedefs. */
-  typedef KMeansClassification Self;
-  typedef Application Superclass;
+  typedef KMeansApplicationBase Self;
+  typedef CompositeApplication Superclass;
   typedef itk::SmartPointer<Self> Pointer;
   typedef itk::SmartPointer<const Self> ConstPointer;
 
   /** Standard macro */
-  itkNewMacro(Self);
+  itkTypeMacro( KMeansApplicationBase, Superclass )
 
-  itkTypeMacro(KMeansClassification, otb::Application);
-
-private:
-  void DoInit() ITK_OVERRIDE
+protected:
+  void InitKMParams()
   {
-    SetName("KMeansClassification");
-    SetDescription("Unsupervised KMeans image classification");
+    AddApplication("ImageEnvelope", "imgenvelop", "mean shift smoothing");
+    AddApplication("PolygonClassStatistics", "polystats", "Polygon Class Statistics");
+    AddApplication("SampleSelection", "select", "Sample selection");
+    AddApplication("SampleExtraction", "extraction", "Sample extraction");
+
+    AddApplication("TrainVectorClassifier", "training", "Model training");
+    AddApplication("ComputeImagesStatistics", "imgstats", "Compute Images second order statistics");
+    AddApplication("ImageClassifier", "classif", "Performs a classification of the input image");
+
+    ShareParameter("in", "imgenvelop.in");
+    ShareParameter("out", "classif.out");
+
+    InitKMSampling();
+    InitKMClassification();
+
+    // init at the end cleanup
+    AddParameter( ParameterType_Empty, "cleanup", "Temporary files cleaning" );
+    EnableParameter( "cleanup" );
+    SetParameterDescription( "cleanup",
+                           "If activated, the application will try to clean all temporary files it created" );
+    MandatoryOff( "cleanup" );
+  }
 
-    SetDocName("Unsupervised KMeans image classification");
-    SetDocLongDescription("Performs unsupervised KMeans image classification.");
-    SetDocLimitations("None");
-    SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
+  void InitKMSampling()
+  {
+    AddParameter(ParameterType_Int, "nc", "Number of classes");
+    SetParameterDescription("nc", "Number of modes, which will be used to generate class membership.");
+    SetDefaultParameterInt("nc", 5);
 
-    AddDocTag(Tags::Learning);
-	AddDocTag(Tags::Segmentation);
-	
-    AddParameter(ParameterType_InputImage, "in", "Input Image");
-    SetParameterDescription("in", "Input image to classify.");
-    AddParameter(ParameterType_OutputImage, "out", "Output Image");
-    SetParameterDescription("out", "Output image containing the class indexes.");
-    SetDefaultOutputPixelType("out",ImagePixelType_uint8);
-
-    AddRAMParameter();
-
-    AddParameter(ParameterType_InputImage, "vm", "Validity Mask");
-    SetParameterDescription("vm", "Validity mask. Only non-zero pixels will be used to estimate KMeans modes.");
-    MandatoryOff("vm");
     AddParameter(ParameterType_Int, "ts", "Training set size");
     SetParameterDescription("ts", "Size of the training set (in pixels).");
     SetDefaultParameterInt("ts", 100);
     MandatoryOff("ts");
-    AddParameter(ParameterType_Int, "nc", "Number of classes");
-    SetParameterDescription("nc", "Number of modes, which will be used to generate class membership.");
-    SetDefaultParameterInt("nc", 5);
+
     AddParameter(ParameterType_Int, "maxit", "Maximum number of iterations");
     SetParameterDescription("maxit", "Maximum number of iterations for the learning step.");
     SetDefaultParameterInt("maxit", 1000);
     MandatoryOff("maxit");
-    AddParameter(ParameterType_Float, "ct", "Convergence threshold");
-    SetParameterDescription("ct", "Convergence threshold for class centroid  (L2 distance, by default 0.0001).");
-    SetDefaultParameterFloat("ct", 0.0001);
-    MandatoryOff("ct");
+
     AddParameter(ParameterType_OutputFilename, "outmeans", "Centroid filename");
     SetParameterDescription("outmeans", "Output text file containing centroid positions");
     MandatoryOff("outmeans");
 
-    AddRANDParameter();
-
-    // Doc example parameter settings
-    SetDocExampleParameterValue("in", "QB_1_ortho.tif");
-    SetDocExampleParameterValue("ts", "1000");
-    SetDocExampleParameterValue("nc", "5");
-    SetDocExampleParameterValue("maxit", "1000");
-    SetDocExampleParameterValue("ct", "0.0001");
-    SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif");
-
-    SetOfficialDocLink();
+    ShareKMSamplingParameters();
+    ConnectKMSamplingParams();
   }
 
-  void DoUpdateParameters() ITK_OVERRIDE
+  void InitKMClassification()
   {
-    // test of input image //
-    if (HasValue("in"))
-      {
-      // input image
-      FloatVectorImageType::Pointer inImage = GetParameterImage("in");
+    ShareKMClassificationParams();
+    ConnectKMClassificationParams();
+  }
 
-      RAMDrivenStrippedStreamingManagerType::Pointer streamingManager = RAMDrivenStrippedStreamingManagerType::New();
-      int availableRAM = GetParameterInt("ram");
-      streamingManager->SetAvailableRAMInMB(availableRAM);
-      float bias = 1.5; // empirical value
-      streamingManager->SetBias(bias);
-      FloatVectorImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion();
-      FloatVectorImageType::SizeType largestRegionSize = largestRegion.GetSize();
-      streamingManager->PrepareStreaming(inImage, largestRegion);
+  void ShareKMSamplingParameters()
+  {
+    ShareParameter("ram", "polystats.ram");
+    ShareParameter("sampler", "select.sampler");
+    ShareParameter("vm", "polystats.mask", "Validity Mask",
+      "Validity mask, only non-zero pixels will be used to estimate KMeans modes.");
+  }
 
-      unsigned long nbDivisions = streamingManager->GetNumberOfSplits();
-      unsigned long largestPixNb = largestRegionSize[0] * largestRegionSize[1];
+  void ShareKMClassificationParams()
+  {
+    ShareParameter("nodatalabel", "classif.nodatalabel", "Label mask value",
+      "By default, hidden pixels will have the assigned label 0 in the output image. "
+      "It's possible to define the label mask by another value, "
+      "but be careful to not take a label from another class. "
+      "This application initalize the labels from 0 to N-1, "
+      "N is the number of class (defined by 'nc' parameter).");
+  }
 
-      unsigned long maxPixNb = largestPixNb / nbDivisions;
+  void ConnectKMSamplingParams()
+  {
+    Connect("polystats.in", "imgenvelop.in");
 
-      if (GetParameterInt("ts") > static_cast<int> (maxPixNb))
-        {
-        otbAppLogWARNING("The available RAM is too small to process this sample size of " << GetParameterInt("ts") <<
-            " pixels. The sample size will be reduced to " << maxPixNb << " pixels." << std::endl);
-        this->SetParameterInt("ts",maxPixNb, false);
-        }
+    Connect("select.in", "polystats.in");
+    Connect("select.vec", "polystats.vec");
+    Connect("select.ram", "polystats.ram");
 
-      this->SetMaximumParameterIntValue("ts", maxPixNb);
-      }
+    Connect("extraction.in", "select.in");
+    Connect("extraction.field", "select.field");
+    Connect("extraction.vec", "select.out");
+    Connect("extraction.ram", "polystats.ram");
   }
 
-  void DoExecute() ITK_OVERRIDE
+  void ConnectKMClassificationParams()
   {
-    GetLogger()->Debug("Entering DoExecute\n");
+    Connect("training.cfield", "extraction.field");
+    Connect("training.io.stats","imgstats.out");
 
-    m_InImage = GetParameterImage("in");
-    m_InImage->UpdateOutputInformation();
-    UInt8ImageType::Pointer maskImage;
+    Connect("classif.in", "imgenvelop.in");
+    Connect("classif.model", "training.io.out");
+    Connect("classif.ram", "polystats.ram");
+    Connect("classif.imstat", "imgstats.out");
+  }
 
-    std::ostringstream message("");
+  void ConnectKMClassificationMask()
+  {
+    otbAppLogINFO("Using input mask ...");
+    Connect("select.mask", "polystats.mask");
+    Connect("classif.mask", "select.mask");
+  }
 
-    int nbsamples = GetParameterInt("ts");
-    const unsigned int nbClasses = GetParameterInt("nc");
+  void ComputeImageEnvelope(const std::string &vectorFileName)
+  {
+    GetInternalApplication("imgenvelop")->SetParameterString("out", vectorFileName, false);
+    GetInternalApplication("imgenvelop")->ExecuteAndWriteOutput();
+  }
 
-    /*******************************************/
-    /*           Sampling data                 */
-    /*******************************************/
+  void ComputeAddField(const std::string &vectorFileName,
+                       const std::string &fieldName)
+  {
+    otbAppLogINFO("add field in the layer ...");
+    otb::ogr::DataSource::Pointer ogrDS;
+    ogrDS = otb::ogr::DataSource::New(vectorFileName, otb::ogr::DataSource::Modes::Update_LayerUpdate);
+    otb::ogr::Layer layer = ogrDS->GetLayer(0);
+
+    OGRFieldDefn classField(fieldName.c_str(), OFTInteger);
+    classField.SetWidth(classField.GetWidth());
+    classField.SetPrecision(classField.GetPrecision());
+    ogr::FieldDefn classFieldDefn(classField);
+    layer.CreateField(classFieldDefn);
+
+    otb::ogr::Layer::const_iterator it = layer.cbegin();
+    otb::ogr::Layer::const_iterator itEnd = layer.cend();
+    for( ; it!=itEnd ; ++it)
+    {
+      ogr::Feature dstFeature(layer.GetLayerDefn());
+      dstFeature.SetFrom( *it, TRUE);
+      dstFeature.SetFID(it->GetFID());
+      dstFeature[fieldName].SetValue<int>(0);
+      layer.SetFeature(dstFeature);
+    }
+    const OGRErr err = layer.ogr().CommitTransaction();
+    if (err != OGRERR_NONE)
+      itkExceptionMacro(<< "Unable to commit transaction for OGR layer " << layer.ogr().GetName() << ".");
+    ogrDS->SyncToDisk();
+  }
 
-    otbAppLogINFO("-- SAMPLING DATA --"<<std::endl);
+  void ComputePolygonStatistics(const std::string &statisticsFileName,
+                                const std::string &fieldName)
+  {
+    std::vector<std::string> fieldList = {fieldName};
 
-    // Update input images information
-    m_InImage->UpdateOutputInformation();
+    GetInternalApplication("polystats")->SetParameterStringList("field", fieldList, false);
+    GetInternalApplication("polystats")->SetParameterString("out", statisticsFileName, false);
 
-    bool maskFlag = IsParameterEnabled("vm");
-    if (maskFlag)
-      {
-      otbAppLogINFO("sample choice using mask "<<std::endl);
-      maskImage = GetParameterUInt8Image("vm");
-      maskImage->UpdateOutputInformation();
-      if (m_InImage->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion())
-        {
-        GetLogger()->Error("Mask image and input image have different sizes.");
-        return;
-        }
-      }
+    ExecuteInternal("polystats");
+  }
 
-    // Training sample lists
-    ListSampleType::Pointer sampleList = ListSampleType::New();
-    sampleList->SetMeasurementVectorSize(m_InImage->GetNumberOfComponentsPerPixel());
+  void SelectAndExtractSamples(const std::string &statisticsFileName,
+                               const std::string &fieldName,
+                               const std::string &sampleFileName,
+                               int NBSamples)
+  {
+    /* SampleSelection */
+    GetInternalApplication("select")->SetParameterString("out", sampleFileName, false);
 
-    //unsigned int init_means_index = 0;
+    UpdateInternalParameters("select");
+    GetInternalApplication("select")->SetParameterString("instats", statisticsFileName, false);
+    GetInternalApplication("select")->SetParameterString("field", fieldName, false);
 
-    // Sample dimension and max dimension
-    const unsigned int nbComp = m_InImage->GetNumberOfComponentsPerPixel();
-    unsigned int sampleSize = nbComp;
-    unsigned int totalSamples = 0;
+    GetInternalApplication("select")->SetParameterString("strategy", "constant", false);
+    GetInternalApplication("select")->SetParameterInt("strategy.constant.nb", NBSamples, false);
 
-    // sampleSize = std::min(nbComp, maxDim);
+    if( IsParameterEnabled("rand"))
+      GetInternalApplication("select")->SetParameterInt("rand", GetParameterInt("rand"), false);
 
-    EstimatorType::ParametersType initialMeans(nbComp * nbClasses);
-    initialMeans.Fill(0);
+    // select sample positions
+    ExecuteInternal("select");
 
-    // use image and mask shrink
+    /* SampleExtraction */
+    UpdateInternalParameters("extraction");
 
-    ImageSamplingFilterType::Pointer imageSampler = ImageSamplingFilterType::New();
-    imageSampler->SetInput(m_InImage);
+    GetInternalApplication("extraction")->SetParameterString("outfield", "prefix", false);
+    GetInternalApplication("extraction")->SetParameterString("outfield.prefix.name", "value_", false);
 
-    double theoricNBSamplesForKMeans = nbsamples;
+    // extract sample descriptors
+    GetInternalApplication("extraction")->ExecuteAndWriteOutput();
+  }
 
-    const double upperThresholdNBSamplesForKMeans = 1000 * 1000;
-    const double actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans, upperThresholdNBSamplesForKMeans);
+  void TrainKMModel(FloatVectorImageType *image,
+                    const std::string &sampleTrainFileName,
+                    const std::string &modelFileName)
+  {
+    std::vector<std::string> extractOutputList = {sampleTrainFileName};
+    GetInternalApplication("training")->SetParameterStringList("io.vd", extractOutputList, false);
+    UpdateInternalParameters("training");
+
+    // set field names
+    std::string selectPrefix = GetInternalApplication("extraction")->GetParameterString("outfield.prefix.name");
+    unsigned int nbBands = image->GetNumberOfComponentsPerPixel();
+    std::vector<std::string> selectedNames;
+    for( unsigned int i = 0; i < nbBands; i++ )
+      {
+      std::ostringstream oss;
+      oss << i;
+      selectedNames.push_back( selectPrefix + oss.str() );
+      }
+    GetInternalApplication("training")->SetParameterStringList("feat", selectedNames, false);
 
-    otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." << std::endl);
+    GetInternalApplication("training")->SetParameterString("classifier", "sharkkm", false);
+    GetInternalApplication("training")->SetParameterInt("classifier.sharkkm.maxiter",
+                                                        GetParameterInt("maxit"), false);
+    GetInternalApplication("training")->SetParameterInt("classifier.sharkkm.k",
+                                                        GetParameterInt("nc"), false);
 
-    const double shrinkFactor = vcl_floor(
-                                          vcl_sqrt(
-                                                   m_InImage->GetLargestPossibleRegion().GetNumberOfPixels()
-                                                       / actualNBSamplesForKMeans));
-    imageSampler->SetShrinkFactor(shrinkFactor);
-    imageSampler->Update();
+    if( IsParameterEnabled("rand"))
+      GetInternalApplication("training")->SetParameterInt("rand", GetParameterInt("rand"), false);
+    GetInternalApplication("training")->GetParameterByKey("v")->SetActive(false);
 
-    MaskSamplingFilterType::Pointer maskSampler;
-    LabeledIteratorType m_MaskIt;
-    if (maskFlag)
-      {
-      maskSampler = MaskSamplingFilterType::New();
-      maskSampler->SetInput(maskImage);
-      maskSampler->SetShrinkFactor(shrinkFactor);
-      maskSampler->Update();
-      m_MaskIt = LabeledIteratorType(maskSampler->GetOutput(), maskSampler->GetOutput()->GetLargestPossibleRegion());
-      m_MaskIt.GoToBegin();
-      }
-    // Then, build the sample list
+    GetInternalApplication("training")->SetParameterString("io.out", modelFileName, false);
 
-    IteratorType it(imageSampler->GetOutput(), imageSampler->GetOutput()->GetLargestPossibleRegion());
+    ExecuteInternal( "training" );
+    otbAppLogINFO("output model : " << GetInternalApplication("training")->GetParameterString("io.out"));
+  }
 
-    it.GoToBegin();
+  void ComputeImageStatistics(const std::string &imageFileName,
+                                               const std::string &imagesStatsFileName)
+  {
+    std::vector<std::string> imageFileNameList = {imageFileName};
+    GetInternalApplication("imgstats")->SetParameterStringList("il", imageFileNameList, false);
+    GetInternalApplication("imgstats")->SetParameterString("out", imagesStatsFileName, false);
 
-    SampleType min;
-    SampleType max;
-    SampleType sample;
-    //first sample
+    ExecuteInternal( "imgstats" );
+    otbAppLogINFO("image statistics file : " << GetInternalApplication("imgstats")->GetParameterString("out"));
+  }
 
-    itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen=itk::Statistics::MersenneTwisterRandomVariateGenerator::GetInstance();
 
-    //randGen->Initialize();
+  void KMeansClassif()
+  {
+    ExecuteInternal( "classif" );
+  }
 
-    if (maskFlag)
+  void CreateOutMeansFile(FloatVectorImageType *image,
+                          const std::string &modelFileName,
+                          unsigned int nbClasses)
+  {
+    if (IsParameterEnabled("outmeans"))
+    {
+      unsigned int nbBands = image->GetNumberOfComponentsPerPixel();
+      unsigned int nbElements = nbClasses * nbBands;
+      // get the line in model file that contains the centroids positions
+      std::ifstream infile(modelFileName);
+      if(!infile)
       {
-      while (!it.IsAtEnd() && !m_MaskIt.IsAtEnd() && (m_MaskIt.Get() <= 0))
-        {
-        ++it;
-        ++m_MaskIt;
-        }
-
-      // If the mask is empty after the subsampling
-      if (m_MaskIt.IsAtEnd())
-        {
-        GetLogger()->Error("The mask image is empty after subsampling. Please increase the training set size.");
-        return;
-        }
+        itkExceptionMacro(<< "File : " << modelFileName << " couldn't be opened");
       }
 
-    min = it.Get();
-    max = it.Get();
-    sample = it.Get();
+      // get the end line with the centroids
+      std::string line, centroidLine;
+      while(std::getline(infile,line))
+      {
+        if (!line.empty())
+          centroidLine = line;
+      }
 
-    sampleList->PushBack(sample);
+      std::vector<std::string> centroidElm;
+      boost::split(centroidElm,centroidLine,boost::is_any_of(" "));
 
-    ++it;
+      // remove the first elements, not the centroids positions
+      int nbWord = centroidElm.size();
+      int beginCentroid = nbWord-nbElements;
+      centroidElm.erase(centroidElm.begin(), centroidElm.begin()+beginCentroid);
 
-    if (maskFlag)
-      {
-      ++m_MaskIt;
-      }
+      // write in the output file
+      std::ofstream outfile;
+      outfile.open(GetParameterString("outmeans"));
 
-    totalSamples = 1;
-    bool selectSample;
-    while (!it.IsAtEnd())
+      for (unsigned int i = 0; i < nbClasses; i++)
       {
-      if (maskFlag)
+        for (unsigned int j = 0; j < nbBands; j++)
         {
-        selectSample = (m_MaskIt.Get() > 0);
-        ++m_MaskIt;
+          outfile << std::setw(8) << centroidElm[i * nbBands + j] << " ";
         }
-      else selectSample = true;
+        outfile << std::endl;
+      }
+    }
+  }
 
-      if (selectSample)
-        {
-        totalSamples++;
+  class KMeansFileNamesHandler
+    {
+    public :
+      KMeansFileNamesHandler(const std::string &outPath)
+      {
+        tmpVectorFile = outPath + "_imgEnvelope.shp";
+        polyStatOutput = outPath + "_polyStats.xml";
+        sampleOutput = outPath + "_sampleSelect.shp";
+        modelFile = outPath + "_model.txt";
+        imgStatOutput = outPath + "_imgstats.xml";
+      }
 
-        sample = it.Get();
+      void clear()
+      {
+        RemoveFile(tmpVectorFile);
+        RemoveFile(polyStatOutput);
+        RemoveFile(sampleOutput);
+        RemoveFile(modelFile);
+        RemoveFile(imgStatOutput);
+      }
 
-        sampleList->PushBack(sample);
+      std::string tmpVectorFile;
+      std::string polyStatOutput;
+      std::string sampleOutput;
+      std::string modelFile;
+      std::string imgStatOutput;
 
-        for (unsigned int i = 0; i < nbComp; ++i)
+    private:
+      bool RemoveFile(const std::string &filePath)
+      {
+        bool res = true;
+        if( itksys::SystemTools::FileExists( filePath.c_str() ) )
           {
-          if (min[i] > sample[i])
+          size_t posExt = filePath.rfind( '.' );
+          if( posExt != std::string::npos && filePath.compare( posExt, std::string::npos, ".shp" ) == 0 )
             {
-            min[i] = sample[i];
+            std::string shxPath = filePath.substr( 0, posExt ) + std::string( ".shx" );
+            std::string dbfPath = filePath.substr( 0, posExt ) + std::string( ".dbf" );
+            std::string prjPath = filePath.substr( 0, posExt ) + std::string( ".prj" );
+            RemoveFile( shxPath );
+            RemoveFile( dbfPath );
+            RemoveFile( prjPath );
             }
-          if (max[i] < sample[i])
+          res = itksys::SystemTools::RemoveFile( filePath.c_str() );
+          if( !res )
             {
-            max[i] = sample[i];
+            //otbAppLogINFO( <<"Unable to remove file  "<<filePath );
             }
           }
-        }
-      ++it;
+        return res;
       }
 
-    // Next, initialize centroids by random sampling in the generated
-    // list of samples
+    };
 
-    for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex)
-      {
-      SampleType newCentroid = sampleList->GetMeasurementVector(randGen->GetIntegerVariate(sampleList->Size()-1));
+};
 
-      for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex)
-        {
-        initialMeans[compIndex + classIndex * sampleSize] = newCentroid[compIndex];
-        }
-      }
-    otbAppLogINFO(<< totalSamples << " samples will be used as estimator input." << std::endl);
 
-    /*******************************************/
-    /*           Learning                      */
-    /*******************************************/
+class KMeansClassification: public KMeansApplicationBase
+{
+public:
+  /** Standard class typedefs. */
+  typedef KMeansClassification Self;
+  typedef KMeansApplicationBase Superclass;
+  typedef itk::SmartPointer<Self> Pointer;
+  typedef itk::SmartPointer<const Self> ConstPointer;
 
-    otbAppLogINFO("-- LEARNING --" << std::endl);
-    otbAppLogINFO("Initial centroids are: " << std::endl);
+  /** Standard macro */
+  itkNewMacro(Self);
 
-    message.str("");
-    message << std::endl;
-    for (unsigned int i = 0; i < nbClasses; i++)
-      {
-      message << "Class " << i << ": ";
-      for (unsigned int j = 0; j < sampleSize; j++)
-        {
-        message << std::setw(8) << initialMeans[i * sampleSize + j] << "   ";
-        }
-      message << std::endl;
-      }
-    message << std::endl;
-    GetLogger()->Info(message.str());
-    message.str("");
-    otbAppLogINFO("Starting optimization." << std::endl);
-    EstimatorType::Pointer estimator = EstimatorType::New();
+  itkTypeMacro(Self, Superclass);
 
-    TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();
-    treeGenerator->SetSample(sampleList);
+private:
+  void DoInit() ITK_OVERRIDE
+  {
+    SetName("KMeansClassification");
+    SetDescription("Unsupervised KMeans image classification");
 
-    treeGenerator->SetBucketSize(10000);
-    treeGenerator->Update();
+    SetDocName("Unsupervised KMeans image classification");
+    SetDocLongDescription("Performs unsupervised KMeans image classification."
+      "KMeansClassification is a composite application, "
+      "using an existing training and classification application."
+      "The SharkKMeans model is used.\n"
+      "The steps of this composite application :\n"
+        "1) ImageEnveloppe : create a shapefile (1 polygon),\n"
+        "2) PolygonClassStatistics : compute the statistics,\n"
+        "3) SampleSelection : select the samples by constant strategy in the shapefile "
+            "(1000000 samples max),\n"
+        "4) SamplesExtraction : extract the samples descriptors (update of SampleSelection output file),\n"
+        "5) ComputeImagesStatistics : compute images second order statistics,\n"
+        "6) TrainVectorClassifier : train the SharkKMeans model,\n"
+        "7) ImageClassifier : performs the classification of the input image "
+            "according to a model file.\n\n"
+        "It's possible to choice random/periodic modes of the SampleSelection application.\n"
+        "If you want keep the temporary files (sample selected, model file, ...), "
+        "initialize cleanup parameter.\n"
+        "For more information on shark KMeans algorithm [1].");
 
-    estimator->SetParameters(initialMeans);
-    estimator->SetKdTree(treeGenerator->GetOutput());
-    int maxIt = GetParameterInt("maxit");
-    estimator->SetMaximumIteration(maxIt);
-    estimator->SetCentroidPositionChangesThreshold(GetParameterFloat("ct"));
-    estimator->StartOptimization();
+    SetDocLimitations("None");
+    SetDocAuthors("OTB-Team");
+    SetDocSeeAlso("ImageEnveloppe PolygonClassStatistics SampleSelection SamplesExtraction "
+      "PolygonClassStatistics TrainVectorClassifier ImageClassifier\n"
+      "[1] http://image.diku.dk/shark/sphinx_pages/build/html/rest_sources/tutorials/algorithms/kmeans.html");
 
-    EstimatorType::ParametersType estimatedMeans = estimator->GetParameters();
+    AddDocTag(Tags::Learning);
+    AddDocTag(Tags::Segmentation);
 
-    otbAppLogINFO("Optimization completed." );
-    if (estimator->GetCurrentIteration() == maxIt)
-      {
-      otbAppLogWARNING("The estimator reached the maximum iteration number." << std::endl);
-      }
-    message.str("");
-    message << "Estimated centroids are: " << std::endl;
-    message << std::endl;
-    for (unsigned int i = 0; i < nbClasses; i++)
-      {
-      message << "Class " << i << ": ";
-      for (unsigned int j = 0; j < sampleSize; j++)
-        {
-        message << std::setw(8) << estimatedMeans[i * sampleSize + j] << "   ";
-        }
-      message << std::endl;
-      }
+    // Perform initialization
+    ClearApplications();
 
-    message << std::endl;
-    message << "Learning completed." << std::endl;
-    message << std::endl;
-    GetLogger()->Info(message.str());
+    // initialisation parameters and synchronizes parameters
+    Superclass::InitKMParams();
 
-    /*******************************************/
-    /*           Classification                */
-    /*******************************************/
-    otbAppLogINFO("-- CLASSIFICATION --" << std::endl);
+    AddRANDParameter();
 
-    // Finally, update the KMeans filter
-    KMeansFunctorType functor;
+    // Doc example parameter settings
+    SetDocExampleParameterValue("in", "QB_1_ortho.tif");
+    SetDocExampleParameterValue("ts", "1000");
+    SetDocExampleParameterValue("nc", "5");
+    SetDocExampleParameterValue("maxit", "1000");
+    SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif uint8");
 
-    for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex)
-      {
-      SampleType centroid(sampleSize);
+    SetOfficialDocLink();
+  }
 
-      for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex)
-        {
-        centroid[compIndex] = estimatedMeans[compIndex + classIndex * sampleSize];
-        }
-      functor.AddCentroid(classIndex, centroid);
-      }
+  void DoUpdateParameters() ITK_OVERRIDE
+  {
+  }
 
-    m_KMeansFilter = KMeansFilterType::New();
-    m_KMeansFilter->SetFunctor(functor);
-    m_KMeansFilter->SetInput(m_InImage);
+  void DoExecute() ITK_OVERRIDE
+  {
+    if (IsParameterEnabled("vm") && HasValue("vm")) Superclass::ConnectKMClassificationMask();
 
-    // optional saving option -> lut
+    KMeansFileNamesHandler fileNames(GetParameterString("out"));
 
-    if (IsParameterEnabled("outmeans"))
-      {
-      std::ofstream file;
-      file.open(GetParameterString("outmeans").c_str());
-      for (unsigned int i = 0; i < nbClasses; i++)
-        {
+    const std::string fieldName = "field";
 
-        for (unsigned int j = 0; j < sampleSize; j++)
-          {
-          file << std::setw(8) << estimatedMeans[i * sampleSize + j] << " ";
-          }
-        file << std::endl;
-        }
+    // Create an image envelope
+    Superclass::ComputeImageEnvelope(fileNames.tmpVectorFile);
+    // Add a new field at the ImageEnvelope output file
+    Superclass::ComputeAddField(fileNames.tmpVectorFile, fieldName);
 
-      file.close();
-      }
+    // Compute PolygonStatistics app
+    UpdateKMPolygonClassStatisticsParameters(fileNames.tmpVectorFile);
+    Superclass::ComputePolygonStatistics(fileNames.polyStatOutput, fieldName);
+
+    // Compute number of sample max for KMeans
+    const int theoricNBSamplesForKMeans = GetParameterInt("ts");
+    const int upperThresholdNBSamplesForKMeans = 1000 * 1000;
+    const int actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans,
+                                                  upperThresholdNBSamplesForKMeans);
+    otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." \
+                  << std::endl);
+
+    // Compute SampleSelection and SampleExtraction app
+    Superclass::SelectAndExtractSamples(fileNames.polyStatOutput, fieldName,
+                                        fileNames.sampleOutput,
+                                        actualNBSamplesForKMeans);
+
+    // Compute Images second order statistics
+    Superclass::ComputeImageStatistics(GetParameterString("in"), fileNames.imgStatOutput);
+
+    // Compute a train model with TrainVectorClassifier app
+    Superclass::TrainKMModel(GetParameterImage("in"), fileNames.sampleOutput,
+                             fileNames.modelFile);
+
+    // Compute a classification of the input image according to a model file
+    Superclass::KMeansClassif();
 
-    SetParameterOutputImage("out", m_KMeansFilter->GetOutput());
+    // Create the output text file containing centroids positions
+    Superclass::CreateOutMeansFile(GetParameterImage("in"), fileNames.modelFile, GetParameterInt("nc"));
 
+    // Remove all tempory files
+    if( IsParameterEnabled( "cleanup" ) )
+      {
+      otbAppLogINFO( <<"Final clean-up ..." );
+      fileNames.clear();
+      }
   }
 
-  // KMeans filter
-  KMeansFilterType::Pointer           m_KMeansFilter;
-  FloatVectorImageType::Pointer       m_InImage;
+  void UpdateKMPolygonClassStatisticsParameters(const std::string &vectorFileName)
+  {
+    GetInternalApplication( "polystats" )->SetParameterString( "vec", vectorFileName, false );
+    UpdateInternalParameters( "polystats" );
+  }
 
 };
 
-
 }
 }
 
 OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification)
 
-
diff --git a/Modules/Applications/AppClassification/app/otbMultiImageSamplingRate.cxx b/Modules/Applications/AppClassification/app/otbMultiImageSamplingRate.cxx
index 6eb8ee539b14b8faa821bc6211ddc41c6afd8118..889e909cc54301fb53eeb952783e9d1f4325fa20 100644
--- a/Modules/Applications/AppClassification/app/otbMultiImageSamplingRate.cxx
+++ b/Modules/Applications/AppClassification/app/otbMultiImageSamplingRate.cxx
@@ -110,7 +110,7 @@ private:
       "  * strategy = smallest class\n\n"
       "    - if mim = proportional, then the smallest class size (computed globally) is used for the strategy constant+proportional.\n\n"
       "    - if mim = equal       , then the smallest class size (computed globally) is used for the strategy constant+equal.\n\n"
-      "    - if mim = custom      , then the smallest class is computed and used for each image separately.\n\n"
+      "    - if mim = custom      , then the smallest class is computed and used for each image separately."
       );
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
diff --git a/Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx b/Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx
index c1600ebce7e4730d13136682d8d602a583671e7b..ff4f4b01e4be8c30476b4aef78dadaf9819e606f 100644
--- a/Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx
+++ b/Modules/Applications/AppClassification/app/otbPolygonClassStatistics.cxx
@@ -85,7 +85,7 @@ private:
       "different for each type of geometry :\n"
       "  - polygon: select pixels whose center is inside the polygon\n"
       "  - lines  : select pixels intersecting the line\n"
-      "  - points : select closest pixel to the point\n");
+      "  - points : select closest pixel to the point");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
diff --git a/Modules/Applications/AppClassification/app/otbSOMClassification.cxx b/Modules/Applications/AppClassification/app/otbSOMClassification.cxx
index 18e12db92ef7836209082b73816c04196be2c9bf..86572e90ad0eebd83dbc8ec8ee3e338677984af6 100644
--- a/Modules/Applications/AppClassification/app/otbSOMClassification.cxx
+++ b/Modules/Applications/AppClassification/app/otbSOMClassification.cxx
@@ -254,6 +254,10 @@ private:
     itk::RandomPermutation randPerm(numberOfStreamDivisions);
     unsigned int index = 0;
 
+    // reset seed and step once (itk::RandomPermutation may have used it)
+    randomGen->SetSeed(GetParameterInt("rand"));
+    randomGen->GetVariateWithClosedRange();
+
     // TODO : maybe change the approach: at the moment, the sampling process is able to pick a sample twice or more
     while (totalSamples < nbsamples)
     {
diff --git a/Modules/Applications/AppClassification/app/otbSampleSelection.cxx b/Modules/Applications/AppClassification/app/otbSampleSelection.cxx
index 0437978311aff3e1de752907edf94bcc05bd6333..b41f20470f2ac4fe5d2321011cc6c806a66ebb03 100644
--- a/Modules/Applications/AppClassification/app/otbSampleSelection.cxx
+++ b/Modules/Applications/AppClassification/app/otbSampleSelection.cxx
@@ -120,7 +120,7 @@ private:
       "polygons, lines, points. \nThe behavior of this application is different for each type of geometry : \n\n"
       "  - polygon: select points whose center is inside the polygon\n"
       "  - lines  : select points intersecting the line\n"
-      "  - points : select closest point to the provided point\n");
+      "  - points : select closest point to the provided point");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
diff --git a/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx b/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx
index 21d3b58552dcd0799d2849632d57093238a7d489..1d1d387c131d3c49fe9402f108e6f1880dd24792 100644
--- a/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx
+++ b/Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx
@@ -110,9 +110,12 @@ protected:
     contingencyTableCalculator->Compute(performanceLabeledListSample->Begin(),
                                         performanceLabeledListSample->End(),predictedListSample->Begin(), predictedListSample->End());
 
-    otbAppLogINFO( "Training performances:" );
-
-    otbAppLogINFO(<<"Contingency table: reference labels (rows) vs. produced labels (cols)\n"<<contingencyTableCalculator->BuildContingencyTable());
+    if(IsParameterEnabled("v"))
+    {
+      otbAppLogINFO( "Training performances:" );
+      otbAppLogINFO(<<"Contingency table: reference labels (rows) vs. produced labels (cols)\n"
+        <<contingencyTableCalculator->BuildContingencyTable());
+    }
 
     return contingencyTableCalculator->BuildContingencyTable();
   }
diff --git a/Modules/Applications/AppClassification/app/otbVectorClassifier.cxx b/Modules/Applications/AppClassification/app/otbVectorClassifier.cxx
index 61d3a691f4560c46d2f76427f49ca7423cd159b8..042c4f450434c96de5367033f2c42ccde851dfe8 100644
--- a/Modules/Applications/AppClassification/app/otbVectorClassifier.cxx
+++ b/Modules/Applications/AppClassification/app/otbVectorClassifier.cxx
@@ -89,39 +89,52 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("VectorClassifier");
-    SetDescription("Performs a classification of the input vector data according to a model file."
-      "Features of the vector data output will contain the class labels decided by the classifier (maximal class label = 65535).");
+    SetDescription("Performs a classification of the input vector data according to a model file.");
 
     SetDocName("Vector Classification");
     SetDocAuthors("OTB-Team");
-    SetDocLongDescription("This application performs a vector data classification based on a model file produced by the TrainVectorClassifier application.");
+    SetDocLongDescription("This application performs a vector data classification "
+      "based on a model file produced by the TrainVectorClassifier application."
+      "Features of the vector data output will contain the class labels decided by the classifier "
+      "(maximal class label = 65535). \n"
+      "There are two modes: \n"
+        "1) Update mode: add of the 'cfield' field containing the predicted class in the input file. \n"
+        "2) Write mode: copies the existing fields of the input file in the output file "
+           " and add the 'cfield' field containing the predicted class. \n"
+      "If you have declared the output file, the write mode applies. "
+      "Otherwise, the input file update mode will be applied.");
+
     SetDocLimitations("Shapefiles are supported. But the SQLite format is only supported in update mode.");
     SetDocSeeAlso("TrainVectorClassifier");
     AddDocTag(Tags::Learning);
 
     AddParameter(ParameterType_InputVectorData, "in", "Name of the input vector data");
-    SetParameterDescription("in","The input vector data to classify.");
+    SetParameterDescription("in","The input vector data file to classify.");
 
     AddParameter(ParameterType_InputFilename, "instat", "Statistics file");
     SetParameterDescription("instat", "A XML file containing mean and standard deviation to center"
-      "and reduce samples before classification (produced by ComputeImagesStatistics application).");
+      "and reduce samples before classification, produced by ComputeImagesStatistics application.");
     MandatoryOff("instat");
 
     AddParameter(ParameterType_InputFilename, "model", "Model file");
-    SetParameterDescription("model", "A model file (produced by TrainVectorClassifier application,"
-      "maximal class label = 65535).");
+    SetParameterDescription("model", "Model file produced by TrainVectorClassifier application.");
 
-    AddParameter(ParameterType_String,"cfield","Field containing the predicted class");
+    AddParameter(ParameterType_String,"cfield","Field class");
     SetParameterDescription("cfield","Field containing the predicted class."
-      "Only geometries with this field available will be taken into account.");
+      "Only geometries with this field available will be taken into account.\n"
+      "The field is added either in the input file (if 'out' off) or in the output file.\n"
+      "Caution, the 'cfield' must not exist in the input file if you are updating the file.");
     SetParameterString("cfield","predicted", false);
 
-    AddParameter(ParameterType_ListView, "feat", "Field names to be calculated."); //
-    SetParameterDescription("feat","List of field names in the input vector data used as features for training."); //
+    AddParameter(ParameterType_ListView, "feat", "Field names to be calculated.");
+    SetParameterDescription("feat","List of field names in the input vector data used as features for training. "
+      "Put the same field names as the TrainVectorClassifier application.");
 
     AddParameter(ParameterType_Empty, "confmap",  "Confidence map");
-    SetParameterDescription( "confmap", "Confidence map of the produced classification. The confidence index depends on the model : \n"
-      "  - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n"
+    SetParameterDescription( "confmap", "Confidence map of the produced classification. "
+      "The confidence index depends on the model : \n"
+      "  - LibSVM : difference between the two highest probabilities "
+           "(needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n"
       "  - OpenCV\n"
       "    * Boost : sum of votes\n"
       "    * DecisionTree : (not supported)\n"
@@ -129,8 +142,9 @@ private:
       "    * KNearestNeighbors : number of neighbors with the same label\n"
       "    * NeuralNetwork : difference between the two highest responses\n"
       "    * NormalBayes : (not supported)\n"
-      "    * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n"
-      "    * SVM : distance to margin (only works for 2-class models)\n");
+      "    * RandomForest : Confidence (proportion of votes for the majority class). "
+             "Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n"
+      "    * SVM : distance to margin (only works for 2-class models).\n");
     MandatoryOff("confmap");
 
     AddParameter(ParameterType_OutputFilename, "out", "Output vector data file containing class labels");
@@ -142,7 +156,7 @@ private:
     SetDocExampleParameterValue("in", "vectorData.shp");
     SetDocExampleParameterValue("instat", "meanVar.xml");
     SetDocExampleParameterValue("model", "svmModel.svm");
-    SetDocExampleParameterValue("out", "svmModel.svm");
+    SetDocExampleParameterValue("out", "vectorDataLabeledVector.shp");
     SetDocExampleParameterValue("feat", "perimeter  area  width");
     SetDocExampleParameterValue("cfield", "predicted");
 
@@ -196,7 +210,7 @@ private:
 
     const int nbFeatures = GetSelectedItems("feat").size();
     input->SetMeasurementVectorSize(nbFeatures);
-
+  
     otb::ogr::Layer::const_iterator it = layer.cbegin();
     otb::ogr::Layer::const_iterator itEnd = layer.cend();
     for( ; it!=itEnd ; ++it)
@@ -205,7 +219,11 @@ private:
       mv.SetSize(nbFeatures);
       for(int idx=0; idx < nbFeatures; ++idx)
         {
-        mv[idx] = (*it)[GetSelectedItems("feat")[idx]].GetValue<double>();
+        // Beware that itemIndex differs from ogr layer field index
+        unsigned int itemIndex = GetSelectedItems("feat")[idx];
+        std::string fieldName = GetChoiceNames( "feat" )[itemIndex];
+        
+        mv[idx] = (*it)[fieldName].GetValue<double>();
         }
       input->PushBack(mv);
       }
diff --git a/Modules/Applications/AppClassification/include/otbTrainBoost.txx b/Modules/Applications/AppClassification/include/otbTrainBoost.txx
index 44093ecd5990eb1b8a7fad10ffe9f4c98dc0051d..46cbbbd12560b459c95a3264116ac189b75398fc 100644
--- a/Modules/Applications/AppClassification/include/otbTrainBoost.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainBoost.txx
@@ -39,11 +39,28 @@ namespace Wrapper
     //BoostType
     AddParameter(ParameterType_Choice, "classifier.boost.t", "Boost Type");
     AddChoice("classifier.boost.t.discrete", "Discrete AdaBoost");
-    AddChoice("classifier.boost.t.real", "Real AdaBoost (technique using confidence-rated predictions "
-                                                "and working well with categorical data)");
-    AddChoice("classifier.boost.t.logit", "LogitBoost (technique producing good regression fits)");
-    AddChoice("classifier.boost.t.gentle", "Gentle AdaBoost (technique setting less weight on outlier data points "
-                                               "and, for that reason, being often good with regression data)");
+    SetParameterDescription("classifier.boost.t.discrete",
+      "This procedure trains the classifiers on weighted versions of the training "
+      "sample, giving higher weight to cases that are currently misclassified. "
+      "This is done for a sequence of weighter samples, and then the final "
+      "classifier is defined as a linear combination of the classifier from "
+      "each stage.");
+    AddChoice("classifier.boost.t.real",
+      "Real AdaBoost (technique using confidence-rated predictions "
+      "and working well with categorical data)");
+    SetParameterDescription("classifier.boost.t.real",
+      "Adaptation of the Discrete Adaboost algorithm with Real value");
+    AddChoice("classifier.boost.t.logit",
+      "LogitBoost (technique producing good regression fits)");
+    SetParameterDescription("classifier.boost.t.logit",
+      "This procedure is an adaptive Newton algorithm for fitting an additive "
+      "logistic regression model. Beware it can produce numeric instability.");
+    AddChoice("classifier.boost.t.gentle",
+      "Gentle AdaBoost (technique setting less weight on outlier data points "
+      "and, for that reason, being often good with regression data)");
+    SetParameterDescription("classifier.boost.t.gentle",
+      "A modified version of the Real Adaboost algorithm, using Newton stepping "
+      "rather than exact optimization at each step.");
     SetParameterString("classifier.boost.t", "real", false);
     SetParameterDescription("classifier.boost.t", "Type of Boosting algorithm.");
     //Do not expose SplitCriteria
@@ -54,9 +71,11 @@ namespace Wrapper
     //WeightTrimRate
     AddParameter(ParameterType_Float, "classifier.boost.r", "Weight Trim Rate");
     SetParameterFloat("classifier.boost.r",0.95, false);
-    SetParameterDescription("classifier.boost.r","A threshold between 0 and 1 used to save computational time. "
-                            "Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. "
-                            "Set this parameter to 0 to turn off this functionality.");
+    SetParameterDescription("classifier.boost.r",
+      "A threshold between 0 and 1 used to save computational time. "
+      "Samples with summary weight <= (1 - weight_trim_rate) do not participate in"
+      " the next iteration of training. Set this parameter to 0 to turn off this "
+      "functionality.");
     //MaxDepth : Not sure that this parameter has to be exposed.
     AddParameter(ParameterType_Int, "classifier.boost.m", "Maximum depth of the tree");
     SetParameterInt("classifier.boost.m",1, false);
diff --git a/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx b/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx
index 3517791928b5d4be87c03d6e7ec72707f29d4525..9803a91a7a8a03f46f9b5bd8443d3d12a112926a 100644
--- a/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainDecisionTree.txx
@@ -35,8 +35,8 @@ LearningApplicationBase<TInputValue,TOutputValue>
 {
   AddChoice("classifier.dt", "Decision Tree classifier");
   SetParameterDescription("classifier.dt",
-                          "This group of parameters allows setting Decision Tree classifier parameters. "
-                          "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/decision_trees.html}.");
+    "This group of parameters allows setting Decision Tree classifier parameters. "
+    "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/decision_trees.html}.");
   //MaxDepth
   AddParameter(ParameterType_Int, "classifier.dt.max", "Maximum depth of the tree");
 #ifdef OTB_OPENCV_3
@@ -44,23 +44,25 @@ LearningApplicationBase<TInputValue,TOutputValue>
 #else
   SetParameterInt("classifier.dt.max",65535, false);
 #endif
-  SetParameterDescription(
-      "classifier.dt.max", "The training algorithm attempts to split each node while its depth is smaller than the maximum "
-      "possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or "
-      "if the tree is pruned.");
+  SetParameterDescription("classifier.dt.max",
+   "The training algorithm attempts to split each node while its depth is smaller "
+   "than the maximum possible depth of the tree. The actual depth may be smaller "
+   "if the other termination criteria are met, and/or if the tree is pruned.");
 
   //MinSampleCount
   AddParameter(ParameterType_Int, "classifier.dt.min", "Minimum number of samples in each node");
   SetParameterInt("classifier.dt.min",10, false);
-  SetParameterDescription("classifier.dt.min", "If the number of samples in a node is smaller than this parameter, "
-                          "then this node will not be split.");
+  SetParameterDescription("classifier.dt.min",
+    "If the number of samples in a node is smaller "
+    "than this parameter, then this node will not be split.");
 
   //RegressionAccuracy
   AddParameter(ParameterType_Float, "classifier.dt.ra", "Termination criteria for regression tree");
   SetParameterFloat("classifier.dt.ra",0.01, false);
-  SetParameterDescription("classifier.dt.min", "If all absolute differences between an estimated value in a node "
-                          "and the values of the train samples in this node are smaller than this regression accuracy parameter, "
-                          "then the node will not be split.");
+  SetParameterDescription("classifier.dt.ra",
+    "If all absolute differences between an estimated value in a node "
+    "and the values of the train samples in this node are smaller than this "
+    "regression accuracy parameter, then the node will not be split further.");
 
   //UseSurrogates : don't need to be exposed !
   //AddParameter(ParameterType_Empty, "classifier.dt.sur", "Surrogate splits will be built");
@@ -68,11 +70,12 @@ LearningApplicationBase<TInputValue,TOutputValue>
 
   //MaxCategories
   AddParameter(ParameterType_Int, "classifier.dt.cat",
-               "Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split");
+    "Cluster possible values of a categorical variable into K <= cat clusters to find a "
+    "suboptimal split");
   SetParameterInt("classifier.dt.cat",10, false);
-  SetParameterDescription(
-      "classifier.dt.cat",
-      "Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.");
+  SetParameterDescription("classifier.dt.cat",
+      "Cluster possible values of a categorical variable into K <= cat clusters to find a "
+      "suboptimal split.");
 
   //CVFolds
   AddParameter(ParameterType_Int, "classifier.dt.f", "K-fold cross-validations");
@@ -82,18 +85,20 @@ LearningApplicationBase<TInputValue,TOutputValue>
 #else
   SetParameterInt("classifier.dt.f",10, false);
 #endif
-  SetParameterDescription(
-      "classifier.dt.f", "If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.");
+  SetParameterDescription("classifier.dt.f",
+    "If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K "
+    "is equal to cv_folds.");
 
   //Use1seRule
   AddParameter(ParameterType_Empty, "classifier.dt.r", "Set Use1seRule flag to false");
-  SetParameterDescription(
-      "classifier.dt.r",
-      "If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.");
+  SetParameterDescription("classifier.dt.r",
+      "If true, then a pruning will be harsher. This will make a tree more compact and more "
+      "resistant to the training data noise but a bit less accurate.");
 
   //TruncatePrunedTree
   AddParameter(ParameterType_Empty, "classifier.dt.t", "Set TruncatePrunedTree flag to false");
-  SetParameterDescription("classifier.dt.t", "If true, then pruned branches are physically removed from the tree.");
+  SetParameterDescription("classifier.dt.t",
+    "If true, then pruned branches are physically removed from the tree.");
 
   //Priors are not exposed.
 
diff --git a/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx b/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx
index 82d5bd8410dad7927c42fdd7a091c63f7e6d930b..18b9f4d39a8926abf645647bec30273d2b98e3b5 100644
--- a/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainLibSVM.txx
@@ -103,7 +103,7 @@ namespace Wrapper
     SetParameterDescription("classifier.libsvm.nu",
         "Cost parameter Nu, in the range 0..1, the larger the value, "
         "the smoother the decision.");
-    
+
     // It seems that it miss a nu parameter for the nu-SVM use. 
     AddParameter(ParameterType_Empty, "classifier.libsvm.opt", "Parameters optimization");
     MandatoryOff("classifier.libsvm.opt");
@@ -120,11 +120,6 @@ namespace Wrapper
         "The distance between feature vectors from the training set and "
         "the fitting hyper-plane must be less than Epsilon. For outliers"
         "the penalty mutliplier is set by C.");
-      // AddParameter(ParameterType_Float, "classifier.libsvm.nu", "Nu");
-      // SetParameterFloat("classifier.libsvm.nu",0.5, false);
-      // SetParameterDescription("classifier.libsvm.nu", 
-      //   "Cost parameter Nu, in the range 0..1, the larger the value, "
-      //   "the smoother the decision.");
       }
   }
 
@@ -214,4 +209,4 @@ namespace Wrapper
 } //end namespace wrapper
 } //end namespace otb
 
-#endif
\ No newline at end of file
+#endif
diff --git a/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx b/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx
index fb8287c4996640bb745046f0b22955e9d79c15e0..2bcd26f3a7f08dbae692c8e36e75e6713e8bacc8 100644
--- a/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainNeuralNetwork.txx
@@ -36,95 +36,125 @@ LearningApplicationBase<TInputValue,TOutputValue>
 {
   AddChoice("classifier.ann", "Artificial Neural Network classifier");
   SetParameterDescription("classifier.ann",
-                          "This group of parameters allows setting Artificial Neural Network classifier parameters. "
-                          "See complete documentation here \\url{http://docs.opencv.org/modules/ml/doc/neural_networks.html}.");
+    "This group of parameters allows setting Artificial Neural Network "
+    "classifier parameters. See complete documentation here "
+    "\\url{http://docs.opencv.org/modules/ml/doc/neural_networks.html}.");
 
   //TrainMethod
   AddParameter(ParameterType_Choice, "classifier.ann.t", "Train Method Type");
-  AddChoice("classifier.ann.t.reg", "RPROP algorithm");
   AddChoice("classifier.ann.t.back", "Back-propagation algorithm");
+  SetParameterDescription("classifier.ann.t.back",
+    "Method to compute the gradient of the loss function and adjust weights "
+    "in the network to optimize the result.");
+  AddChoice("classifier.ann.t.reg", "Resilient Back-propagation algorithm");
+  SetParameterDescription("classifier.ann.t.reg",
+    "Almost the same as the Back-prop algorithm exept that it does not "
+    "take into account the magnitude of the partial derivative (coordinate "
+    "of the gradient) but only its sign.");
+
   SetParameterString("classifier.ann.t", "reg", false);
-  SetParameterDescription("classifier.ann.t", "Type of training method for the multilayer perceptron (MLP) neural network.");
+  SetParameterDescription("classifier.ann.t", 
+    "Type of training method for the multilayer perceptron (MLP) neural network.");
 
   //LayerSizes
   //There is no ParameterType_IntList, so i use a ParameterType_StringList and convert it.
   /*std::vector<std::string> layerSizes;
    layerSizes.push_back("100");
    layerSizes.push_back("100"); */
-  AddParameter(ParameterType_StringList, "classifier.ann.sizes", "Number of neurons in each intermediate layer");
+  AddParameter(ParameterType_StringList, "classifier.ann.sizes", 
+    "Number of neurons in each intermediate layer");
   //SetParameterStringList("classifier.ann.sizes", layerSizes);
   SetParameterDescription("classifier.ann.sizes",
-                          "The number of neurons in each intermediate layer (excluding input and output layers).");
+    "The number of neurons in each intermediate layer (excluding input and output layers).");
 
   //ActivateFunction
-  AddParameter(ParameterType_Choice, "classifier.ann.f", "Neuron activation function type");
+  AddParameter(ParameterType_Choice, "classifier.ann.f", 
+    "Neuron activation function type");
   AddChoice("classifier.ann.f.ident", "Identity function");
   AddChoice("classifier.ann.f.sig", "Symmetrical Sigmoid function");
   AddChoice("classifier.ann.f.gau", "Gaussian function (Not completely supported)");
   SetParameterString("classifier.ann.f", "sig", false);
-  SetParameterDescription("classifier.ann.f", "Neuron activation function.");
+  SetParameterDescription("classifier.ann.f", 
+    "This function determine whether the output of the node is positive or not "
+    "depending on the output of the transfert function.");
 
   //Alpha
-  AddParameter(ParameterType_Float, "classifier.ann.a", "Alpha parameter of the activation function");
+  AddParameter(ParameterType_Float, "classifier.ann.a", 
+    "Alpha parameter of the activation function");
   SetParameterFloat("classifier.ann.a",1., false);
   SetParameterDescription("classifier.ann.a",
-                          "Alpha parameter of the activation function (used only with sigmoid and gaussian functions).");
+    "Alpha parameter of the activation function (used only with sigmoid and gaussian functions).");
 
   //Beta
-  AddParameter(ParameterType_Float, "classifier.ann.b", "Beta parameter of the activation function");
+  AddParameter(ParameterType_Float, "classifier.ann.b", 
+    "Beta parameter of the activation function");
   SetParameterFloat("classifier.ann.b",1., false);
   SetParameterDescription("classifier.ann.b",
-                          "Beta parameter of the activation function (used only with sigmoid and gaussian functions).");
+    "Beta parameter of the activation function (used only with sigmoid and gaussian functions).");
 
   //BackPropDWScale
   AddParameter(ParameterType_Float, "classifier.ann.bpdw",
-               "Strength of the weight gradient term in the BACKPROP method");
+    "Strength of the weight gradient term in the BACKPROP method");
   SetParameterFloat("classifier.ann.bpdw",0.1, false);
-  SetParameterDescription(
-      "classifier.ann.bpdw",
-      "Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.");
+  SetParameterDescription("classifier.ann.bpdw",
+    "Strength of the weight gradient term in the BACKPROP method. The "
+    "recommended value is about 0.1.");
 
   //BackPropMomentScale
   AddParameter(ParameterType_Float, "classifier.ann.bpms",
-               "Strength of the momentum term (the difference between weights on the 2 previous iterations)");
+    "Strength of the momentum term (the difference between weights on the 2 previous iterations)");
   SetParameterFloat("classifier.ann.bpms",0.1, false);
-  SetParameterDescription(
-      "classifier.ann.bpms",
-      "Strength of the momentum term (the difference between weights on the 2 previous iterations). "
-      "This parameter provides some inertia to smooth the random fluctuations of the weights. "
-      "It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.");
+  SetParameterDescription("classifier.ann.bpms",
+    "Strength of the momentum term (the difference between weights on the 2 previous "
+    "iterations). This parameter provides some inertia to smooth the random "
+    "fluctuations of the weights. It can vary from 0 (the feature is disabled) "
+    "to 1 and beyond. The value 0.1 or so is good enough.");
 
   //RegPropDW0
   AddParameter(ParameterType_Float, "classifier.ann.rdw",
-               "Initial value Delta_0 of update-values Delta_{ij} in RPROP method");
+    "Initial value Delta_0 of update-values Delta_{ij} in RPROP method");
   SetParameterFloat("classifier.ann.rdw",0.1, false);
-  SetParameterDescription("classifier.ann.rdw", "Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).");
+  SetParameterDescription("classifier.ann.rdw",
+    "Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).");
 
   //RegPropDWMin
-  AddParameter(ParameterType_Float, "classifier.ann.rdwm", "Update-values lower limit Delta_{min} in RPROP method");
+  AddParameter(ParameterType_Float, "classifier.ann.rdwm",
+    "Update-values lower limit Delta_{min} in RPROP method");
   SetParameterFloat("classifier.ann.rdwm",1e-7, false);
-  SetParameterDescription(
-      "classifier.ann.rdwm",
-      "Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).");
+  SetParameterDescription("classifier.ann.rdwm",
+    "Update-values lower limit Delta_{min} in RPROP method. It must be positive "
+    "(default = 1e-7).");
 
   //TermCriteriaType
   AddParameter(ParameterType_Choice, "classifier.ann.term", "Termination criteria");
   AddChoice("classifier.ann.term.iter", "Maximum number of iterations");
+  SetParameterDescription("classifier.ann.term.iter", 
+    "Set the number of iterations allowed to the network for its "
+    "training. Training will stop regardless of the result when this "
+    "number is reached");
   AddChoice("classifier.ann.term.eps", "Epsilon");
+  SetParameterDescription("classifier.ann.term.eps", 
+    "Training will focus on result and will stop once the precision is"
+    "at most epsilon");
   AddChoice("classifier.ann.term.all", "Max. iterations + Epsilon");
+  SetParameterDescription("classifier.ann.term.all", 
+    "Both termination criteria are used. Training stop at the first reached");
   SetParameterString("classifier.ann.term", "all", false);
   SetParameterDescription("classifier.ann.term", "Termination criteria.");
 
   //Epsilon
-  AddParameter(ParameterType_Float, "classifier.ann.eps", "Epsilon value used in the Termination criteria");
+  AddParameter(ParameterType_Float, "classifier.ann.eps",
+    "Epsilon value used in the Termination criteria");
   SetParameterFloat("classifier.ann.eps",0.01, false);
-  SetParameterDescription("classifier.ann.eps", "Epsilon value used in the Termination criteria.");
+  SetParameterDescription("classifier.ann.eps",
+    "Epsilon value used in the Termination criteria.");
 
   //MaxIter
   AddParameter(ParameterType_Int, "classifier.ann.iter",
-               "Maximum number of iterations used in the Termination criteria");
+    "Maximum number of iterations used in the Termination criteria");
   SetParameterInt("classifier.ann.iter",1000, false);
-  SetParameterDescription("classifier.ann.iter", "Maximum number of iterations used in the Termination criteria.");
+  SetParameterDescription("classifier.ann.iter",
+    "Maximum number of iterations used in the Termination criteria.");
 
 }
 
@@ -143,12 +173,12 @@ LearningApplicationBase<TInputValue,TOutputValue>
 
   switch (GetParameterInt("classifier.ann.t"))
     {
-    case 0: // RPROP
-      classifier->SetTrainMethod(CvANN_MLP_TrainParams::RPROP);
-      break;
-    case 1: // BACKPROP
+    case 0: // BACKPROP
       classifier->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);
       break;
+    case 1: // RPROP
+      classifier->SetTrainMethod(CvANN_MLP_TrainParams::RPROP);
+      break;
     default: // DEFAULT = RPROP
       classifier->SetTrainMethod(CvANN_MLP_TrainParams::RPROP);
       break;
diff --git a/Modules/Applications/AppClassification/include/otbTrainSVM.txx b/Modules/Applications/AppClassification/include/otbTrainSVM.txx
index 4c4729e7c5b1cea810941871b6ac37a06ff97aff..ac9524faa26de64a04e4a98b008b101f225cc8ca 100644
--- a/Modules/Applications/AppClassification/include/otbTrainSVM.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainSVM.txx
@@ -53,6 +53,7 @@ namespace Wrapper
       }
     AddParameter(ParameterType_Choice, "classifier.svm.k", "SVM Kernel Type");
     AddChoice("classifier.svm.k.linear", "Linear");
+
     AddChoice("classifier.svm.k.rbf", "Gaussian radial basis function");
     AddChoice("classifier.svm.k.poly", "Polynomial");
     AddChoice("classifier.svm.k.sigmoid", "Sigmoid");
@@ -60,52 +61,71 @@ namespace Wrapper
     SetParameterDescription("classifier.svm.k", "SVM Kernel Type.");
     AddParameter(ParameterType_Float, "classifier.svm.c", "Cost parameter C");
     SetParameterFloat("classifier.svm.c",1.0, false);
-    SetParameterDescription(
-        "classifier.svm.c",
-        "SVM models have a cost parameter C (1 by default) to control the trade-off between training errors and forcing rigid margins.");
+    SetParameterDescription("classifier.svm.c",
+        "SVM models have a cost parameter C (1 by default) to control the trade-off"
+        " between training errors and forcing rigid margins.");
     AddParameter(ParameterType_Float, "classifier.svm.nu",
                  "Parameter nu of a SVM optimization problem (NU_SVC / ONE_CLASS)");
     SetParameterFloat("classifier.svm.nu",0.0, false);
-    SetParameterDescription("classifier.svm.nu", "Parameter nu of a SVM optimization problem.");
+    SetParameterDescription("classifier.svm.nu", 
+      "Parameter nu of a SVM optimization problem.");
     if (this->m_RegressionFlag)
       {
       AddParameter(ParameterType_Float, "classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)");
       SetParameterFloat("classifier.svm.p",1.0, false);
       SetParameterDescription("classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR).");
 
-      AddParameter(ParameterType_Choice, "classifier.svm.term", "Termination criteria");
-      SetParameterDescription("classifier.svm.term","Termination criteria for iterative algorithm");
-      AddChoice("classifier.svm.term.iter", "Stops when maximum iteration is reached.");
-      AddChoice("classifier.svm.term.eps", "Stops when accuracy is lower than epsilon.");
-      AddChoice("classifier.svm.term.all", "Stops when either iteration or epsilon criteria is true");
+      AddParameter(ParameterType_Choice, 
+        "classifier.svm.term", "Termination criteria");
+      SetParameterDescription("classifier.svm.term",
+        "Termination criteria for iterative algorithm");
+      AddChoice("classifier.svm.term.iter", 
+        "Stops when maximum iteration is reached.");
+      AddChoice("classifier.svm.term.eps", 
+        "Stops when accuracy is lower than epsilon.");
+      AddChoice("classifier.svm.term.all", 
+        "Stops when either iteration or epsilon criteria is true");
 
       AddParameter(ParameterType_Float, "classifier.svm.iter", "Maximum iteration");
       SetParameterFloat("classifier.svm.iter",1000, false);
-      SetParameterDescription("classifier.svm.iter", "Maximum number of iterations (corresponds to the termination criteria 'iter').");
+      SetParameterDescription("classifier.svm.iter", 
+        "Maximum number of iterations (corresponds to the termination criteria 'iter').");
 
-      AddParameter(ParameterType_Float, "classifier.svm.eps", "Epsilon accuracy threshold");
+      AddParameter(ParameterType_Float, "classifier.svm.eps", 
+        "Epsilon accuracy threshold");
       SetParameterFloat("classifier.svm.eps",FLT_EPSILON, false);
-      SetParameterDescription("classifier.svm.eps", "Epsilon accuracy (corresponds to the termination criteria 'eps').");
+      SetParameterDescription("classifier.svm.eps", 
+        "Epsilon accuracy (corresponds to the termination criteria 'eps').");
       }
-    AddParameter(ParameterType_Float, "classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID)");
+    AddParameter(ParameterType_Float, "classifier.svm.coef0", 
+      "Parameter coef0 of a kernel function (POLY / SIGMOID)");
     SetParameterFloat("classifier.svm.coef0",0.0, false);
-    SetParameterDescription("classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID).");
+    SetParameterDescription("classifier.svm.coef0", 
+      "Parameter coef0 of a kernel function (POLY / SIGMOID).");
     AddParameter(ParameterType_Float, "classifier.svm.gamma",
                  "Parameter gamma of a kernel function (POLY / RBF / SIGMOID)");
     SetParameterFloat("classifier.svm.gamma",1.0, false);
-    SetParameterDescription("classifier.svm.gamma", "Parameter gamma of a kernel function (POLY / RBF / SIGMOID).");
-    AddParameter(ParameterType_Float, "classifier.svm.degree", "Parameter degree of a kernel function (POLY)");
+    SetParameterDescription("classifier.svm.gamma", 
+      "Parameter gamma of a kernel function (POLY / RBF / SIGMOID).");
+    AddParameter(ParameterType_Float, "classifier.svm.degree", 
+      "Parameter degree of a kernel function (POLY)");
     SetParameterFloat("classifier.svm.degree",1.0, false);
-    SetParameterDescription("classifier.svm.degree", "Parameter degree of a kernel function (POLY).");
-    AddParameter(ParameterType_Empty, "classifier.svm.opt", "Parameters optimization");
+    SetParameterDescription("classifier.svm.degree", 
+      "Parameter degree of a kernel function (POLY).");
+    AddParameter(ParameterType_Empty, "classifier.svm.opt", 
+      "Parameters optimization");
     MandatoryOff("classifier.svm.opt");
-    SetParameterDescription("classifier.svm.opt", "SVM parameters optimization flag.\n-If set to True, then the optimal SVM parameters will be estimated. "
-                            "Parameters are considered optimal by OpenCV when the cross-validation estimate of the test set error is minimal. "
-                            "Finally, the SVM training process is computed 10 times with these optimal parameters over subsets corresponding to 1/10th of "
-                            "the training samples using the k-fold cross-validation (with k = 10).\n-If set to False, the SVM classification process will be "
-                            "computed once with the currently set input SVM parameters over the training samples.\n-Thus, even with identical input SVM "
-                            "parameters and a similar random seed, the output SVM models will be different according to the method used (optimized or not) "
-                            "because the samples are not identically processed within OpenCV.");
+    SetParameterDescription("classifier.svm.opt", "SVM parameters optimization flag.\n"
+      "-If set to True, then the optimal SVM parameters will be estimated. "
+      "Parameters are considered optimal by OpenCV when the cross-validation estimate of "
+      "the test set error is minimal. Finally, the SVM training process is computed "
+      "10 times with these optimal parameters over subsets corresponding to 1/10th of "
+      "the training samples using the k-fold cross-validation (with k = 10).\n-If set "
+      "to False, the SVM classification process will be computed once with the "
+      "currently set input SVM parameters over the training samples.\n-Thus, even "
+      "with identical input SVM parameters and a similar random seed, the output "
+      "SVM models will be different according to the method used (optimized or not) "
+      "because the samples are not identically processed within OpenCV.");
   }
 
   template <class TInputValue, class TOutputValue>
diff --git a/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx b/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx
index e24c4165de2b6a1b1bf57c672e5ec69a1ef825a2..2c3575c2ead20381438f9f66d5cd9c65c1723132 100644
--- a/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx
+++ b/Modules/Applications/AppClassification/include/otbTrainVectorBase.txx
@@ -31,54 +31,70 @@ void TrainVectorBase::DoInit()
 {
   // Common Parameters for all Learning Application
   AddParameter( ParameterType_Group, "io", "Input and output data" );
-  SetParameterDescription( "io", "This group of parameters allows setting input and output data." );
+  SetParameterDescription( "io", 
+    "This group of parameters allows setting input and output data." );
 
   AddParameter( ParameterType_InputVectorDataList, "io.vd", "Input Vector Data" );
   SetParameterDescription( "io.vd",
-                           "Input geometries used for training (note : all geometries from the layer will be used)" );
+    "Input geometries used for training (note : all geometries from the layer will be used)" );
 
   AddParameter( ParameterType_InputFilename, "io.stats", "Input XML image statistics file" );
   MandatoryOff( "io.stats" );
-  SetParameterDescription( "io.stats", "XML file containing mean and variance of each feature." );
+  SetParameterDescription( "io.stats", 
+    "XML file containing mean and variance of each feature." );
 
   AddParameter( ParameterType_OutputFilename, "io.out", "Output model" );
-  SetParameterDescription( "io.out", "Output file containing the model estimated (.txt format)." );
+  SetParameterDescription( "io.out", 
+    "Output file containing the model estimated (.txt format)." );
 
   AddParameter( ParameterType_Int, "layer", "Layer Index" );
-  SetParameterDescription( "layer", "Index of the layer to use in the input vector file." );
+  SetParameterDescription( "layer", 
+    "Index of the layer to use in the input vector file." );
   MandatoryOff( "layer" );
   SetDefaultParameterInt( "layer", 0 );
 
   AddParameter(ParameterType_ListView,  "feat", "Field names for training features.");
-  SetParameterDescription("feat","List of field names in the input vector data to be used as features for training.");
+  SetParameterDescription("feat",
+    "List of field names in the input vector data to be used as features for training.");
 
   // Add validation data used to compute confusion matrix or contingency table
   AddParameter( ParameterType_Group, "valid", "Validation data" );
-  SetParameterDescription( "valid", "This group of parameters defines validation data." );
+  SetParameterDescription( "valid", 
+    "This group of parameters defines validation data." );
 
-  AddParameter( ParameterType_InputVectorDataList, "valid.vd", "Validation Vector Data" );
+  AddParameter( ParameterType_InputVectorDataList, "valid.vd", 
+    "Validation Vector Data" );
   SetParameterDescription( "valid.vd", "Geometries used for validation "
           "(must contain the same fields used for training, all geometries from the layer will be used)" );
   MandatoryOff( "valid.vd" );
 
   AddParameter( ParameterType_Int, "valid.layer", "Layer Index" );
-  SetParameterDescription( "valid.layer", "Index of the layer to use in the validation vector file." );
+  SetParameterDescription( "valid.layer", 
+    "Index of the layer to use in the validation vector file." );
   MandatoryOff( "valid.layer" );
   SetDefaultParameterInt( "valid.layer", 0 );
 
   // Add class field if we used validation
-  AddParameter( ParameterType_ListView, "cfield", "Field containing the class integer label for supervision" );
-  SetParameterDescription( "cfield", "Field containing the class id for supervision. "
-          "The values in this field shall be cast into integers. "
-          "Only geometries with this field available will be taken into account." );
+  AddParameter( ParameterType_ListView, "cfield",
+    "Field containing the class integer label for supervision" );
+  SetParameterDescription( "cfield", 
+    "Field containing the class id for supervision. "
+    "The values in this field shall be cast into integers. "
+    "Only geometries with this field available will be taken into account." );
   SetListViewSingleSelectionMode( "cfield", true );
 
   // Add a new parameter to compute confusion matrix / contingency table
-  AddParameter( ParameterType_OutputFilename, "io.confmatout", "Output confusion matrix or contingency table" );
-  SetParameterDescription( "io.confmatout", "Output file containing the confusion matrix or contingency table (.csv format)."
-          "The contingency table is output when we unsupervised algorithms is used otherwise the confusion matrix is output." );
+  AddParameter( ParameterType_OutputFilename, "io.confmatout", 
+    "Output confusion matrix or contingency table" );
+  SetParameterDescription( "io.confmatout", 
+    "Output file containing the confusion matrix or contingency table (.csv format)."
+    "The contingency table is output when we unsupervised algorithms is used otherwise the confusion matrix is output." );
   MandatoryOff( "io.confmatout" );
 
+  AddParameter(ParameterType_Empty, "v", "Verbose mode");
+  EnableParameter("v");
+  SetParameterDescription("v", "Verbose mode, display the contingency table result.");
+  MandatoryOff("v");
 
   // Doc example parameter settings
   SetDocExampleParameterValue( "io.vd", "vectorData.shp" );
@@ -273,7 +289,7 @@ TrainVectorBase::ExtractSamplesWithLabel(std::string parameterName, std::string
 
         input->PushBack( mv );
 
-        if( feature.ogr().IsFieldSet( cFieldIndex ) && cFieldIndex != -1 )
+        if(cFieldIndex>=0 && ogr::Field(feature,cFieldIndex).HasBeenSet())
           target->PushBack( feature.ogr().GetFieldAsInteger( cFieldIndex ) );
         else
           target->PushBack( 0 );
diff --git a/Modules/Applications/AppClassification/otb-module.cmake b/Modules/Applications/AppClassification/otb-module.cmake
index ca0c9281275d233b7dcb441d667fb295d5580755..efd9cb32d789831e5b673f398ea2af866cf29503 100644
--- a/Modules/Applications/AppClassification/otb-module.cmake
+++ b/Modules/Applications/AppClassification/otb-module.cmake
@@ -53,6 +53,7 @@ otb_module(OTBAppClassification
   TEST_DEPENDS
     OTBTestKernel
     OTBCommandLine
+    OTBAppProjection
 
   DESCRIPTION
     "${DOCUMENTATION}"
diff --git a/Modules/Applications/AppClassification/test/CMakeLists.txt b/Modules/Applications/AppClassification/test/CMakeLists.txt
index aa7e33d744d5eda1191e327bcc5ea8afe13da102..fae1474266db959a03a6accd01b14b43f00f4ec0 100644
--- a/Modules/Applications/AppClassification/test/CMakeLists.txt
+++ b/Modules/Applications/AppClassification/test/CMakeLists.txt
@@ -629,20 +629,24 @@ if(OTB_DATA_USE_LARGEINPUT)
 endif()
 
 #----------- KMeansClassification TESTS ----------------
-otb_test_application(NAME apTvClKMeansImageClassification
-  APP  KMeansClassification
-  OPTIONS -in ${INPUTDATA}/qb_RoadExtract.img
-  -vm ${INPUTDATA}/qb_RoadExtract_mask.png
-  -ts 30000
-  -nc 5
-  -maxit 10000
-  -ct 0.0000001
-  -rand 121212
-  -out ${TEMP}/apTvClKMeansImageClassificationFilterOutput.tif
-  VALID   --compare-image ${NOTOL}
-  ${OTBAPP_BASELINE}/apTvClKMeansImageClassificationFilterOutput.tif
-  ${TEMP}/apTvClKMeansImageClassificationFilterOutput.tif )
-
+if(OTB_USE_SHARK)
+  otb_test_application(NAME apTvClKMeansImageClassification_composite
+    APP  KMeansClassification
+    OPTIONS -in ${INPUTDATA}/qb_RoadExtract.img
+    -vm ${INPUTDATA}/qb_RoadExtract_mask_binary.png
+    -ts 30000
+    -nc 5
+    -maxit 10000
+    -sampler periodic
+    -rand 121212
+    -nodatalabel 255
+    -outmeans ${TEMP}/apTvClKMeansImageClassificationFilterOutMeans.txt
+    -out ${TEMP}/apTvClKMeansImageClassificationFilterOutput.tif uint8
+    -cleanup 0
+    VALID   --compare-image ${NOTOL}
+    ${OTBAPP_BASELINE}/apTvClKMeansImageClassificationFilterOutput.tif
+    ${TEMP}/apTvClKMeansImageClassificationFilterOutput.tif )
+endif()
 
 #----------- TrainImagesClassifier TESTS ----------------
 if(OTB_USE_LIBSVM)
diff --git a/Modules/Applications/AppEdge/app/otbEdgeExtraction.cxx b/Modules/Applications/AppEdge/app/otbEdgeExtraction.cxx
index c4bcb9841cc0e87bcc760520165ef7913a27c5e9..a608338ddefab721dc1c8b0a4f0f0b6f035f8c49 100644
--- a/Modules/Applications/AppEdge/app/otbEdgeExtraction.cxx
+++ b/Modules/Applications/AppEdge/app/otbEdgeExtraction.cxx
@@ -64,11 +64,16 @@ private:
 void DoInit() ITK_OVERRIDE
 {
 SetName("EdgeExtraction");
-SetDescription("Computes edge features on every pixel of the input image selected channel");
+SetDescription(
+  "This application computes edge features on every pixel of the input image "
+  "selected channel");
 
 // Documentation
 SetDocName("Edge Feature Extraction");
-SetDocLongDescription("This application computes edge features on a mono band image");
+SetDocLongDescription(
+  "This application computes edge features on a selected channel of the input."
+  "It uses different filter such as gradient, Sobel and Touzi");
+
 SetDocLimitations("None");
 SetDocAuthors("OTB-Team");
 SetDocSeeAlso("otb class");
@@ -77,7 +82,7 @@ AddDocTag(Tags::FeatureExtraction);
 AddDocTag("Edge");
 
 AddParameter(ParameterType_InputImage, "in",  "Input Image");
-SetParameterDescription("in", "The input image to compute the features on.");
+SetParameterDescription("in", "The input image on which the features are computed.");
 
 AddParameter(ParameterType_Int,  "channel",  "Selected Channel");
 SetParameterDescription("channel", "The selected channel index");
@@ -91,15 +96,26 @@ SetParameterDescription("filter", "Choice of edge feature");
 
 //Gradient Section
 AddChoice("filter.gradient", "Gradient");
+SetParameterDescription("filter.gradient", 
+  "This filter computes the gradient magnitude of the image at each pixel.");
 
 //Sobel Section
 AddChoice("filter.sobel", "Sobel");
+SetParameterDescription("filter.sobel", 
+  "This filter uses the Sobel operator to calculate the image gradient and "
+  "then finds the magnitude of this gradient vector.");
 
 //Touzi Section
 AddChoice("filter.touzi", "Touzi");
-AddParameter(ParameterType_Int, "filter.touzi.xradius", "The X Radius");
+SetParameterDescription("filter.touzi", 
+  "This filter is more suited for radar images. It has a spatial parameter "
+  "to avoid speckle noise perturbations. The larger the radius is, "
+  "less sensible to the speckle noise the filter is, but micro edge will be missed.");
+AddParameter(ParameterType_Int, "filter.touzi.xradius", 
+  "The X radius of the neighborhood.");
 SetDefaultParameterInt("filter.touzi.xradius", 1);
-AddParameter(ParameterType_Int, "filter.touzi.yradius", "The Y Radius");
+AddParameter(ParameterType_Int, "filter.touzi.yradius", 
+  "The Y radius of the neighborhood.");
 SetDefaultParameterInt("filter.touzi.yradius", 1);
 
 //Canny Section
diff --git a/Modules/Applications/AppEdge/app/otbLineSegmentDetection.cxx b/Modules/Applications/AppEdge/app/otbLineSegmentDetection.cxx
index 65eb71689cf5a51cb89610765d5a7b427cc44f6b..b9eccc12eb2f02004ffe1f2156ebd65bdb55d53f 100644
--- a/Modules/Applications/AppEdge/app/otbLineSegmentDetection.cxx
+++ b/Modules/Applications/AppEdge/app/otbLineSegmentDetection.cxx
@@ -60,10 +60,19 @@ private:
 
     // Documentation
     SetDocName("Line segment detection");
-    SetDocLongDescription("This application detects locally straight contours in a image. It is based on Burns, Hanson, and Riseman method and use an a contrario validation approach (Desolneux, Moisan, and Morel). The algorithm was published by Rafael Gromponevon Gioi, Jérémie Jakubowicz, Jean-Michel Morel and Gregory Randall.\n The given approach computes gradient and level lines of the image and detects aligned points in line support region. The application allows exporting the detected lines in a vector data.");
+    SetDocLongDescription(
+      "This application detects locally straight contours in a image."
+      " It is based on Burns, Hanson, and Riseman method and use an a contrario "
+      "validation approach (Desolneux, Moisan, and Morel). The algorithm was published "
+      "by Rafael Gromponevon Gioi, Jérémie Jakubowicz, Jean-Michel Morel and "
+      "Gregory Randall. The given approach computes gradient and level lines of the "
+      "image and detects aligned points in line support region. "
+      "The application allows exporting the detected lines in a vector data.");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso("On Line demonstration of the LSD algorithm is available here: http://www.ipol.im/pub/algo/gjmr_line_segment_detector/\n");
+    SetDocSeeAlso(
+      "On Line demonstration of the LSD algorithm is available here: "
+      "http://www.ipol.im/pub/algo/gjmr_line_segment_detector/\n");
 
     AddDocTag(Tags::FeatureExtraction);
 
@@ -77,7 +86,9 @@ private:
     ElevationParametersHandler::AddElevationParameters(this, "elev");
 
     AddParameter(ParameterType_Empty, "norescale", "No rescaling in [0, 255]");
-    SetParameterDescription("norescale","By default, the input image amplitude is rescaled between [0,255]. Turn on this parameter to skip rescaling");
+    SetParameterDescription("norescale",
+      "By default, the input image amplitude is rescaled between [0,255]."
+      " Turn on this parameter to skip rescaling");
     MandatoryOff("norescale");
 
     AddRAMParameter();
diff --git a/Modules/Applications/AppFiltering/app/CMakeLists.txt b/Modules/Applications/AppFiltering/app/CMakeLists.txt
index 9d58ba674f60c2fcc463948685f54a9a496b3429..d7f3dcd0c3c1ce9a06b5b50bc3d4293d9e4adbcc 100644
--- a/Modules/Applications/AppFiltering/app/CMakeLists.txt
+++ b/Modules/Applications/AppFiltering/app/CMakeLists.txt
@@ -19,17 +19,11 @@
 #
 
 set(OTBAppFiltering_LINK_LIBS
-  ${OTBImageNoise_LIBRARIES}
   ${OTBImageManipulation_LIBRARIES}
   ${OTBApplicationEngine_LIBRARIES}
   ${OTBImageBase_LIBRARIES}
 )
 
-otb_create_application(
-  NAME           Despeckle
-  SOURCES        otbDespeckle.cxx
-  LINK_LIBRARIES ${${otb-module}_LIBRARIES})
-
 otb_create_application(
   NAME           Smoothing
   SOURCES        otbSmoothing.cxx
diff --git a/Modules/Applications/AppFiltering/otb-module.cmake b/Modules/Applications/AppFiltering/otb-module.cmake
index d33a9eec90a461aadf2223cf63e60eaa5b10c4ff..5e8fc45196bb23ef0d7e19e6c062b7d7a5d3a5a2 100644
--- a/Modules/Applications/AppFiltering/otb-module.cmake
+++ b/Modules/Applications/AppFiltering/otb-module.cmake
@@ -18,11 +18,10 @@
 # limitations under the License.
 #
 
-set(DOCUMENTATION "Basic filters application.")
+set(DOCUMENTATION "Image filtering application.")
 
 otb_module(OTBAppFiltering
   DEPENDS
-    OTBImageNoise
     OTBImageManipulation
     OTBITK
     OTBApplicationEngine
diff --git a/Modules/Applications/AppFiltering/test/CMakeLists.txt b/Modules/Applications/AppFiltering/test/CMakeLists.txt
index f88934a0c03ebb59f837240e7482344f8254f3e0..9c4a8026882033f886e31cc4d222c21945eb3f1c 100644
--- a/Modules/Applications/AppFiltering/test/CMakeLists.txt
+++ b/Modules/Applications/AppFiltering/test/CMakeLists.txt
@@ -19,8 +19,6 @@
 #
 
 otb_module_test()
-#----------- Despeckle TESTS ----------------
-
 #----------- Smoothing TESTS ----------------
 otb_test_application(NAME  apTvUtSmoothingTest_InXML
                      APP  Smoothing
@@ -52,46 +50,4 @@ otb_test_application(NAME  apTvUtSmoothingTest_OutXML
                              ${TEMP}/apTvUtSmoothingTest_OutXML.tif)
                              
                              
-otb_test_application(NAME  apTvDespeckleLee
-                     APP  Despeckle
-                     OPTIONS -in ${INPUTDATA}/GomaAvant.tif
-               	             -out ${TEMP}/bfFiltreLee_05_05_12_app.tif
-                             -filter lee
-                             -filter.lee.rad 5
-                             -filter.lee.nblooks 12
-                     VALID   --compare-image ${EPSILON_7}
-                             ${BASELINE}/bfFiltreLee_05_05_12.tif
-                             ${TEMP}/bfFiltreLee_05_05_12_app.tif)
-                             
-otb_test_application(NAME  apTvDespeckleFrost
-                     APP  Despeckle
-                     OPTIONS -in ${INPUTDATA}/GomaAvant.tif
-               	             -out ${TEMP}/bfFiltreFrost_05_05_12_app.tif
-                             -filter frost
-                             -filter.frost.rad 5
-                             -filter.frost.deramp 0.1
-                     VALID   --compare-image ${EPSILON_7}
-                             ${BASELINE}/bfFiltreFrost_05_05_12_app.tif
-                             ${TEMP}/bfFiltreFrost_05_05_12_app.tif)
 
-otb_test_application(NAME  apTvDespeckleGammaMAP
-                     APP  Despeckle
-                     OPTIONS -in ${INPUTDATA}/GomaAvant.tif
-               	             -out ${TEMP}/bfFiltreGammaMAP_05_05_12_app.tif
-                             -filter gammamap
-                             -filter.gammamap.rad 5
-                             -filter.gammamap.nblooks 12
-                     VALID   --compare-image ${EPSILON_7}
-                             ${BASELINE}/bfFiltreGammaMAP_05_05_12.tif
-                             ${TEMP}/bfFiltreGammaMAP_05_05_12_app.tif)                      
-                             
-otb_test_application(NAME  apTvDespeckleKuan
-                     APP  Despeckle
-                     OPTIONS -in ${INPUTDATA}/GomaAvant.tif
-               	             -out ${TEMP}/bfFiltreKuan_05_05_12_app.tif
-                             -filter kuan
-                             -filter.kuan.rad 5
-                             -filter.kuan.nblooks 12
-                     VALID   --compare-image ${EPSILON_7}
-                             ${BASELINE}/bfFiltreKuan_05_05_12.tif
-                             ${TEMP}/bfFiltreKuan_05_05_12_app.tif)
diff --git a/Modules/Applications/AppFusion/app/CMakeLists.txt b/Modules/Applications/AppFusion/app/CMakeLists.txt
index a75c4ca00da7b4805a004aea9757694f8a1f2903..1e7a0eb91559fd30e65a87870e8af08f661c6307 100644
--- a/Modules/Applications/AppFusion/app/CMakeLists.txt
+++ b/Modules/Applications/AppFusion/app/CMakeLists.txt
@@ -35,3 +35,6 @@ otb_create_application(
   NAME           Pansharpening
   SOURCES        otbPansharpening.cxx
   LINK_LIBRARIES ${${otb-module}_LIBRARIES})
+
+# Mantis-1427 : temporary fix
+add_dependencies(${otb-module}-all otbapp_Superimpose)
diff --git a/Modules/Applications/AppHyperspectral/app/otbHyperspectralUnmixing.cxx b/Modules/Applications/AppHyperspectral/app/otbHyperspectralUnmixing.cxx
index a16a00b234aae826d1df74d828868b7c40ec99ef..3ed9b7c18996e89e4be9c11a0e942a334d4e0077 100644
--- a/Modules/Applications/AppHyperspectral/app/otbHyperspectralUnmixing.cxx
+++ b/Modules/Applications/AppHyperspectral/app/otbHyperspectralUnmixing.cxx
@@ -95,22 +95,37 @@ private:
 
     // Documentation
     SetDocName("Hyperspectral data unmixing");
-    SetDocLongDescription("The application applies a linear unmixing algorithm to an hyperspectral data cube. This method supposes that the mixture between materials in the scene is macroscopic and simulates a linear mixing model of spectra.\nThe Linear Mixing Model (LMM) acknowledges that reflectance spectrum associated with each pixel is a linear combination of pure materials in the recovery area, commonly known as endmembers. Endmembers can be estimated using the VertexComponentAnalysis application.\nThe application allows one to estimate the abundance maps with several algorithms : Unconstrained Least Square (ucls), Fully Constrained Least Square (fcls), Image Space Reconstruction Algorithm (isra) and Non-negative constrained Least Square (ncls) and Minimum Dispersion Constrained Non Negative Matrix Factorization (MDMDNMF).\n");
+    SetDocLongDescription("The application applies a linear unmixing algorithm"
+    "to an hyperspectral data cube. This method supposes that the mixture between"
+    "aterials in the scene is macroscopic and simulates a linear mixing model of"
+    "spectra.\n\n"
+    "The Linear Mixing Model (LMM) acknowledges that reflectance"
+    "spectrum associated with each pixel is a linear combination of pure"
+    "materials in the recovery area, commonly known as endmembers. Endmembers can"
+    "be estimated using the VertexComponentAnalysis application.\n\n"
+    "The application allows to estimate the abundance maps with several algorithms :\n"
+    "  * Unconstrained Least Square (ucls)\n"
+                          //"  * Fully Constrained Least Square (fcls)\n"
+    "  * Image Space Reconstruction Algorithm (isra)\n"
+    "  * Non-negative constrained\n"
+    "  * Least Square (ncls)\n"
+    "  * Minimum Dispersion Constrained Non Negative Matrix Factorization (MDMDNMF)."
+    );
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso("VertexComponentAnalysis");
 
-	AddDocTag("Miscellaneous");
+    AddDocTag("Miscellaneous");
     AddDocTag(Tags::Hyperspectral);
 
     AddParameter(ParameterType_InputImage,  "in",   "Input Image Filename");
-    SetParameterDescription("in","The hyperspectral data cube to unmix");
+    SetParameterDescription("in","The hyperspectral data cube input");
 
     AddParameter(ParameterType_OutputImage, "out",  "Output Image");
-    SetParameterDescription("out","The output abundance map");
+    SetParameterDescription("out","The output abundance map. The abundance fraction are stored in a multispectral image where band N corresponds to the fraction of endmembers N in each pixel.");
 
     AddParameter(ParameterType_InputImage,  "ie",   "Input endmembers");
-    SetParameterDescription("ie","The endmembers (estimated pure pixels) to use for unmixing. Must be stored as a multispectral image, where each pixel is interpreted as an endmember");
+    SetParameterDescription("ie","The endmembers (estimated pure pixels) to use for unmixing. Must be stored as a multispectral image, where each pixel is interpreted as an endmember.");
 
     AddParameter(ParameterType_Choice, "ua", "Unmixing algorithm");
     SetParameterDescription("ua", "The algorithm to use for unmixing");
diff --git a/Modules/Applications/AppImageUtils/app/otbExtractROI.cxx b/Modules/Applications/AppImageUtils/app/otbExtractROI.cxx
index b7a4110b39cccfdef8838cf1d345e94f58414bfb..1f0221e665a2291577f3d8ba4cb316624647148d 100644
--- a/Modules/Applications/AppImageUtils/app/otbExtractROI.cxx
+++ b/Modules/Applications/AppImageUtils/app/otbExtractROI.cxx
@@ -20,12 +20,13 @@
 
 #include "otbWrapperApplication.h"
 #include "otbWrapperApplicationFactory.h"
-
 #include "otbMultiChannelExtractROI.h"
 #include "otbStandardFilterWatcher.h"
 #include "otbWrapperNumericalParameter.h"
 #include "otbWrapperListViewParameter.h"
 #include "otbWrapperTypes.h"
+#include "otbOGRDataSourceToLabelImageFilter.h"
+#include <algorithm> 
 
 #include "otbWrapperElevationParametersHandler.h"
 
@@ -55,42 +56,146 @@ public:
 
   /** Filters typedef */
   typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType,
-                                      FloatVectorImageType::InternalPixelType> ExtractROIFilterType;
+                                      FloatVectorImageType::InternalPixelType> 
+                                      ExtractROIFilterType;
+
+  typedef ExtractROIFilterType::InputImageType ImageType;
 
 private:
-  void DoInit() ITK_OVERRIDE
+  void 
+  DoInit() ITK_OVERRIDE
   {
     SetName("ExtractROI");
     SetDescription("Extract a ROI defined by the user.");
 
     // Documentation
     SetDocName("Extract ROI");
-    SetDocLongDescription("This application extracts a Region Of Interest with user defined size, or reference image.");
+    SetDocLongDescription("This application extracts a Region Of Interest with "
+      "user parameters. There are four mode of extraction. The standard mode "
+      "allows the user to enter one point (upper left corner of the region to "
+      "extract) and a size. The extent mode needs two points (upper left "
+      "corner and lower right) and the radius mode need the center of the "
+      "region and the radius : it will extract the rectangle containing the "
+      "circle defined and limited by the image dimension. The fit mode "
+      "needs a reference image or vector and the dimension of the extracted "
+      "region will be the same as the extent of the reference. "
+      "Different units are available such as pixel, image physical space "
+      "or longitude and latitude.");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
 
     AddDocTag(Tags::Manip);
 
+    // Set parameter input
     AddParameter(ParameterType_InputImage,  "in",   "Input Image");
-    SetParameterDescription("in", "Input image.");
+    SetParameterDescription("in", "Image to be processed.");
     AddParameter(ParameterType_OutputImage, "out",  "Output Image");
-    SetParameterDescription("out", "Output image.");
+    SetParameterDescription("out", "Region of interest from the input image");
 
-    AddRAMParameter();
 
     AddParameter(ParameterType_Choice,"mode","Extraction mode");
     AddChoice("mode.standard","Standard");
-    SetParameterDescription("mode.standard","In standard mode, extract is done according the coordinates entered by the user");
-    AddChoice("mode.fit","Fit");
-    SetParameterDescription("mode.fit","In fit mode, extract is made to best fit a reference image.");
-
-    AddParameter(ParameterType_InputImage,"mode.fit.ref","Reference image");
-    SetParameterDescription("mode.fit.ref","Reference image to define the ROI");
-
-    // Elevation
-    ElevationParametersHandler::AddElevationParameters(this,"mode.fit.elev");
+    SetParameterDescription("mode.standard",
+      "In standard mode extraction is done with 2 parameters : the "
+      "upper left corner and the size of the region, decomposed "
+      "in X and Y coordinates.");
 
+    // Fit mode : the ROI is computed through a ref vector dataset or a ref image 
+    AddChoice("mode.fit","Fit");
+    SetParameterDescription("mode.fit",
+      "In fit mode, extract is made from a reference : image or vector dataset.");
+
+    AddParameter( ParameterType_InputImage , "mode.fit.im" , 
+      "Reference image" );
+    SetParameterDescription( "mode.fit.im" ,
+      "Reference image to define the ROI" );
+    AddParameter( ParameterType_InputVectorData , "mode.fit.vect" , 
+                  "Reference vector" );
+    SetParameterDescription( "mode.fit.vect" ,
+      "The extent of the input vector file is computed and then "
+      "gives a region of interest that will be extracted." );
+
+    // Extent mode : ROI is computed with two point (upper left and lower left corners)
+    AddChoice( "mode.extent" , "Extent" );
+    SetParameterDescription( "mode.extent" ,
+      "In extent mode, the ROI is defined by two points, the upper left corner "
+      "and the lower right corner, decomposed in 2 coordinates : "
+      "X and Y. The unit for those coordinates can be set." );
+    AddParameter( ParameterType_Float , "mode.extent.ulx" ,
+                  "X coordinate of the Upper left corner" );
+    SetParameterDescription( "mode.extent.ulx" ,
+      "X coordinate of upper left corner point." );
+    AddParameter( ParameterType_Float , "mode.extent.uly" ,
+                  "Y coordinate of Upper Left corner point." );
+    SetParameterDescription( "mode.extent.uly" ,
+      "Y coordinate of upper left corner point." );
+    AddParameter( ParameterType_Float , "mode.extent.lrx" , 
+                  "X coordinate of Lower Right corner point." );
+    SetParameterDescription( "mode.extent.lrx" ,
+      "X coordinate of lower right corner point." );
+    AddParameter( ParameterType_Float , "mode.extent.lry" ,
+                  "Y coordinate of Lower Right corner point." );
+    SetParameterDescription( "mode.extent.lry" ,
+      "Y coordinate of lower right corner point." );
+    // Unit of extent mode
+    AddParameter( ParameterType_Choice , "mode.extent.unit" , "Unit" );
+    AddChoice( "mode.extent.unit.pxl" , "Pixel" );
+    SetParameterDescription("mode.extent.unit.pxl",
+      "The unit for the parameters coordinates will be the pixel, meaning the "
+      "index of the two points.");
+    AddChoice( "mode.extent.unit.phy" , "Image physical space" );
+    SetParameterDescription("mode.extent.unit.phy",
+      "The unit for the parameters coordinates will be the physical "
+      "measure of the image.");
+    AddChoice( "mode.extent.unit.lonlat" , "Longitude and latitude" );
+    SetParameterDescription("mode.extent.unit.lonlat",
+      "The unit for the parameters coordinates will be the longitude and "
+      "the latitude.");
+
+
+    // Radius mode : ROI is computed through a point and a radius
+    AddChoice( "mode.radius" , "Radius" );
+    SetParameterDescription( "mode.radius" ,
+      "In radius mode, the ROI is defined by a point and a radius. The "
+      "unit of those two parameters can be chosen independently." );
+
+    AddParameter( ParameterType_Float , "mode.radius.r" , "Radius" );
+    SetParameterDescription( "mode.radius.r" ,
+      "This is the radius parameter of the radius mode." );
+    AddParameter( ParameterType_Choice , "mode.radius.unitr" , "Radius unit" );
+    AddChoice( "mode.radius.unitr.pxl" , "Pixel" );
+    SetParameterDescription("mode.radius.unitr.pxl",
+      "The unit of the radius will be the pixel.");
+    AddChoice( "mode.radius.unitr.phy" , "Image physical space" );
+    SetParameterDescription("mode.radius.unitr.phy",
+      "The unit of the radius will be the physical measure of the image.");
+
+    AddParameter( ParameterType_Float , "mode.radius.cx" ,
+                  "X coordinate of the center" );
+    SetParameterDescription( "mode.radius.cx" ,
+      "This is the center coordinate of the radius mode, it will be either an "
+      "abscissa or a longitude." );
+    AddParameter( ParameterType_Float , "mode.radius.cy" ,
+                  "Y coordinate of the center" );
+    SetParameterDescription( "mode.radius.cx" ,
+      "This is the center coordinate of the radius mode, it will be either an "
+      "ordinate or a latitude." );
+    AddParameter( ParameterType_Choice , "mode.radius.unitc" , "Center unit" );
+    AddChoice( "mode.radius.unitc.pxl" , "Pixel" );
+    SetParameterDescription("mode.radius.unitc.pxl",
+      "The unit for the center coordinates will be the pixel");
+    AddChoice( "mode.radius.unitc.phy" , "Image physical space" );
+    SetParameterDescription("mode.radius.unitc.phy",
+      "The unit for the center coordinates will be the physical "
+      "measure of the image.");
+    AddChoice( "mode.radius.unitc.lonlat" , "Lon/Lat" );
+    SetParameterDescription("mode.radius.unitc.lonlat",
+      "The unit for the center coordinates will be the longitude and "
+      "the latitude.");
+
+
+    // Standard parameter
     AddParameter(ParameterType_Int,  "startx", "Start X");
     SetParameterDescription("startx", "ROI start x position.");
     AddParameter(ParameterType_Int,  "starty", "Start Y");
@@ -100,47 +205,86 @@ private:
     AddParameter(ParameterType_Int,  "sizey",  "Size Y");
     SetParameterDescription("sizey","size along y in pixels.");
 
+    // Channelist Parameters
+    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
+    SetParameterDescription("cl","Channels to write in the output image.");
+
+    // Elevation
+    ElevationParametersHandler::AddElevationParameters(this,"elev");
+    AddRAMParameter();
+
     // Default values
     SetDefaultParameterInt("startx", 0);
     SetDefaultParameterInt("starty", 0);
     SetDefaultParameterInt("sizex",  0);
     SetDefaultParameterInt("sizey",  0);
 
-    // Channelist Parameters
-    AddParameter(ParameterType_ListView,  "cl", "Output Image channels");
-    SetParameterDescription("cl","Channels to write in the output image.");
+    SetDefaultParameterInt("mode.extent.ulx", 0);
+    SetDefaultParameterInt("mode.extent.uly", 0);
+    SetDefaultParameterInt("mode.extent.lry", 0);
+    SetDefaultParameterInt("mode.extent.lrx", 0);
+
+    SetDefaultParameterInt("mode.radius.r", 0);
+    SetDefaultParameterInt("mode.radius.cx", 0);
+    SetDefaultParameterInt("mode.radius.cy", 0);
+
 
     // Doc example parameter settings
     SetDocExampleParameterValue("in", "VegetationIndex.hd");
-    SetDocExampleParameterValue("startx", "40");
-    SetDocExampleParameterValue("starty", "250");
-    SetDocExampleParameterValue("sizex", "150");
-    SetDocExampleParameterValue("sizey", "150");
+    SetDocExampleParameterValue("mode", "extent");
+    SetDocExampleParameterValue("mode.extent.ulx", "40");
+    SetDocExampleParameterValue("mode.extent.uly", "40");
+    SetDocExampleParameterValue("mode.extent.lrx", "150");
+    SetDocExampleParameterValue("mode.extent.lry", "150");
     SetDocExampleParameterValue("out", "ExtractROI.tif");
+    SetMinimumParameterIntValue("sizex", 0);
+    SetMinimumParameterIntValue("sizey", 0);
+    SetMinimumParameterIntValue("startx", 0);
+    SetMinimumParameterIntValue("starty", 0);
+    SetMinimumParameterFloatValue( "mode.radius.r" , 0 );
 
     SetOfficialDocLink();
   }
 
-  void DoUpdateParameters() ITK_OVERRIDE
+  void 
+  DoUpdateParameters() ITK_OVERRIDE
   {
-    // Update the sizes only if the user has not defined a size
     if ( HasValue("in") )
       {
-      ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
-      ExtractROIFilterType::InputImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();
+      ImageType* inImage = GetParameterImage("in");
+      ImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();
+
+      bool userExtent = !HasUserValue( "mode.extent.ulx" ) \
+                     && !HasUserValue( "mode.extent.uly" ) \
+                     && !HasUserValue( "mode.extent.lrx" ) \
+                     && !HasUserValue( "mode.extent.lry" );
 
+      bool userRadius = !HasUserValue( "mode.radius.r" ) \
+                     && !HasUserValue( "mode.radius.cx" ) \
+                     && !HasUserValue( "mode.radius.cy" );
+
+      // Update the sizes only if the user has not defined a size
       if (!HasUserValue("sizex")  && !HasUserValue("sizey") )
         {
         SetParameterInt("sizex",largestRegion.GetSize()[0], false);
         SetParameterInt("sizey",largestRegion.GetSize()[1], false);
+
+        // Compute extent parameter with default sizex and sizey
+        if ( GetParameterString( "mode" ) == "extent" && userExtent )
+          ComputeExtentFromIndex( inImage, largestRegion );
+
+        // Compute radius parameter with default sizex and sizey
+        if ( GetParameterString( "mode" ) == "radius" && userRadius )
+          ComputeRadiusFromIndex( inImage , largestRegion );
         }
 
+
       unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
-      ListViewParameter *clParam = dynamic_cast<ListViewParameter*>(GetParameterByKey("cl"));
+      ListViewParameter *clParam = 
+                  dynamic_cast<ListViewParameter*>(GetParameterByKey("cl"));
       // Update the values of the channels to be selected if nbComponents is changed
       if (clParam != ITK_NULLPTR && clParam->GetNbChoices() != nbComponents)
         {
-
         ClearChoices("cl");
         for (unsigned int idx = 0; idx < nbComponents; ++idx)
           {
@@ -152,18 +296,20 @@ private:
         }
 
       // Put the limit of the index and the size relative the image
-      SetMinimumParameterIntValue("sizex", 0);
-      SetMaximumParameterIntValue("sizex", largestRegion.GetSize(0));
-
-      SetMinimumParameterIntValue("sizey", 0);
-      SetMaximumParameterIntValue("sizey", largestRegion.GetSize(1));
-
-      SetMinimumParameterIntValue("startx", 0);
+      
+      SetMaximumParameterIntValue("sizex", largestRegion.GetSize(0));      
+      SetMaximumParameterIntValue("sizey", largestRegion.GetSize(1));      
       SetMaximumParameterIntValue("startx", largestRegion.GetSize(0));
-
-      SetMinimumParameterIntValue("starty", 0);
       SetMaximumParameterIntValue("starty", largestRegion.GetSize(1));
 
+      
+      // Update the start and size parameter depending on the mode
+      if ( GetParameterString("mode") == "extent" && !userExtent)
+          ComputeIndexFromExtent();
+      if (GetParameterString("mode") == "radius" && !userRadius)
+          ComputeIndexFromRadius();
+
+      
       // Crop the roi region to be included in the largest possible
       // region
       if(!this->CropRegionOfInterest())
@@ -173,34 +319,62 @@ private:
         SetParameterInt("starty",0, false);
         this->CropRegionOfInterest();
         }
+
+      if(GetParameterString("mode")=="fit")
+        {
+        this->SetParameterRole("startx",Role_Output);
+        this->SetParameterRole("starty",Role_Output);
+        this->SetParameterRole("sizex",Role_Output);
+        this->SetParameterRole("sizey",Role_Output);
+        this->DisableParameter("startx");
+        this->DisableParameter("starty");
+        this->DisableParameter("sizex");
+        this->DisableParameter("sizey");
+        }
+
+      else if(GetParameterString("mode")=="standard" || 
+              GetParameterString("mode")=="extent" ||
+              GetParameterString("mode")== "radius" )
+        {
+        this->SetParameterRole("startx",Role_Input);
+        this->SetParameterRole("starty",Role_Input);
+        this->SetParameterRole("sizex",Role_Input);
+        this->SetParameterRole("sizey",Role_Input);
+        this->EnableParameter("startx");
+        this->EnableParameter("starty");
+        this->EnableParameter("sizex");
+        this->EnableParameter("sizey");
+        }
       }
 
-    if(GetParameterString("mode")=="fit")
+    // If not standard mode start and size parameter will be computed by the application
+    if ( GetParameterString( "mode" ) != "standard" )
       {
-      this->SetParameterRole("startx",Role_Output);
-      this->SetParameterRole("starty",Role_Output);
-      this->SetParameterRole("sizex",Role_Output);
-      this->SetParameterRole("sizey",Role_Output);
-
-      this->DisableParameter("startx");
-      this->DisableParameter("starty");
-      this->DisableParameter("sizex");
-      this->DisableParameter("sizey");
+      MandatoryOff("startx");
+      MandatoryOff("starty");
+      MandatoryOff("sizex");
+      MandatoryOff("sizey");
+      }
+    else
+      {
+      MandatoryOn("startx");
+      MandatoryOn("starty");
+      MandatoryOn("sizex");
+      MandatoryOn("sizey");
+      }
 
+    if ( GetParameterString( "mode" ) == "fit" && HasValue( "mode.fit.im" ) )
+      {
+      MandatoryOff( "mode.fit.vect" );
+      MandatoryOn( "mode.fit.im" );
       }
-    else if(GetParameterString("mode")=="standard")
+    else if ( GetParameterString( "mode" ) == "fit" && 
+              HasValue( "mode.fit.vect" ) )
       {
-      this->SetParameterRole("startx",Role_Input);
-      this->SetParameterRole("starty",Role_Input);
-      this->SetParameterRole("sizex",Role_Input);
-      this->SetParameterRole("sizey",Role_Input);
-
-      this->EnableParameter("startx");
-      this->EnableParameter("starty");
-      this->EnableParameter("sizex");
-      this->EnableParameter("sizey");
+      MandatoryOff( "mode.fit.im" );
+      MandatoryOn( "mode.fit.vect" );
       }
-  }
+  } 
 
   bool CropRegionOfInterest()
   {
@@ -209,33 +383,386 @@ private:
     region.SetSize(1,  GetParameterInt("sizey"));
     region.SetIndex(0, GetParameterInt("startx"));
     region.SetIndex(1, GetParameterInt("starty"));
-
     if ( HasValue("in") )
       {
-        if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
+      if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
+        {
+        SetParameterInt("sizex",region.GetSize(0), HasUserValue("sizex"));
+        SetParameterInt("sizey",region.GetSize(1), HasUserValue("sizey"));
+        SetParameterInt("startx",region.GetIndex(0), HasUserValue("startx"));
+        SetParameterInt("starty",region.GetIndex(1), HasUserValue("starty"));
+        return true;
+        }
+      }
+    return false;
+  }
+
+  void
+  ComputeIndexFromExtent()
+  {
+    assert( GetParameterString( "mode" ) == "extent" );
+    int pixelValue = -1 ;
+    // Compute standard parameter depending on the unit chosen by the user
+    if (GetParameterString( "mode.extent.unit" ) == "pxl" )
+      {
+      pixelValue = std::round( GetParameterFloat( "mode.extent.ulx" ) );
+      SetParameterInt( "startx", pixelValue , true );
+      pixelValue = std::round( GetParameterFloat( "mode.extent.lrx" ) \
+                   - pixelValue ) + 1 ;
+      SetParameterInt( "sizex", pixelValue , true );
+      pixelValue = std::round( GetParameterFloat( "mode.extent.uly" ) );
+      SetParameterInt( "starty", pixelValue , true );
+      pixelValue = std::round( GetParameterFloat( "mode.extent.lry" ) \
+                   - pixelValue ) + 1 ;
+      SetParameterInt( "sizey", pixelValue , true );
+      }
+    else if( GetParameterString( "mode.extent.unit" ) == "phy" )
+      {
+      itk::Point<float, 2> ulp,  lrp;
+      ulp[ 0 ] = GetParameterFloat( "mode.extent.ulx" );
+      ulp[ 1 ] = GetParameterFloat( "mode.extent.uly" );
+      lrp[ 0 ] = GetParameterFloat( "mode.extent.lrx" );
+      lrp[ 1 ] = GetParameterFloat( "mode.extent.lry" );
+
+      ImageType * inImage = GetParameterImage("in");
+      FloatVectorImageType::IndexType uli , lri;
+      bool startin = inImage->TransformPhysicalPointToIndex(ulp,uli);
+      bool sizein = inImage->TransformPhysicalPointToIndex(lrp,lri);
+      if ( startin )
+        {
+        SetParameterInt( "startx", uli[0] , true );
+        SetParameterInt( "starty", uli[1] , true );
+        }
+        
+      if( startin && sizein )
+        {
+        SetParameterInt( "sizex", lri[0] - uli[0] + 1, true );
+        SetParameterInt( "sizey", lri[1] - uli[1] + 1, true );
+        }
+      }
+    else if( GetParameterString( "mode.extent.unit" ) == "lonlat" )
+      {
+      RSTransformType::Pointer rsTransform = RSTransformType::New();
+      ImageType* inImage = GetParameterImage("in");
+      rsTransform->SetOutputKeywordList( inImage->GetImageKeywordlist() );
+      rsTransform->SetOutputProjectionRef( inImage->GetProjectionRef() );
+      rsTransform->InstantiateTransform();
+      itk::Point<float, 2> ulp_in,  lrp_in , ulp_out , lrp_out;
+      ulp_in[ 0 ] = GetParameterFloat( "mode.extent.ulx" );
+      ulp_in[ 1 ] = GetParameterFloat( "mode.extent.uly" );
+      lrp_in[ 0 ] = GetParameterFloat( "mode.extent.lrx" );
+      lrp_in[ 1 ] = GetParameterFloat( "mode.extent.lry" );
+      ulp_out = rsTransform->TransformPoint(ulp_in);
+      lrp_out = rsTransform->TransformPoint(lrp_in);
+
+      FloatVectorImageType::IndexType uli_out , lri_out;
+      bool startin = inImage->TransformPhysicalPointToIndex(ulp_out,uli_out);
+      bool sizein = inImage->TransformPhysicalPointToIndex(lrp_out,lri_out);
+
+      if ( startin )
+        {
+        SetParameterInt( "startx", uli_out[0] , true );
+        SetParameterInt( "starty", uli_out[1] , true );
+        }
+            
+      if( startin && sizein )
+        {
+        SetParameterInt( "sizex", lri_out[0] - uli_out[0] + 1, true );
+        SetParameterInt( "sizey", lri_out[1] - uli_out[1] + 1, true );
+        }
+      }  
+  }
+
+  void
+  ComputeExtentFromIndex(const ImageType * input , 
+                         const ImageType::RegionType & largestRegion )
+  {
+    FloatVectorImageType::IndexType uli , lri;
+    uli.Fill(0);
+    lri[ 0 ] = largestRegion.GetSize()[0];
+    lri[ 1 ] = largestRegion.GetSize()[1];
+    if ( GetParameterString( "mode.extent.unit" ) == "pxl" )
+      {
+      SetParameterFloat("mode.extent.ulx", uli[0] , false);
+      SetParameterFloat("mode.extent.uly", uli[1] , false);
+      SetParameterFloat("mode.extent.lrx", lri[0] , false);
+      SetParameterFloat("mode.extent.lry", lri[1] , false);
+      }
+    else if ( GetParameterString( "mode.extent.unit" ) == "phy" )
+      {
+      itk::Point<float, 2> ulp,  lrp;
+
+      input->TransformIndexToPhysicalPoint(uli,ulp);
+      SetParameterFloat("mode.extent.ulx",ulp[0], false);
+      SetParameterFloat("mode.extent.uly",ulp[1], false);
+
+      input->TransformIndexToPhysicalPoint(lri,lrp);
+      SetParameterFloat("mode.extent.lrx",lrp[0], false);
+      SetParameterFloat("mode.extent.lry",lrp[1], false);  
+      }
+    else if ( GetParameterString( "mode.extent.unit" ) == "lonlat" )
+      {
+      RSTransformType::Pointer rsTransform = RSTransformType::New();
+      rsTransform->SetInputKeywordList( input->GetImageKeywordlist() );
+      rsTransform->SetInputProjectionRef( input->GetProjectionRef() );
+      rsTransform->InstantiateTransform();
+      itk::Point<float, 2> ulp_in,  lrp_in , ulp_out , lrp_out;
+      input->TransformIndexToPhysicalPoint(uli,ulp_in);
+      ulp_out = rsTransform->TransformPoint( ulp_in );
+      SetParameterFloat( "mode.extent.ulx" , ulp_out[ 0 ] , false );
+      SetParameterFloat( "mode.extent.uly" , ulp_out[ 1 ] , false );
+
+      input->TransformIndexToPhysicalPoint( lri , lrp_in );
+      lrp_out = rsTransform->TransformPoint( lrp_in );
+      SetParameterFloat( "mode.extent.lrx" , lrp_out[ 0 ] , false );
+      SetParameterFloat( "mode.extent.lry" , lrp_out[ 1 ] , false );
+      }
+  }
+
+  void
+  ComputeIndexFromRadius()
+  {
+    int pixelValue = -1;
+    assert( GetParameterString( "mode" ) == "radius" );
+    // First compute sizex sizey thanks to the radius
+    if ( HasUserValue( "mode.radius.r" ) )
+      {
+      if ( GetParameterString( "mode.radius.unitr" ) == "pxl" )
+        {
+        pixelValue = std::floor( 2 * GetParameterFloat( "mode.radius.r" ) ) + 1;
+        SetParameterInt( "sizey", pixelValue , true );
+        SetParameterInt( "sizex", pixelValue , true );
+        }
+      if ( GetParameterString( "mode.radius.unitr" ) == "phy" )
+        {
+        ImageType * inImage = GetParameterImage("in");
+        itk::Point<float, 2> radxp , radyp , ulp ;
+        FloatVectorImageType::IndexType radxi , radyi , uli;
+        uli.Fill(0);
+        inImage->TransformIndexToPhysicalPoint( uli , ulp );
+        radxp = ulp; 
+        radyp = ulp; 
+        radxp[0] += GetParameterFloat( "mode.radius.r" );
+        radyp[1] += GetParameterFloat( "mode.radius.r" );
+        bool lgtx = inImage->TransformPhysicalPointToIndex( radxp , radxi );
+        bool lgty = inImage->TransformPhysicalPointToIndex( radyp , radyi );
+        FloatVectorImageType::IndexValueType maxR = 
+                std::min( inImage->GetLargestPossibleRegion().GetSize()[0] , 
+                          inImage->GetLargestPossibleRegion().GetSize()[1] );
+        maxR = maxR / 2 - ( (maxR + 1) % 2 );
+        if ( lgtx && lgty)
+          {
+          pixelValue = std::max( radxi[0] , radyi[1] );
+          if ( maxR<pixelValue )
+            {
+            pixelValue = std::min( std::min( radxi[0] , radyi[1] ) , maxR );
+            }
+          }
+        else if ( lgtx )
           {
-            SetParameterInt("sizex",region.GetSize(0), HasUserValue("sizex"));
-            SetParameterInt("sizey",region.GetSize(1), HasUserValue("sizey"));
-            SetParameterInt("startx",region.GetIndex(0), HasUserValue("startx"));
-            SetParameterInt("starty",region.GetIndex(1), HasUserValue("starty"));
-            return true;
+          pixelValue = std::min( radxi[0] , maxR );
           }
+        else if ( lgty )
+          {
+          pixelValue = std::min( radyi[1] , maxR );
+          }
+        else
+          {
+          pixelValue = maxR;
+          }
+        SetParameterInt( "sizey", 2 * pixelValue + 1 , true );
+        SetParameterInt( "sizex", 2 * pixelValue + 1 , true );
+        }
+      }
+
+    // Then compute startx and starty
+    bool size = ( HasValue("sizex")  && HasValue("sizey") );
+    if ( size ) 
+      {
+      int radiusxi = GetParameterInt("sizex") / 2 ;
+      int radiusyi = GetParameterInt("sizey") / 2 ;
+
+      if ( GetParameterString( "mode.radius.unitc" ) == "pxl" && size )
+        {
+        pixelValue = std::round(GetParameterFloat( "mode.radius.cx" ));
+        SetParameterInt( "startx", pixelValue - radiusxi , true );
+        pixelValue = std::round(GetParameterFloat( "mode.radius.cy" ));
+        SetParameterInt( "starty", pixelValue - radiusyi , true );
+        }
+      if ( GetParameterString( "mode.radius.unitc" ) == "phy" && size ) 
+        {
+        ImageType * inImage = GetParameterImage("in");
+        itk::Point<float, 2> centerp;
+        centerp[ 0 ] = GetParameterFloat( "mode.radius.cx" );
+        centerp[ 1 ] = GetParameterFloat( "mode.radius.cy" );
+        FloatVectorImageType::IndexType centeri ;
+        bool isIn = inImage->TransformPhysicalPointToIndex( centerp , centeri );
+          if ( isIn )
+          {
+          SetParameterInt( "startx", centeri[0] - radiusxi , true );
+          SetParameterInt( "starty", centeri[1] - radiusyi , true );
+          }
+        }
+      if ( GetParameterString( "mode.radius.unitc" ) == "lonlat" && size )
+        {
+        ImageType* inImage = GetParameterImage("in");
+        RSTransformType::Pointer rsTransform = RSTransformType::New();
+        rsTransform->SetOutputKeywordList( inImage->GetImageKeywordlist() );
+        rsTransform->SetOutputProjectionRef( inImage->GetProjectionRef() );
+        rsTransform->InstantiateTransform();
+        itk::Point<float, 2> centerp_in , centerp_out;
+        centerp_in[ 0 ] = GetParameterFloat( "mode.radius.cx" );
+        centerp_in[ 1 ] = GetParameterFloat( "mode.radius.cy" );
+        centerp_out = rsTransform->TransformPoint(centerp_in);
+        FloatVectorImageType::IndexType centeri_out;
+        bool isIn = inImage->TransformPhysicalPointToIndex( centerp_out , 
+                                                            centeri_out );
+        if ( isIn )
+          {
+          SetParameterInt( "startx", centeri_out[0] - radiusxi , true );
+          SetParameterInt( "starty", centeri_out[1] - radiusyi , true );
+          }
+        }
+      }
+  }
+
+  void
+  ComputeRadiusFromIndex(const ImageType * input , 
+                         const ImageType::RegionType & largestRegion)
+  {
+    FloatVectorImageType::IndexType centeri , helpRxi, helpRyi;
+    centeri[ 0 ] = largestRegion.GetSize()[0] / 2  \
+                   - (largestRegion.GetSize()[0] + 1)%2;
+    centeri[ 1 ] = largestRegion.GetSize()[1] / 2  \
+                   - (largestRegion.GetSize()[1] + 1)%2;
+    helpRxi[ 0 ] = centeri[ 0 ];
+    helpRxi[ 1 ] = 0;
+    helpRyi[ 0 ] = 0;
+    helpRyi[ 1 ] = centeri[ 1 ];
+    if ( GetParameterString("mode.radius.unitr") == "pxl" )
+      {
+      int rad = std::min( centeri[ 0 ], centeri[ 1 ] );
+      SetParameterFloat( "mode.radius.r" , rad , false );
+      }
+    if ( GetParameterString("mode.radius.unitr") == "phy" )
+      {
+      itk::Point<float, 2> centerp , helpRxp, helpRyp;
+      input->TransformIndexToPhysicalPoint(centeri,centerp);
+      input->TransformIndexToPhysicalPoint(helpRxi,helpRxp);
+      input->TransformIndexToPhysicalPoint(helpRyi,helpRyp);
+      float rad = std::min( helpRxp[0] - helpRyp[0] , helpRyp[1] - helpRxp[1] );
+      SetParameterFloat( "mode.radius.r" , rad , false );
+      }
+    if ( GetParameterString("mode.radius.unitc") == "pxl" )
+      {
+      SetParameterFloat( "mode.radius.cx" , centeri[0] , false );
+      SetParameterFloat( "mode.radius.cy" , centeri[1] , false) ;
+      }
+    if ( GetParameterString("mode.radius.unitc") == "phy" )
+      {
+      itk::Point<float, 2> centerp , helpRp;
+      input->TransformIndexToPhysicalPoint(centeri,centerp);
+      SetParameterFloat( "mode.radius.cx" , centerp[0] , false );
+      SetParameterFloat( "mode.radius.cy" , centerp[1] , false) ;
+      }
+    if ( GetParameterString("mode.radius.unitc") == "lonlat" )
+      {
+      RSTransformType::Pointer rsTransform = RSTransformType::New();
+      rsTransform->SetInputKeywordList( input->GetImageKeywordlist() );
+      rsTransform->SetInputProjectionRef( input->GetProjectionRef() );
+      rsTransform->InstantiateTransform();
+      itk::Point<float, 2> centerp_in,  centerp_out;
+      input->TransformIndexToPhysicalPoint(centeri,centerp_in);
+      centerp_out = rsTransform->TransformPoint( centerp_in );
+      SetParameterFloat( "mode.radius.cx" , centerp_out[ 0 ] , false );
+      SetParameterFloat( "mode.radius.cy" , centerp_out[ 1 ] , false );
       }
-    return false;
   }
 
-  void DoExecute() ITK_OVERRIDE
+  void 
+  DoExecute() ITK_OVERRIDE
   {
-    ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
+    ImageType* inImage = GetParameterImage("in");
     inImage->UpdateOutputInformation();
 
+    if ( HasValue( "mode.fit.vect" ) && GetParameterString("mode") == "fit" )
+      {
+      otb::ogr::DataSource::Pointer ogrDS;
+      ogrDS = otb::ogr::DataSource::New(GetParameterString("in") ,
+                                        otb::ogr::DataSource::Modes::Read);
+      double ulx, uly, lrx, lry;
+      bool extentAvailable = true;
+      std::string inputProjectionRef = "";
+      // First try to get the extent in the metadata
+      try
+        {
+        inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry);
+        }
+      catch(const itk::ExceptionObject&)
+        {
+        extentAvailable = false;
+        }
+      // If no extent available force the computation of the extent
+      if (!extentAvailable)
+        {
+        try
+          {
+          inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry,true);
+          extentAvailable = true;
+          }
+        catch(itk::ExceptionObject & err)
+          {
+          extentAvailable = false;
+
+          otbAppLogFATAL(<<"Failed to retrieve the spatial extent of the dataset "
+                           "in force mode. The spatial extent is mandatory when "
+                           "orx, ory, spx and spy parameters are not set, consider "
+                           "setting them. Error from library: "<<err.GetDescription());
+          }
+        }
+
+      if (extentAvailable)
+        {
+        RSTransformType::Pointer rsTransform = RSTransformType::New();
+        rsTransform->SetInputProjectionRef(inputProjectionRef);
+        rsTransform->SetOutputKeywordList( inImage->GetImageKeywordlist() );
+        rsTransform->SetOutputProjectionRef( inImage->GetProjectionRef() );
+        rsTransform->InstantiateTransform();
+
+        itk::Point<float, 2> ulp_in,  lrp_in , ulp_out , lrp_out;
+        ulp_in[ 0 ] = ulx ;
+        ulp_in[ 1 ] = uly ;
+        lrp_in[ 0 ] = lrx ;
+        lrp_in[ 1 ] = lry ;
+        ulp_out = rsTransform->TransformPoint(ulp_in);
+        lrp_out = rsTransform->TransformPoint(lrp_in);
+
+        FloatVectorImageType::IndexType uli_out , lri_out;
+        bool startin , sizein ;
+        startin = inImage->TransformPhysicalPointToIndex(ulp_out,uli_out);
+        sizein = inImage->TransformPhysicalPointToIndex(lrp_out,lri_out);
+
+        if ( startin )
+            {
+            SetParameterInt( "startx", uli_out[0] , false );
+            SetParameterInt( "starty", uli_out[1] , false );
+            }
+                
+        if( startin && sizein )
+            {
+            SetParameterInt( "sizey", lri_out[1] - uli_out[1] + 1 , false );
+            SetParameterInt( "sizex", lri_out[0] - uli_out[0] + 1 , false );
+            }
+        }
+        
+      }
 
-    if(GetParameterString("mode")=="fit")
+    if( HasValue( "mode.fit.im" ) && GetParameterString( "mode" ) == "fit" )
       {
       // Setup the DEM Handler
-      otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"mode.fit.elev");
+      otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
 
-      FloatVectorImageType::Pointer referencePtr = this->GetParameterImage("mode.fit.ref");
+      FloatVectorImageType::Pointer referencePtr = this->GetParameterImage("mode.fit.im");
       referencePtr->UpdateOutputInformation();
 
       RSTransformType::Pointer rsTransform = RSTransformType::New();
@@ -278,11 +805,15 @@ private:
 
       FloatVectorImageType::IndexType uli, lri;
 
-      uli[0] = std::min(std::min(uli_out[0],uri_out[0]),std::min(lli_out[0],lri_out[0]));
-      uli[1] = std::min(std::min(uli_out[1],uri_out[1]),std::min(lli_out[1],lri_out[1]));
+      uli[0] = std::min( std::min( uli_out[0] , uri_out[0] ) , 
+                         std::min( lli_out[0] , lri_out[0] ) );
+      uli[1] = std::min( std::min( uli_out[1] , uri_out[1] ) ,
+                         std::min( lli_out[1] , lri_out[1] ) );
 
-      lri[0] = std::max(std::max(uli_out[0],uri_out[0]),std::max(lli_out[0],lri_out[0]));
-      lri[1] = std::max(std::max(uli_out[1],uri_out[1]),std::max(lli_out[1],lri_out[1]));
+      lri[0] = std::max( std::max( uli_out[0] , uri_out[0] ) ,
+                         std::max( lli_out[0] , lri_out[0] ) );
+      lri[1] = std::max( std::max( uli_out[1] , uri_out[1] ) ,
+                         std::max( lli_out[1] , lri_out[1] ) );
 
       SetParameterInt("startx",uli[0]);
       SetParameterInt("starty",uli[1]);
diff --git a/Modules/Applications/AppImageUtils/otb-module.cmake b/Modules/Applications/AppImageUtils/otb-module.cmake
index 72e63db6e8fa76b5edae021ced6df391f936065d..6b378f1f31adc8b54cab8249c2ec2a95f208de00 100644
--- a/Modules/Applications/AppImageUtils/otb-module.cmake
+++ b/Modules/Applications/AppImageUtils/otb-module.cmake
@@ -22,6 +22,7 @@ set(DOCUMENTATION "Image utils and handling application.")
 
 otb_module(OTBAppImageUtils
   DEPENDS
+    OTBConversion
     OTBApplicationEngine
     OTBBoostAdapters
     OTBCarto
diff --git a/Modules/Applications/AppImageUtils/test/CMakeLists.txt b/Modules/Applications/AppImageUtils/test/CMakeLists.txt
index 32d54bdef86587cee770865836d895c76a361462..1117d032186bd937d516522ce449924bdc63e8f2 100644
--- a/Modules/Applications/AppImageUtils/test/CMakeLists.txt
+++ b/Modules/Applications/AppImageUtils/test/CMakeLists.txt
@@ -77,6 +77,26 @@ otb_test_application(NAME apTvUtExtractROISizeTooBig
                              ${INPUTDATA}/couleurs_extrait.png
                              ${TEMP}/apTvUtExtractROISizeTooBig.tif)
 
+otb_test_application(NAME apTvUtExtractROISizeTooBigExtent
+                     APP  ExtractROI
+                     OPTIONS -in ${INPUTDATA}/couleurs_extrait.png
+                             -out ${TEMP}/apTvUtExtractROISizeTooBigExtent.tif
+                             -mode extent
+                             -mode.extent.lrx 1000000
+                     VALID   --compare-image ${NOTOL}
+                             ${INPUTDATA}/couleurs_extrait.png
+                             ${TEMP}/apTvUtExtractROISizeTooBigExtent.tif)
+
+otb_test_application(NAME apTvUtExtractROISizeTooBigRadius
+                     APP  ExtractROI
+                     OPTIONS -in ${INPUTDATA}/couleurs_extrait.png
+                             -out ${TEMP}/apTvUtExtractROISizeTooBigRadius.tif
+                             -mode radius
+                             -mode.radius.r 1000000
+                     VALID   --compare-image ${NOTOL}
+                             ${INPUTDATA}/couleurs_extrait.png
+                             ${TEMP}/apTvUtExtractROISizeTooBigRadius.tif)
+
 otb_test_application(NAME apTvUtExtractROISizeNULL
                      APP  ExtractROI
                      OPTIONS -in ${INPUTDATA}/couleurs_extrait.png
diff --git a/Modules/Applications/AppMathParser/app/otbBandMath.cxx b/Modules/Applications/AppMathParser/app/otbBandMath.cxx
index 7a03d84c69aa80382941c2e6d5b60b538f2532fa..f8ecc1bafb051cc231cf61b14c3d2ea7f0669fb1 100644
--- a/Modules/Applications/AppMathParser/app/otbBandMath.cxx
+++ b/Modules/Applications/AppMathParser/app/otbBandMath.cxx
@@ -55,38 +55,72 @@ public:
 private:
   void DoInit() ITK_OVERRIDE
   {
-    SetName("BandMath");
-    SetDescription("Perform a mathematical operation on monoband images");
-
-    SetDocName("Band Math");
-    SetDocLongDescription("This application performs a mathematical operation on monoband images."
-      "Mathematical formula interpretation is done via MuParser libraries.\n"
-      "For MuParser version superior to 2.0 uses '&&' and '||' logical operators, and ternary operator 'boolean_expression ? if_true : if_false'\n"
-      "For older version of MuParser (prior to v2) use 'and' and 'or' logical operators, and ternary operator 'if(; ; )'.\n"
-      "The list of features and operators is available on MuParser website: http://muparser.sourceforge.net/\n"
+    SetName( "BandMath" );
+
+    SetDescription(
+      "Outputs a monoband image which is the result of a mathematical operation "
+      "on several multi-band images."
+    );
+
+    SetDocName( "Band Math" );
+
+    SetDocLongDescription(
+      "This application performs a mathematical operation on several multi-band "
+      "images and outputs the result into a monoband image. Evaluation of the "
+      "mathematical formula is done by the muParser libraries.\n\n"
+
+      "muParser version superior to 2.0, provides the '&&' and '||' logical "
+      "operators, and a ternary operator 'boolean_expression ? if_true : "
+      "if_false'.\n\n"
+
+      "Older versions of muParser (prior to v-2.0) provides only the 'and' and "
+      "'or' logical operators, and a ternary operator 'if(; ; )'.\n\n"
+
+      "The list of features and operators is available on the muParser website [1]."
       );
 
-    SetDocLimitations("None");
-    SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
-    AddDocTag("Miscellaneous");
+    SetDocLimitations( "None" );
+    SetDocAuthors( "OTB-Team" );
+    SetDocSeeAlso("[1] http://muparser.sourceforge.net/");
+    AddDocTag( "Miscellaneous" );
 
-    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
-    SetParameterDescription("il", "Image list to perform computation on.");
+    AddParameter( ParameterType_InputImageList, "il", "Input image-list" );
+    SetParameterDescription(
+      "il",
+      "Image-list of operands to the mathematical expression."
+    );
 
-    AddParameter(ParameterType_OutputImage, "out", "Output Image");
-    SetParameterDescription("out","Output image.");
+    AddParameter( ParameterType_OutputImage, "out", "Output Image" );
+    SetParameterDescription(
+      "out",
+      "Output image which is the result of the mathematical expressions on input"
+      " image-list operands.");
 
     AddRAMParameter();
 
-    AddParameter(ParameterType_String, "exp", "Expression");
-    SetParameterDescription("exp",
-                            "The mathematical expression to apply. \nUse im1b1 for the first band, im1b2 for the second one...");
+    AddParameter( ParameterType_String, "exp", "Expression");
+    SetParameterDescription(
+      "exp",
+      "The muParser mathematical expression to apply on input images.\n"
+      "Use im1b1 as first band of first image, im1b2 for the second band of "
+      "first image.\n"
+      "Use im2b1 as first band of second image, im2b2 for the second band of "
+      "second image.\n"
+      "etc."
+    );
 
     // Doc example parameter settings
-    SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif");
-    SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif");
-    SetDocExampleParameterValue("exp", "\"cos(im1b1) > cos(im2b1) ? im3b1 : im3b2\"");
+    SetDocExampleParameterValue(
+      "il",
+      "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"
+    );
+    SetDocExampleParameterValue(
+      "out",
+      "apTvUtBandMathOutput.tif"
+    );
+    SetDocExampleParameterValue(
+      "exp", "'cos( im1b1 ) > cos( im2b1 ) ? im3b1 : im3b2'"
+    );
 
     SetOfficialDocLink();
   }
@@ -222,5 +256,3 @@ private:
 } // namespace otb
 
 OTB_APPLICATION_EXPORT(otb::Wrapper::BandMath)
-
-
diff --git a/Modules/Applications/AppMathParserX/app/otbBandMathX.cxx b/Modules/Applications/AppMathParserX/app/otbBandMathX.cxx
index ef5ed35775a42984592332e274417f1faca2f40a..06da000b882e6c8215e602e79ca01baad1bd9877 100644
--- a/Modules/Applications/AppMathParserX/app/otbBandMathX.cxx
+++ b/Modules/Applications/AppMathParserX/app/otbBandMathX.cxx
@@ -57,121 +57,221 @@ public:
 private:
   void DoInit() ITK_OVERRIDE
   {
-    SetName("BandMathX");
-    SetDescription("This application performs mathematical operations on multiband images.\n"
-      "Mathematical formula interpretation is done via muParserX library : http://articles.beltoforion.de/article.php?a=muparserx");
-
-    SetDocName("Band Math X");
-    SetDocLongDescription("The goal of this documentation is to give the user some hints about the syntax used in this application.\n"
-      "The syntax is mainly constrained by the muparserx library, which can be considered as the core of the application.\n"
-      "\n\n"
-      "- Fundamentals:\n\n"
-      "The default prefix name for variables related to the ith input is 'im(i+1)'(note the indexing from 1 to N, for N inputs). \n"
-      "The following list summaries the available variables for input #0 (and so on for every input): \n"
-      "\n"
-      "im1                                -->   a pixel from first input, made of n components (n bands)\n"
-      "im1bj                             -->   jth component of a pixel from first input (first band is indexed by 1)\n"
-      "im1bjNkxp                     -->   a neighbourhood ('N') of pixels of the jth component from first input, of size kxp\n"
-      "im1PhyX and im1PhyY  -->   spacing of first input in X and Y directions (horizontal and vertical)\n"
-      "im1bjMean im1bjMin im1bjMax im1bjSum im1bjVar  -->   mean, min, max, sum, variance of jth band from first input (global statistics)\n"
-      "\nMoreover, we also have the following generic variables:\n"
-      "idxX and idxY        -->   indices of the current pixel\n"
-      "\n"
-      "Always keep in mind that this application only addresses mathematically well-defined formulas.\n"
-      "For instance, it is not possible to add vectors of different dimensions (this implies the addition of a row vector with a column vector),\n"
-      "or add a scalar to a vector or a matrix, or divide two vectors, and so on...\n"
-      "Thus, it is important to remember that a pixel of n components is always represented as a row vector.\n"
-      "\n"
-      "Example :\n\n"
-      "                   im1 + im2       (1)\n"
-      "\nrepresents the addition of pixels from first and second inputs. This expression is consistent only if\n"
-      "both inputs have the same number of bands.\n"
-      "Note that it is also possible to use the following expressions to obtain the same result:\n"
-      "\n"
-      "                   im1b1 + im2b1 \n"
-      "                   im1b2 + im2b2       (2)\n"
-      "                   ..."
-      "\n\nNevertheless, the first expression is by far much pleaseant. We call this new functionality the 'batch mode'\n"
-      "(performing the same operation in a band-to-band fashion).\n"
-
-      "\n\n"
-      "- Operations involving neighborhoods of pixels:\n\n"
-      "Another new fonctionnality is the possibility to perform operations that involve neighborhoods of pixels.\n"
-      "Variable related to such neighborhoods are always defined following the pattern imIbJNKxP, where: \n"
-      "- I is an number identifying the image input (remember, input #0 = im1, and so on)\n"
-      "- J is an number identifying the band (remember, first band is indexed by 1)\n"
-      "- KxP are two numbers that represent the size of the neighborhood (first one is related to the horizontal direction)\n"
-      "All neighborhood are centered, thus K and P must be odd numbers.\n"
-      "Many operators come with this new functionality: dotpr, mean var median min max...\n"
-      "For instance, if im1 represents the pixel of 3 bands image:\n\n"
-      "               im1 - mean(im1b1N5x5,im1b2N5x5,im1b3N5x5)       (3)\n"
-      "\ncould represent a high pass filter (Note that by implying three neighborhoods, the operator mean returns a row vector of three components.\n"
-      "It is a typical behaviour for many operators of this application).\n"
-
-      "\n\n"
-      "- Operators:\n\n"
+    SetName( "BandMathX" );
+
+    SetDescription(
+      "This application performs mathematical operations on several multiband images.\n"
+    );
+
+    SetDocName( "Band Math X" );
+
+    SetDocLongDescription(
+      "This application performs a mathematical operation on several multi-band "
+      "images and outputs the result into an image (multi- or mono-band, as "
+      "opposed to the BandMath OTB-application). The mathematical formula is "
+      "done by the muParserX libraries.\n\n"
+
+      "The list of features and the syntax of muParserX is available at [1].\n\n"
+
+      "As opposed to muParser (and thus the BandMath OTB-application [2]), "
+      "muParserX supports vector expressions which allows to output multi-band "
+      "images.\n\n"
+
+      "Hereafter is a brief reference of the muParserX syntax\n\n"
+
+      "Fundamentals\n"
+      "------------\n\n"
+
+      "The i-th input image is identified by the 'im<i+1>' (e.g. 'im1') prefix "
+      "(please, note the indexing from 1 to N, for N inputs).\n\n"
+
+      "The following list summarizes the available variables of input #0:\n\n"
+
+      "im1\n"
+      "  a pixel from 1st input, made of n components (n bands).\n\n"
+
+      "im1b2\n"
+      "  the 2nd component of a pixel from 1st input (band index is 1-based).\n\n"
+
+      "im1b2N3x4\n"
+      "  a 3x4 pixels 'N'eighbourhood of a pixel the 2nd component of a pixel "
+      "from the 1st input.\n\n"
+
+      "im1PhyX\n"
+      "  horizontal (X-axis) spacing of the 1st input.\n\n"
+
+      "im1PhyY\n"
+      "  vertical spacing of the 1st input input.\n\n"
+
+      "im1b2Mean\n"
+      "  mean of the 2nd component of the 1st input (global statistics)\n\n"
+
+      "im1b2Min\n"
+      "  minimum of the 2nd component of the 1st input (global statistics)\n\n"
+
+      "im1b2Max\n"
+      "  minimum of the 2nd component of the 1st input (global statistics)\n\n"
+
+      "im1b2Sum\n"
+      "  minimum of the 2nd component of the 1st input (global statistics)\n\n"
+
+      "im1b2Var\n"
+      "  minimum of the 2nd component of the 1st input (global statistics)\n\n"
+
+      "idxX, idxY\n"
+      "  indices of the current pixel (generic variables)\n\n"
+
+      "Always keep in mind that this application only addresses mathematically "
+      "well-defined formulas. For instance, it is not possible to add vectors of"
+      " different dimensions (e.g. addition of a row vector with a column vector"
+      "), or a scalar to a vector or matrix, or divide two vectors, etc.\n\n"
+
+      "Thus, it is important to remember that a pixel of n components is always "
+      "represented as a row vector.\n\n"
+
+      "Example:\n"
+      "  im1 + im2 (1)\n"
+      "  represents the addition of pixels from the 1st and 2nd inputs. This "
+      "expression is consistent only if both inputs have the same number of "
+      "bands.\n\n"
+
+      "Please, note that it is also possible to use the following expressions"
+      " to obtain the same result:\n"
+      "  im1b1 + im2b1\n"
+      "  im1b2 + im2b2 (2)\n"
+      "  ...\n\n"
+
+      "Nevertheless, the first expression is by far much pleaseant. We call "
+      "this new functionality the 'batch mode' (performing the same operation "
+      "in a band-to-band fashion).\n\n"
+
+      "Operations involving neighborhoods of pixels\n"
+      "--------------------------------------------\n\n"
+
+      "Another new feature is the possibility to perform operations that "
+      "involve neighborhoods of pixels. Variables related to such neighborhoods "
+      "are always defined following the imIbJNKxP pattern, where:\n"
+      "- I is an number identifying the image input (remember, input #0 = im1, "
+      "and so on)\n"
+      "- J is an number identifying the band (remember, first band is indexed by"
+      "1)\n"
+      "- KxP are two numbers that represent the size of the neighborhood (first "
+      "one is related to the horizontal direction)\n\n"
+
+      "NB: All neighborhood are centered, thus K and P must be odd numbers.\n\n"
+
+      "Many operators come with this new functionality:\n"
+      "- dotpr\n"
+      "- mean\n"
+      "- var\n"
+      "- median\n"
+      "- min\n"
+      "- max\n"
+      "- etc.\n\n"
+
+      "For instance, if im1 represents the pixel of 3 bands image:\n"
+      "  im1 - mean( im1b1N5x5, im1b2N5x5, im1b3N5x5 ) (3)\n\n"
+      "could represent a high pass filter (note that by implying three "
+      "neighborhoods, the operator mean returns a row vector of three components"
+      ". It is a typical behaviour for many operators of this application).\n\n"
+
       "In addition to the previous operators, other operators are available:\n"
-      "- existing operators/functions from muParserX, that were not originally defined for vectors and\n"
-      "matrices (for instance cos, sin, ...). These new operators/ functions keep the original names to which we added the prefix 'v' for vector (vcos, vsin, ...).\n"
-      "- mult, div and pow operators, that perform element-wise multiplication, division or exponentiation of vector/matrices (for instance im1 div im2)\n"
-      "- mlt, dv and pw operators, that perform multiplication, division or exponentiation of vector/matrices by a scalar (for instance im1 dv 2.0)\n"
-      "- bands, which is a very useful operator. It allows selecting specific bands from an image, and/or to rearrange them in a new vector;\n"
-      "for instance bands(im1,{1,2,1,1}) produces a vector of 4 components made of band 1, band 2, band 1 and band 1 values from the first input.\n"
-      "Note that curly brackets must be used in order to select the desired band indices.\n"
-      "... and so on.\n"
-
-      "\n\n"
-      "- Application itself:\n\n"
-      "The application takes the following parameters :\n"
-      "- Setting the list of inputs can be done with the 'il' parameter.\n"
-      "- Setting expressions can be done with the 'exp' parameter (see also limitations section below).\n"
-      "- Setting constants can be done with the 'incontext' parameter. User must provide a txt file with a specific syntax: #type name value\n"
-      "An example of such a file is given below:\n\n"
-      "#F expo 1.1\n"
-      "#M kernel1 { 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1 , 1.1 , 1.2; 1.3 , 1.4 , 1.5 }\n"
-      "\nAs we can see,  #I/#F allows the definition of an integer/float constant, whereas #M allows the definition of a vector/matrix.\n"
-      "In the latter case, elements of a row must be separated by commas, and rows must be separated by semicolons.\n"
-      "It is also possible to define expressions within the same txt file, with the pattern #E expr. For instance (two expressions; see also limitations section below):\n\n"
-      "#E $dotpr(kernel1,im1b1N3x5); im2b1^expo$\n"
-      "\n- The 'outcontext' parameter allows saving user's constants and expressions (context).\n"
-      "- Setting the output image can be done with the 'out' parameter (multi-outputs is not implemented yet).\n"
-      "\n\n"
-      "Finally, we strongly recommend that the reader takes a look at the cookbook, where additional information can be found (http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf).\n"
-
-);
-
-    SetDocLimitations("The application is currently unable to produce one output image per expression, contrary to otbBandMathXImageFilter.\n"
-                      "Separating expressions by semi-colons (; ) will concatenate their results into a unique multiband output image. ");
-    SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
-    AddDocTag("Miscellaneous");
-
-    AddParameter(ParameterType_InputImageList,  "il",   "Input image list");
-    SetParameterDescription("il", "Image list to perform computation on.");
-
-    AddParameter(ParameterType_OutputImage, "out", "Output Image");
-    SetParameterDescription("out","Output image.");
+      "- existing operators/functions from muParserX, that were not originally "
+      "defined for vectors and matrices (e.g. cos, sin). These new "
+      "operators/functions keep the original names to which we added the prefix "
+      "'v' for vector (vcos, vsin, etc.)\n"
+      "- mult, div and pow operators, that perform element-wise multiplication, "
+      "division or exponentiation of vector/matrices (e.g. im1 div im2).\n"
+      "- mlt, dv and pw operators, that perform multiplication, division or "
+      "exponentiation of vector/matrices by a scalar (e.g. im1 dv 2.0).\n"
+      "- bands, which is a very useful operator. It allows selecting specific "
+      "bands from an image, and/or to rearrange them in a new vector (e.g."
+      "bands( im1, { 1, 2, 1, 1 } ) produces a vector of 4 components made of "
+      "band 1, band 2, band 1 and band 1 values from the first input.\n\n"
+      "Note that curly brackets must be used in order to select the desired band"
+      "indices.\n\n"
+
+      "The application itself\n"
+      "----------------------\n\n"
+
+      "The application takes the following parameters:\n"
+      "-il          Sets the list of inputs\n"
+      "-ext         Sets the mathematical expression (see also limitations "
+      "section below).\n"
+      "-incontext   Sets the text filename containing constants values (syntax: "
+      "'#type name value')\n\n"
+
+      "An example of such a file is given below:\n"
+      "  #F expo 1.1\n"
+      "  #M kernel1 { 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1 , 1.1"
+      ", 1.2; 1.3 , 1.4 , 1.5 }\n\n"
+
+      "As we can see, #I/#F allows the definition of an integer/float constant, "
+      "whereas #M allows the definition of a vector/matrix. In the latter case, "
+      "elements of a row must be separated by commas, and rows must be separated"
+      " by semicolons.\n\n"
+
+      "It is also possible to define expressions within the same txt file, with "
+      "#E <expr> (see limitations, below). For instance:\n"
+      "  #E $dotpr( kernel1, im1b1N3x5 ); im2b1^expo$\n\n"
+
+      "-outcontext  Output usesr's constants and expressions (context).\n"
+      "-out         Sets output image (multi-outputs is not implemented yet).\n"
+      "\n"
 
-    AddRAMParameter();
+      "Finally, we strongly recommend to read the OTB Cookbook which can be "
+      "found at: http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf"
+    );
+
+    SetDocLimitations(
+      "The application is currently unable to produce one output image per "
+      "expression, contrary to otbBandMathXImageFilter.\n\n"
+      "Separating expressions by semi-colons ';' will concatenate their results "
+      "into a unique multiband output image."
+    );
+    SetDocAuthors( "OTB-Team" );
+    SetDocSeeAlso("[1] http://articles.beltoforion.de/article.php?a=muparserx\n"
+      "[2] BandMath");
+    AddDocTag( "Miscellaneous" );
 
-    AddParameter(ParameterType_String, "exp", "Expressions");
-    SetParameterDescription("exp",
-                            "Mathematical expression to apply.");
+    AddParameter( ParameterType_InputImageList, "il", "Input image-list" );
+    SetParameterDescription( "il", "Image-list to perform computation on." );
 
-    AddParameter(ParameterType_InputFilename, "incontext", "Import context");
-    SetParameterDescription("incontext",
-                            "A txt file containing user's constants and expressions.");
-    MandatoryOff("incontext");
+    AddParameter( ParameterType_OutputImage, "out", "Output Image" );
+    SetParameterDescription( "out", "Output image." );
+
+    AddRAMParameter();
 
-    AddParameter(ParameterType_OutputFilename, "outcontext", "Export context");
-    SetParameterDescription("outcontext",
-                            "A txt file where to save user's constants and expressions.");
-    MandatoryOff("outcontext");
+    AddParameter( ParameterType_String, "exp", "Expressions" );
+    SetParameterDescription(
+      "exp",
+      "Mathematical expression to apply."
+    );
+
+    AddParameter( ParameterType_InputFilename, "incontext", "Import context" );
+    SetParameterDescription(
+      "incontext",
+      "A txt file containing user's constants and expressions."
+    );
+    MandatoryOff( "incontext" );
+
+    AddParameter( ParameterType_OutputFilename, "outcontext", "Export context" );
+    SetParameterDescription(
+      "outcontext",
+      "A txt file where to save user's constants and expressions."
+    );
+    MandatoryOff( "outcontext" );
 
     // Doc example parameter settings
-    SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif");
-    SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif");
-    SetDocExampleParameterValue("exp", "\"cos(im1b1)+im2b1*im3b1-im3b2+ndvi(im3b3, im3b4)\"");
+    SetDocExampleParameterValue(
+      "il",
+      "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"
+    );
+    SetDocExampleParameterValue( "out", "apTvUtBandMathOutput.tif");
+    SetDocExampleParameterValue(
+      "exp",
+      "'cos( im1b1 ) + im2b1 * im3b1 - im3b2 + ndvi( im3b3, im3b4 )'"
+    );
 
     SetOfficialDocLink();
   }
diff --git a/Modules/Applications/AppMorphology/app/otbMorphologicalProfilesAnalysis.cxx b/Modules/Applications/AppMorphology/app/otbMorphologicalProfilesAnalysis.cxx
index 3593b85ed6b34fcbd4decaae1f40fa182dd95f46..79d9464a202674a8df71e89e6125ccb5d7aa07a2 100644
--- a/Modules/Applications/AppMorphology/app/otbMorphologicalProfilesAnalysis.cxx
+++ b/Modules/Applications/AppMorphology/app/otbMorphologicalProfilesAnalysis.cxx
@@ -103,7 +103,7 @@ private:
                                    "The output image can be :"
                                    "- A :math:`N` multi band image for the opening/closing normal or derivative profiles.\n"
                                    "- A mono band image for the opening/closing characteristics.\n"
-                                   "- A labeled image for the classification\n" );
+                                   "- A labeled image for the classification." );
     SetDocLimitations( "Generation of the morphological profile is not streamable, pay attention to this fact when setting the radius initial size and step of the structuring element." );
     SetDocAuthors( "OTB-Team" );
     SetDocSeeAlso( "otbMorphologicalOpeningProfileFilter, otbMorphologicalClosingProfileFilter, otbProfileToProfileDerivativeFilter, otbProfileDerivativeToMultiScaleCharacteristicsFilter, otbMultiScaleConvexOrConcaveClassificationFilter, classes" );
diff --git a/Modules/Applications/AppProjection/app/otbImageEnvelope.cxx b/Modules/Applications/AppProjection/app/otbImageEnvelope.cxx
index 4dcee6f2347d56c1c837f2d28b7ed558562fbb55..cda6b1fc64307e1a0fabc79c508d934b03156a1c 100644
--- a/Modules/Applications/AppProjection/app/otbImageEnvelope.cxx
+++ b/Modules/Applications/AppProjection/app/otbImageEnvelope.cxx
@@ -56,21 +56,25 @@ private:
 
     // Documentation
     SetDocName("Image Envelope");
-    SetDocLongDescription("Build a vector data containing the polygon of the image envelope.");
+    SetDocLongDescription("Build a vector data containing the image envelope polygon. "
+      "Useful for some projection, you can set the polygon with more points with the sr parameter. "
+      "This filter supports user-specified output projection. "
+      "If no projection is defined, the standard WGS84 projection will be used.");
+
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
 
     AddDocTag(Tags::Geometry);
 
-    AddParameter(ParameterType_InputImage,  "in",   "Input Image");
-    SetParameterDescription("in", "Input image.");
+    AddParameter(ParameterType_InputImage, "in", "Input Image");
+    SetParameterDescription("in", "Input image filename.");
 
-    AddParameter(ParameterType_OutputVectorData,  "out",   "Output Vector Data");
-    SetParameterDescription("out", "Vector data file containing the envelope");
+    AddParameter(ParameterType_OutputVectorData, "out", "Output Vector Data");
+    SetParameterDescription("out", "Vector data file containing the envelope.");
 
     AddParameter(ParameterType_Int, "sr", "Sampling Rate");
-    SetParameterDescription("sr", "Sampling rate for image edges (in pixel)");
+    SetParameterDescription("sr", "Sampling rate for image edges (in pixel).");
     SetDefaultParameterInt("sr",0);
     MandatoryOff("sr");
     DisableParameter("sr");
diff --git a/Modules/Applications/AppSARCalibration/app/otbSARCalibration.cxx b/Modules/Applications/AppSARCalibration/app/otbSARCalibration.cxx
index d38349f8eab904fec0c2b4bba68648015bcc0295..4a91dda2f5183e34a8bd470684302805b54d5609 100644
--- a/Modules/Applications/AppSARCalibration/app/otbSARCalibration.cxx
+++ b/Modules/Applications/AppSARCalibration/app/otbSARCalibration.cxx
@@ -52,7 +52,7 @@ private:
 
     // Documentation
     SetDocName("SAR Radiometric calibration");
-    SetDocLongDescription("The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products).\n");
+    SetDocLongDescription("The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products).");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
diff --git a/Modules/Applications/AppSARCalibration/app/otbSARDeburst.cxx b/Modules/Applications/AppSARCalibration/app/otbSARDeburst.cxx
index 98bbd5924b8ffb5520adcfd53ceaa7d0389755ef..01e09464a313ffdabb1871be4266b8ade73948a0 100644
--- a/Modules/Applications/AppSARCalibration/app/otbSARDeburst.cxx
+++ b/Modules/Applications/AppSARCalibration/app/otbSARDeburst.cxx
@@ -47,23 +47,38 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("SARDeburst");
-    SetDescription("This application performs a deburst operation by removing redundant lines. \n");
+    SetDescription("This application performs deburst of Sentinel1 IW SLC images by removing redundant lines.\n");
 
     // Documentation
     SetDocName("SAR Deburst");
-    SetDocLongDescription("This application performs a deburst operation by removing redundant lines between burst. This operation is useful when dealing with Sentinel1 IW SLC products, where each subswath is composed of several overlapping burst separated by black lines. Lines to remove are computed by SAR sensor model in OSSIM plugins. The output image is smaller in azimuth direction than the input line, because of removed lines. Note that the output sensor model is updated accordingly. This deburst filter is the perfect preprocessing step to orthorectify S1 IW SLC product with OTB without suffering from artifacts caused by bursts separation.\n");
-    SetDocLimitations("Only Sentinel1 IW SLC products are supported for now.");
+    SetDocLongDescription("Sentinel1 IW SLC products are composed of several burst overlapping in"
+                          " azimuth time for each subswath, separated by black lines [1]. The deburst"
+                          " operation consist in generating a continuous image in terms of azimuth"
+                          " time, by removing black separation lines as well as redundant lines"
+                          " between bursts.\n\n"
+                          
+                          "Note that the output sensor model is updated accordingly. This deburst"
+                          " operation is the perfect preprocessing step to orthorectify S1 IW SLC"
+                          " product with OTB [2] without suffering from artifacts caused by"
+                          " bursts separation.");
+    
+    SetDocLimitations("Only Sentinel1 IW SLC products are supported for now. Processing of"
+                      " other Sentinel1 modes or TerrasarX images will result in no changes in"
+                      " the image and metadata. Images from other sensors will lead to an"
+                      " error.");
+    
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso("OrthoRectification");
+    SetDocSeeAlso("[1] Sentinel1 User Handbook, p. 52: https://sentinel.esa.int/documents/247904/685163/Sentinel-1_User_Handbook\n"
+                  "[2] OrthoRectification application");
 
-    AddDocTag(Tags::Calibration);
     AddDocTag(Tags::SAR);
+    AddDocTag(Tags::Calibration);
 
-    AddParameter(ParameterType_InputImage,  "in", "Input Image");
-    SetParameterDescription("in", "Input image");
+    AddParameter(ParameterType_InputImage,  "in", "Input Sentinel1 IW SLC Image");
+    SetParameterDescription("in", "Raw Sentinel1 IW SLC image, or any extract of such made by OTB (geom file needed)");
 
     AddParameter(ParameterType_OutputImage,  "out", "Output Image");
-    SetParameterDescription("out", "Output deburst image");
+    SetParameterDescription("out", "Deburst image, with updated geom file that can be further used by Orthorectification application. If the input image is a raw Sentinel1 product, uint16 output type should be used (encoding of S1 product). Otherwise, output type should match type of input image.");
 
     AddRAMParameter();
 
diff --git a/Modules/Applications/AppSARDecompositions/app/otbSARDecompositions.cxx b/Modules/Applications/AppSARDecompositions/app/otbSARDecompositions.cxx
index 8d0e99cffc0c68bc3239114eb1c76bf031a0e2b3..155795417f8c78b96317cd7676e4ed1294be90b4 100644
--- a/Modules/Applications/AppSARDecompositions/app/otbSARDecompositions.cxx
+++ b/Modules/Applications/AppSARDecompositions/app/otbSARDecompositions.cxx
@@ -97,7 +97,7 @@ private:
                           "In the coherent case, only the Pauli decomposition is available.\n"
                           "In the incoherent case, there the decompositions available : Huynen, Barnes, and H-alpha-A.\n"   
 						  "User must provide three one-band complex images HH, HV or VH, and VV (mono-static case <=> HV = VH).\n"
-						  "Incoherent decompositions consist in averaging 3x3 complex coherency/covariance matrices; the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize.\n "
+						  "Incoherent decompositions consist in averaging 3x3 complex coherency/covariance matrices; the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize."
 						  );
 						  
 						  
diff --git a/Modules/Applications/AppSARPolarMatrixConvert/app/otbSARPolarMatrixConvert.cxx b/Modules/Applications/AppSARPolarMatrixConvert/app/otbSARPolarMatrixConvert.cxx
index e558ac68a08f7c3751a843556588c65860ca2e17..9c8c06211234eef4f9f8207c1762e6f10fbe88fb 100644
--- a/Modules/Applications/AppSARPolarMatrixConvert/app/otbSARPolarMatrixConvert.cxx
+++ b/Modules/Applications/AppSARPolarMatrixConvert/app/otbSARPolarMatrixConvert.cxx
@@ -222,7 +222,7 @@ private:
     
     "11 sinclairtomueller --> Sinclair matrix to Mueller matrix (input : 4 x 1 complex channel (HH, HV, VH, VV) | output : 16 real channels)\n"
     "12 muellertomcovariance --> Mueller matrix to covariance matrix (input : 16 real channels | output : 6 complex channels)\n"
-    "13 muellertopoldegandpower --> Mueller matrix to polarization degree and power (input : 16 real channels | output : 4 real channels)\n"
+    "13 muellertopoldegandpower --> Mueller matrix to polarization degree and power (input : 16 real channels | output : 4 real channels)"
 
  );
 						  
diff --git a/Modules/Applications/AppSARPolarSynth/test/CMakeLists.txt b/Modules/Applications/AppSARPolarSynth/test/CMakeLists.txt
index e77967b05c1ca08b7f9d908a5ebce567a2273572..ebdaca7c686939019b1e019b25515494e919043d 100644
--- a/Modules/Applications/AppSARPolarSynth/test/CMakeLists.txt
+++ b/Modules/Applications/AppSARPolarSynth/test/CMakeLists.txt
@@ -23,7 +23,7 @@ otb_module_test()
 
 otb_test_application(NAME  apTvSARPolarSynth
                      APP  SARPolarSynth
-                     OPTIONS -in ${INPUTDATA}/RSAT2_AltonaExtract_1000_1000_100_100.hdr
+                     OPTIONS -in ${INPUTDATA}/RSAT2_AltonaExtract_1000_1000_100_100.tif
                	             -out ${TEMP}/resApMultiPolarimetricSynthesis1.tif
                              -psii 10.0 
                              -khii 0.0
diff --git a/Modules/Applications/AppSARUtils/app/CMakeLists.txt b/Modules/Applications/AppSARUtils/app/CMakeLists.txt
index f0e7132c08c68baa6c95c2bc7dd114974e26278f..6f0e019f716c745c675961dc0e61923595171dd3 100644
--- a/Modules/Applications/AppSARUtils/app/CMakeLists.txt
+++ b/Modules/Applications/AppSARUtils/app/CMakeLists.txt
@@ -1,5 +1,8 @@
 set(OTBAppSARUtils_LINK_LIBS
   ${OTBSARUtils_LIBRARIES}
+  {OTBImageNoise_LIBRARIES}
+  ${OTBImageBase_LIBRARIES}
+  ${OTBITK_LIBRARIES}
   ${OTBApplicationEngine_LIBRARIES}
 )
 
@@ -7,3 +10,8 @@ otb_create_application(
   NAME           ComputeModulusAndPhase
   SOURCES        otbComputeModulusAndPhase.cxx
   LINK_LIBRARIES ${${otb-module}_LIBRARIES})
+
+otb_create_application(
+  NAME           Despeckle
+  SOURCES        otbDespeckle.cxx
+  LINK_LIBRARIES ${${otb-module}_LIBRARIES})
diff --git a/Modules/Applications/AppSARUtils/app/otbComputeModulusAndPhase.cxx b/Modules/Applications/AppSARUtils/app/otbComputeModulusAndPhase.cxx
index a1ec51a1d3df70c47a5bb4016b7f93d6fd98395d..39db311e799737b730973d68c5156d273366896b 100644
--- a/Modules/Applications/AppSARUtils/app/otbComputeModulusAndPhase.cxx
+++ b/Modules/Applications/AppSARUtils/app/otbComputeModulusAndPhase.cxx
@@ -20,11 +20,11 @@
 
 #include "otbWrapperApplication.h"
 #include "otbWrapperApplicationFactory.h"
-#include <otbMultiToMonoChannelExtractROI.h>
+#include "otbMultiToMonoChannelExtractROI.h"
 
 #include "itkComplexToPhaseImageFilter.h"
 #include "itkComplexToModulusImageFilter.h"
-#include <itkMacro.h>
+#include "itkMacro.h"
 
 namespace otb
 {
@@ -68,21 +68,26 @@ private:
       "complex SAR image. The input should be a single band image with "
       "complex pixels."
     );
-    SetDocLimitations("None");
+    SetDocLimitations("The application takes as input single band image with complex pixels.");
     SetDocAuthors("Alexia Mondot (alexia.mondot@c-s.fr) and Mickael Savinaud (mickael.savinaud@c-s.fr)");
-    SetDocSeeAlso("SARPolarMatrixConvert, SARPolarSynth");
-    AddDocTag(Tags::SAR);
+    SetDocSeeAlso("Despeckle, SARPolarMatrixConvert, SARPolarSynth");
 
+    AddDocTag(Tags::SAR);
+    AddDocTag(Tags::Manip);
     // Input images
     AddParameter(ParameterType_ComplexInputImage,  "in",   "Input Image");
     SetParameterDescription("in", "Input image (complex single band)");
 
     // Outputs
     AddParameter(ParameterType_OutputImage, "modulus", "Modulus");
-    SetParameterDescription("modulus", "Modulus of the input: sqrt(real*real + imag*imag).");
-
+    SetParameterDescription("modulus", "Modulus of the input image computes with the\n"
+                            "following formula: :math:`\\sqrt{real*real + imag*imag}` where real and imag \n"
+                            "are respectively the real and the imaginary part of the input complex image.\n");
+    
     AddParameter(ParameterType_OutputImage, "phase", "Phase");
-    SetParameterDescription("phase", "Phase of the input: atan2(imag, real).");
+    SetParameterDescription("phase", "Phase of the input image computes with the following formula:\n"
+    ":math:`\\tan^{-1}(\\frac{imag}{real})` where real and imag are respectively the real and\n"
+    "the imaginary part of the input complex image.");
 
     AddRAMParameter();
 
diff --git a/Modules/Applications/AppFiltering/app/otbDespeckle.cxx b/Modules/Applications/AppSARUtils/app/otbDespeckle.cxx
similarity index 64%
rename from Modules/Applications/AppFiltering/app/otbDespeckle.cxx
rename to Modules/Applications/AppSARUtils/app/otbDespeckle.cxx
index 2d3a2de8d2d280d82070dbffff49e44f0c18d4d4..f469402397ec95185ecdfb5ed8c99009b550b594 100644
--- a/Modules/Applications/AppFiltering/app/otbDespeckle.cxx
+++ b/Modules/Applications/AppSARUtils/app/otbDespeckle.cxx
@@ -61,13 +61,44 @@ private:
 
     // Documentation
     SetDocName("Despeckle");
-    SetDocLongDescription("This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.");
-    SetDocLimitations("None");
+    SetDocLongDescription("SAR images are affected by speckle noise that inherently exists in and which"
+     " degrades the image quality. It is caused by the coherent nature of"
+     " back-scattered waves from multiple distributed targets. It is locally strong"
+     " and it increases the mean Grey level of a local area. \n\n"
+     "Reducing the speckle noise enhances radiometric resolution but tend to decrease the spatial resolution."
+     "Several different methods are used to eliminate speckle noise, based upon"
+     " different mathematical models of the phenomenon. The application includes four"
+     " methods: Lee [1], Frost [2], GammaMAP [3] and Kuan [4]. \n\n"
+     "We sum up below the basic principle of this four methods:\n"
+      "  * Lee : Estimate the signal by mean square error minimization (MMSE) on a sliding window.\n"
+      "  * Frost : Also derived from the MMSE criteria with a weighted sum of the values within the window. The weighting factors decrease with distance from the pixel of interest.\n"
+      "  * GammaMAP  : Derived under the assumption of the image follows a Gamma distribution.\n"
+      "  * Kuan : Also derived from the MMSE criteria under the assumption of non stationary mean and variance. It is quite similar to Lee filter in form."
+      );
+
+    SetDocLimitations("The application does not handle complex image as input.");
+
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
+
+    SetDocSeeAlso("[1] J. Lee. Digital image enhancement and noise filtering by"
+                  "use of local statistics. IEEE Transactions on Pattern Analysis and Machine"
+                  "Intelligence, 2:165–168, 1980.\n"
+                  "[2] V. S. Frost, et al., A Model for Radar Images and Its"
+                  "Application to Adaptive Digital Filtering of Multiplicative"
+                  "Noise, IEEE Trans. Pattern Anal., Machine Intell., vol. 4,"
+                  "no. 2, pp. 157-166, Mar. 1982.\n"
+                  "[3] A. Lopes, E. Nezry, R. Touzi and H. Laur, Maximum A"
+                  "Posteriori Speckle Filtering And First Order Texture Models"
+                  "In Sar Images, 10th" "Annual International Symposium on"
+                  "Geoscience and Remote Sensing, 1990,pp. 2409-2412.  doi:"
+                  "10.1109/IGARSS.1990.689026\n"
+                  "[4] Kuan, D.  T., Sawchuk, A.  A., Strand, T.  C, and Chavel,"
+                  "P., 1987.  Adaptive restoration of image with speckle.  IEEE"
+                  "Trans on Acoustic Speech and Signal Processing, 35,"
+                  "pp. 373-383.");
 
     AddDocTag(Tags::Filter);
-	AddDocTag(Tags::SAR);
+	  AddDocTag(Tags::SAR);
 
     AddParameter(ParameterType_InputImage,  "in",   "Input Image");
     SetParameterDescription("in", "Input image.");
@@ -76,39 +107,47 @@ private:
 
     AddRAMParameter();
 
-    AddParameter(ParameterType_Choice,"filter","speckle filtering method");
+    AddParameter(ParameterType_Choice,"filter","Speckle filtering method");
+    
     AddChoice("filter.lee","Lee");
     SetParameterDescription("filter.lee","Lee filter");
+
     AddChoice("filter.frost","Frost");
     SetParameterDescription("filter.frost","Frost filter");
+
     AddChoice("filter.gammamap","GammaMap");
     SetParameterDescription("filter.gammamap","GammaMap filter");
+
     AddChoice("filter.kuan","Kuan");
     SetParameterDescription("filter.kuan","Kuan filter");
 
     AddParameter(ParameterType_Int,"filter.lee.rad","Radius");
-    SetParameterDescription("filter.lee.rad","Radius for lee filter");
+    SetParameterDescription("filter.lee.rad","Radius in pixel");
 
-    AddParameter(ParameterType_Float,"filter.lee.nblooks","nb looks");
-    SetParameterDescription("filter.lee.nblooks","Nb looks for lee filter");
+    AddParameter(ParameterType_Float,"filter.lee.nblooks","Number of looks");
+    SetParameterDescription("filter.lee.nblooks","Number of looks in the input image.");
 
     AddParameter(ParameterType_Int,"filter.frost.rad","Radius");
-    SetParameterDescription("filter.frost.rad","Radius for frost filter");
-
-    AddParameter(ParameterType_Float,"filter.frost.deramp","deramp");
-    SetParameterDescription("filter.frost.deramp","Decrease factor declaration");
+    SetParameterDescription("filter.frost.rad","Radius in pixel.");
+
+    AddParameter(ParameterType_Float,"filter.frost.deramp","Deramp factor");
+    SetParameterDescription("filter.frost.deramp","factor use to control the\n"
+       "exponential function used to weight effect of the distance between the\n"
+       "central pixel and its neighborhood. Increasing the deramp parameter will\n"
+       "lead to take more into account pixels farther from the center and\n"
+       "therefore increase the smoothing effects.");
     
     AddParameter(ParameterType_Int,"filter.gammamap.rad","Radius");
-    SetParameterDescription("filter.gammamap.rad","Radius for GammaMAP filter");
+    SetParameterDescription("filter.gammamap.rad","Radius in pixel.");
 
-    AddParameter(ParameterType_Float,"filter.gammamap.nblooks","nb looks");
-    SetParameterDescription("filter.gammamap.nblooks","Nb looks for GammaMAP filter");
+    AddParameter(ParameterType_Float,"filter.gammamap.nblooks","Number of looks");
+    SetParameterDescription("filter.gammamap.nblooks","Number of looks in the input image.");
     
     AddParameter(ParameterType_Int,"filter.kuan.rad","Radius");
-    SetParameterDescription("filter.kuan.rad","Radius for Kuan filter");
+    SetParameterDescription("filter.kuan.rad","Radius in pixel.");
 
-    AddParameter(ParameterType_Float,"filter.kuan.nblooks","nb looks");
-    SetParameterDescription("filter.kuan.nblooks","Nb looks for Kuan filter");
+    AddParameter(ParameterType_Float,"filter.kuan.nblooks","Number of looks");
+    SetParameterDescription("filter.kuan.nblooks","Number of looks in the input image.");
 
     // Default values
     SetDefaultParameterInt("filter.lee.rad", 1);
diff --git a/Modules/Applications/AppSARUtils/otb-module.cmake b/Modules/Applications/AppSARUtils/otb-module.cmake
index 41a1b43467aa97d35721a46dd6f4e4f4ad6b04be..964acb5a4f4f01fcfc86bd030df4e067da8af680 100644
--- a/Modules/Applications/AppSARUtils/otb-module.cmake
+++ b/Modules/Applications/AppSARUtils/otb-module.cmake
@@ -3,6 +3,10 @@ set(DOCUMENTATION "SAR Utils application.")
 otb_module(OTBAppSARUtils
   DEPENDS
     OTBApplicationEngine
+    OTBImageNoise
+    OTBImageBase
+    OTBITK
+    
   TEST_DEPENDS
     OTBTestKernel
     OTBCommandLine
diff --git a/Modules/Applications/AppSARUtils/test/CMakeLists.txt b/Modules/Applications/AppSARUtils/test/CMakeLists.txt
index 65dc6b75a9de038c360f9671a1a83c357a020bed..4c7a02ec56f895c2712aaa68237b8d643fe998d7 100644
--- a/Modules/Applications/AppSARUtils/test/CMakeLists.txt
+++ b/Modules/Applications/AppSARUtils/test/CMakeLists.txt
@@ -1,13 +1,79 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
 otb_module_test()
 #----------- ComputeModulusAndPhase TESTS ----------------
 otb_test_application(NAME apTvUtComputeModulusAndPhase_1inputComplex
-                     APP  ComputeModulusAndPhase
-                     OPTIONS -in ${INPUTDATA}/monobandComplexFloat.tif
-                             -modulus ${TEMP}/apTvUtMod1inputComplex.tif
-                             -phase ${TEMP}/apTvUtPha1inputComplex.tif
-                     VALID   --compare-n-images ${EPSILON_6} 2
-                             ${BASELINE}/Mod_monobandComplexFloat.tif
-                             ${TEMP}/apTvUtMod1inputComplex.tif
-                             ${BASELINE}/Pha_monobandComplexFloat.tif
-                             ${TEMP}/apTvUtPha1inputComplex.tif
-                     )
+  APP  ComputeModulusAndPhase
+  OPTIONS -in ${INPUTDATA}/monobandComplexFloat.tif
+  -modulus ${TEMP}/apTvUtMod1inputComplex.tif
+  -phase ${TEMP}/apTvUtPha1inputComplex.tif
+  VALID   --compare-n-images ${EPSILON_6} 2
+  ${BASELINE}/Mod_monobandComplexFloat.tif
+  ${TEMP}/apTvUtMod1inputComplex.tif
+  ${BASELINE}/Pha_monobandComplexFloat.tif
+  ${TEMP}/apTvUtPha1inputComplex.tif
+  )
+
+#----------- Despeckle TESTS ----------------
+
+otb_test_application(NAME  apTvDespeckleLee
+  APP  Despeckle
+  OPTIONS -in ${INPUTDATA}/GomaAvant.tif
+  -out ${TEMP}/bfFiltreLee_05_05_12_app.tif
+  -filter lee
+  -filter.lee.rad 5
+  -filter.lee.nblooks 12
+  VALID   --compare-image ${EPSILON_7}
+  ${BASELINE}/bfFiltreLee_05_05_12.tif
+  ${TEMP}/bfFiltreLee_05_05_12_app.tif)
+
+otb_test_application(NAME  apTvDespeckleFrost
+  APP  Despeckle
+  OPTIONS -in ${INPUTDATA}/GomaAvant.tif
+  -out ${TEMP}/bfFiltreFrost_05_05_12_app.tif
+  -filter frost
+  -filter.frost.rad 5
+  -filter.frost.deramp 0.1
+  VALID   --compare-image ${EPSILON_7}
+  ${BASELINE}/bfFiltreFrost_05_05_12_app.tif
+  ${TEMP}/bfFiltreFrost_05_05_12_app.tif)
+
+otb_test_application(NAME  apTvDespeckleGammaMAP
+  APP  Despeckle
+  OPTIONS -in ${INPUTDATA}/GomaAvant.tif
+  -out ${TEMP}/bfFiltreGammaMAP_05_05_12_app.tif
+  -filter gammamap
+  -filter.gammamap.rad 5
+  -filter.gammamap.nblooks 12
+  VALID   --compare-image ${EPSILON_7}
+  ${BASELINE}/bfFiltreGammaMAP_05_05_12.tif
+  ${TEMP}/bfFiltreGammaMAP_05_05_12_app.tif)                      
+
+otb_test_application(NAME  apTvDespeckleKuan
+  APP  Despeckle
+  OPTIONS -in ${INPUTDATA}/GomaAvant.tif
+  -out ${TEMP}/bfFiltreKuan_05_05_12_app.tif
+  -filter kuan
+  -filter.kuan.rad 5
+  -filter.kuan.nblooks 12
+  VALID   --compare-image ${EPSILON_7}
+  ${BASELINE}/bfFiltreKuan_05_05_12.tif
+  ${TEMP}/bfFiltreKuan_05_05_12_app.tif)
diff --git a/Modules/Applications/AppSegmentation/app/CMakeLists.txt b/Modules/Applications/AppSegmentation/app/CMakeLists.txt
index 097d9971f16a23b266e64e28469fca2444e15f0f..f55ae3d7f91d607359b5024a17f89136428edf76 100644
--- a/Modules/Applications/AppSegmentation/app/CMakeLists.txt
+++ b/Modules/Applications/AppSegmentation/app/CMakeLists.txt
@@ -75,3 +75,8 @@ otb_create_application(
   NAME           MeanShiftSmoothing
   SOURCES        otbMeanShiftSmoothing.cxx
   LINK_LIBRARIES ${${otb-module}_LIBRARIES})
+
+otb_create_application(
+  NAME           LargeScaleMeanShift
+  SOURCES        otbLargeScaleMeanShift.cxx
+  LINK_LIBRARIES ${${otb-module}_LIBRARIES})
diff --git a/Modules/Applications/AppSegmentation/app/otbLSMSSegmentation.cxx b/Modules/Applications/AppSegmentation/app/otbLSMSSegmentation.cxx
index dd624673d0490e3d74402faba8a41f904868aa60..93694cc420dcc271c6dff0ac551d43d519acd2b4 100644
--- a/Modules/Applications/AppSegmentation/app/otbLSMSSegmentation.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbLSMSSegmentation.cxx
@@ -217,51 +217,83 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("LSMSSegmentation");
-    SetDescription("Second step of the exact Large-Scale Mean-Shift segmentation workflow.");
+    SetDescription("This application performs the second step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS) [1].");
 
     SetDocName("Exact Large-Scale Mean-Shift segmentation, step 2");
-    SetDocLongDescription("This application performs the second step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Filtered range image and spatial image should be created with the MeanShiftSmoothing application, with modesearch parameter disabled. If spatial image is not set, the application will only process the range image and spatial radius parameter will not be taken into account. This application will produce a labeled image where neighbor pixels whose range distance is below range radius (and optionally spatial distance below spatial radius) will be grouped together into the same cluster. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results. Please note that this application will generate a lot of temporary files (as many as the number of tiles), and will therefore require twice the size of the final result in term of disk space. The cleanup option (activated by default) allows removing all temporary file as soon as they are not needed anymore (if cleanup is activated, tmpdir set and tmpdir does not exists before running the application, it will be removed as well during cleanup). The tmpdir option allows defining a directory where to write the temporary files. Please also note that the output image type should be set to uint32 to ensure that there are enough labels available.");
-    SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
+    SetDocLongDescription("This application will produce a labeled image where neighbor pixels"
+                          " whose range distance is below range radius (and optionally spatial"
+                          " distance below spatial radius) will be grouped together into the same"
+                          " cluster. For large images one can use the tilesizex and tilesizey"
+                          " parameters for tile-wise processing, with the guarantees of identical"
+                          " results.\n\n"
+                          "Filtered range image and spatial image should be created with the"
+                          " MeanShiftSmoothing application outputs (fout and foutpos) [2], with"
+                          " modesearch parameter disabled. If spatial image is not set, the"
+                          " application will only process the range image and spatial radius"
+                          " parameter will not be taken into account.\n\n"
+                          "Please note that this application will generate a lot of temporary"
+                          " files (as many as the number of tiles), and will therefore require"
+                          " twice the size of the final result in term of disk space. The cleanup"
+                          " option (activated by default) allows removing all temporary file as"
+                          " soon as they are not needed anymore (if cleanup is activated, tmpdir"
+                          " set and tmpdir does not exists before running the application, it will"
+                          " be removed as well during cleanup). The tmpdir option allows defining"
+                          " a directory where to write the temporary files.\n\n"
+                          "Please also note that the output image type should be set to uint32 to"
+                          " ensure that there are enough labels available.\n\n"
+                          "The output of this application can be passed to the"
+                          " LSMSSmallRegionMerging [3] or LSMSVectorization [4] applications to"
+                          " complete the LSMS workflow.");
+    SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation"
+                      " workflow (LSMS) [1] and may not be suited for any other purpose. This"
+                      " application is not compatible with in-memory connection since it does"
+                      " its own internal streaming.");
     SetDocAuthors("David Youssefi");
-    SetDocSeeAlso("MeanShiftSmoothing, LSMSSmallRegionsMerging, LSMSVectorization");
+    SetDocSeeAlso( "[1] Michel, J., Youssefi, D., & Grizonnet, M. (2015). Stable"
+                   " mean-shift algorithm and its application to the segmentation of"
+                   " arbitrarily large remote sensing images. IEEE Transactions on"
+                   " Geoscience and Remote Sensing, 53(2), 952-964.\n"
+                   "[2] MeanShiftSmoothing\n"
+                   "[3] LSMSSmallRegionsMerging\n"
+                   "[4] LSMSVectorization");
     AddDocTag(Tags::Segmentation);
     AddDocTag("LSMS");
 
     AddParameter(ParameterType_InputImage,  "in",    "Filtered image");
-    SetParameterDescription( "in", "The filtered image (cf. Adaptive MeanShift Smoothing application)." );
-    AddParameter(ParameterType_InputImage,  "inpos",    "Spatial image");
-    SetParameterDescription( "inpos", " The spatial image. Spatial input is the displacement map (output of the Adaptive MeanShift Smoothing application)." );
+    SetParameterDescription( "in", "The filtered image, corresponding to the fout output parameter of the MeanShiftSmoothing application." );
+    AddParameter(ParameterType_InputImage,  "inpos",    "Filtered position image");
+    SetParameterDescription( "inpos", " The filtered position image, corresponding to the foutpos output parameter of the MeanShiftSmoothing application.");
     MandatoryOff("inpos");
 
-    AddParameter(ParameterType_OutputImage, "out", "Output Image");
-    SetParameterDescription( "out", "The output image. The output image is the segmentation of the filtered image. It is recommended to set the pixel type to uint32." );
+    AddParameter(ParameterType_OutputImage, "out", "Output labeled Image");
+    SetParameterDescription( "out", "This output contains the segmented image, where each pixel value is the unique integer label of the segment it belongs to. It is recommended to set the pixel type to uint32." );
     SetDefaultOutputPixelType("out",ImagePixelType_uint32);
 
     AddParameter(ParameterType_Float, "spatialr", "Spatial radius");
-    SetParameterDescription("spatialr", "Spatial radius of the neighborhood.");
+    SetParameterDescription("spatialr", "Threshold on Spatial distance to consider pixels in the same segment. A good value is half the spatial radius used in the MeanShiftSmoothing application (spatialr parameter).");
     SetDefaultParameterFloat("spatialr", 5);
     SetMinimumParameterFloatValue("spatialr", 0);
     MandatoryOff("spatialr");
     
     AddParameter(ParameterType_Float, "ranger", "Range radius");
-    SetParameterDescription("ranger", "Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space.");
+    SetParameterDescription("ranger", "Threshold on spectral signature euclidean distance (expressed in radiometry unit) to consider pixels in the same segment. A good value is half the range radius used in the MeanShiftSmoothing application (ranger parameter).");
     SetDefaultParameterFloat("ranger", 15);
     SetMinimumParameterFloatValue("ranger", 0);
     MandatoryOff("ranger");
 
-    AddParameter(ParameterType_Int, "minsize", "Minimum Region Size");
-    SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is deleted.");
+    AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
+    SetParameterDescription("minsize", "Minimum Segment Size. If, after the segmentation, a segment is of size lower than this criterion, the segment is discarded.");
     SetDefaultParameterInt("minsize", 0);
     SetMinimumParameterIntValue("minsize", 0);
     MandatoryOff("minsize");
 
     AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
-    SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
+    SetParameterDescription("tilesizex", "Size of tiles along the X-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizex", 500);
     SetMinimumParameterIntValue("tilesizex", 1);
 
     AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
-    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
+    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizey", 500);
     SetMinimumParameterIntValue("tilesizey", 1);
 
@@ -272,7 +304,7 @@ private:
 
     AddParameter(ParameterType_Empty,"cleanup","Temporary files cleaning");
     EnableParameter("cleanup");
-    SetParameterDescription("cleanup","If activated, the application will try to clean all temporary files it created");
+    SetParameterDescription("cleanup","If activated, the application will try to remove all temporary files it created.");
     MandatoryOff("cleanup");
 
     // Doc example parameter settings
diff --git a/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx b/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
index dc04847b2c8e5c4137cb6dd695368786ca33835f..14c8354a143503d61ddbc3680512d5eb6ccb5143 100644
--- a/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbLSMSSmallRegionsMerging.cxx
@@ -76,38 +76,58 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("LSMSSmallRegionsMerging");
-    SetDescription("Third (optional) step of the exact Large-Scale Mean-Shift segmentation workflow.");
+    SetDescription("This application performs the third (optional) step of the exact Large-Scale Mean-Shift segmentation workflow [1].");
 
     SetDocName("Exact Large-Scale Mean-Shift segmentation, step 3 (optional)");
-    SetDocLongDescription("This application performs the third step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image) and the original image, it will merge regions whose size in pixels is lower than minsize parameter with the adjacent regions with the adjacent region with closest radiometry and acceptable size. Small regions will be processed by size: first all regions of area, which is equal to 1 pixel will be merged with adjacent region, then all regions of area equal to 2 pixels, until regions of area minsize. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.");
-    SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
+    SetDocLongDescription("Given a segmentation result (can be the out output parameter of the"
+                          " LSMSSegmentation application [2]) and the original image, it will"
+                          " merge segments whose size in pixels is lower than minsize parameter"
+                          " with the adjacent segments with the adjacent segment with closest"
+                          " radiometry and acceptable size.\n\n"
+                          "Small segments will be processed by increasing size: first all segments"
+                          " for which area is equal to 1 pixel will be merged with adjacent"
+                          " segments, then all segments of area equal to 2 pixels will be processed,"
+                          " until segments of area minsize. For large images one can use the"
+                          " tilesizex and tilesizey parameters for tile-wise processing, with the"
+                          " guarantees of identical results.\n\n"
+                          "The output of this application can be passed to the"
+                          " LSMSVectorization application [3] to complete the LSMS workflow.");
+    SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation"
+                      " workflow (LSMS) and may not be suited for any other purpose. This"
+                      " application is not compatible with in-memory connection since it does"
+                      " its own internal streaming.");
     SetDocAuthors("David Youssefi");
-    SetDocSeeAlso("LSMSSegmentation, LSMSVectorization, MeanShiftSmoothing");
+    SetDocSeeAlso( "[1] Michel, J., Youssefi, D., & Grizonnet, M. (2015). Stable"
+                   " mean-shift algorithm and its application to the segmentation of"
+                   " arbitrarily large remote sensing images. IEEE Transactions on"
+                   " Geoscience and Remote Sensing, 53(2), 952-964.\n"
+                   "[2] LSMSegmentation\n"
+                   "[3] LSMSVectorization");
     AddDocTag(Tags::Segmentation);
     AddDocTag("LSMS");
 
     AddParameter(ParameterType_InputImage,  "in",    "Input image");
-    SetParameterDescription( "in", "The input image." );
+    SetParameterDescription( "in", "The input image, containing initial spectral signatures corresponding to the segmented image (inseg)." );
     AddParameter(ParameterType_InputImage,  "inseg",    "Segmented image");
-    SetParameterDescription( "inseg", " The segmented image input. Segmented image input is the segmentation of the input image." );
+    SetParameterDescription( "inseg", "Segmented image where each pixel value is the unique integer label of the segment it belongs to." );
 
     AddParameter(ParameterType_OutputImage, "out", "Output Image");
-    SetParameterDescription( "out", "The output image. The output image is the input image where the minimal regions have been merged." );
+    SetParameterDescription( "out", "The output image. The output image is the segmented image where the minimal segments have been merged. An ecoding of uint32 is advised." );
     SetDefaultOutputPixelType("out",ImagePixelType_uint32);
 
-    AddParameter(ParameterType_Int, "minsize", "Minimum Region Size");
-    SetParameterDescription("minsize", "Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is merged with the \"nearest\" region (radiometrically).");
+    AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
+    SetParameterDescription("minsize", "Minimum Segment Size. If, after the segmentation, a segment is of size lower than this criterion, the segment is merged with the segment that has the closest sepctral signature.");
     SetDefaultParameterInt("minsize", 50);
     SetMinimumParameterIntValue("minsize", 0);
     MandatoryOff("minsize");
 
     AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
-    SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
+    SetParameterDescription("tilesizex", "Size of tiles along the X-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizex", 500);
     SetMinimumParameterIntValue("tilesizex", 1);
 
     AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
-    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
+    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizey", 500);
     SetMinimumParameterIntValue("tilesizey", 1);
 
diff --git a/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx b/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
index aa3ea2a1be6bb89977ebe11083f27168bf92ecf3..166b87141dc47b313e1eb5b388f55cbfd2dccb01 100644
--- a/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbLSMSVectorization.cxx
@@ -69,31 +69,46 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("LSMSVectorization");
-    SetDescription("Fourth step of the exact Large-Scale Mean-Shift segmentation workflow.");
+    SetDescription("This application performs the fourth step of the exact Large-Scale Mean-Shift segmentation workflow [1].");
 
     SetDocName("Exact Large-Scale Mean-Shift segmentation, step 4");
-    SetDocLongDescription("This application performs the fourth step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image), that may have been processed for small regions merging or not, it will convert it to a GIS vector file containing one polygon per segment. Each polygon contains additional fields: mean and variance of each channels from input image (in parameter), segmentation image label, number of pixels in the polygon. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.");
+    SetDocLongDescription("Given a segmentation result (label image), that may come from the"
+                          " LSMSSegmentation [2] application (out parameter) or have been"
+                          " processed for small regions merging [3] (out parameter), it will"
+                          " convert it to a GIS vector file containing one polygon per"
+                          " segment. Each polygon contains additional fields: mean and variance of"
+                          " each channels from input image (in parameter), segmentation image"
+                          " label, number of pixels in the polygon. For large images one can use"
+                          " the tilesizex and tilesizey parameters for tile-wise processing, with"
+                          " the guarantees of identical results.");
     SetDocLimitations("This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.");
     SetDocAuthors("David Youssefi");
-    SetDocSeeAlso("MeanShiftSmoothing, LSMSSegmentation, LSMSSmallRegionsMerging");
+
+    SetDocSeeAlso( "[1] Michel, J., Youssefi, D., & Grizonnet, M. (2015). Stable"
+                   " mean-shift algorithm and its application to the segmentation of"
+                   " arbitrarily large remote sensing images. IEEE Transactions on"
+                   " Geoscience and Remote Sensing, 53(2), 952-964.\n"
+                   "[2] LSMSegmentation\n"
+                   "[3] LSMSmallRegionMerging");
+
     AddDocTag(Tags::Segmentation);
     AddDocTag("LSMS");
 
     AddParameter(ParameterType_InputImage, "in", "Input Image");
-    SetParameterDescription( "in", "The input image." );
+    SetParameterDescription( "in", "The input image, containing initial spectral signatures corresponding to the segmented image (inseg)." );
     AddParameter(ParameterType_InputImage,  "inseg",    "Segmented image");
-    SetParameterDescription( "inseg", " The segmented image input. Segmented image input is the segmentation of the input image." );
+    SetParameterDescription( "inseg", "Segmented image where each pixel value is the unique integer label of the segment it belongs to.");
 
     AddParameter(ParameterType_OutputFilename, "out", "Output GIS vector file");
     SetParameterDescription( "out", "The output GIS vector file, representing the vectorized version of the segmented image where the features of the polygons are the radiometric means and variances." );
 
     AddParameter(ParameterType_Int, "tilesizex", "Size of tiles in pixel (X-axis)");
-    SetParameterDescription("tilesizex", "Size of tiles along the X-axis.");
+    SetParameterDescription("tilesizex", "Size of tiles along the X-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizex", 500);
     SetMinimumParameterIntValue("tilesizex", 1);
 
     AddParameter(ParameterType_Int, "tilesizey", "Size of tiles in pixel (Y-axis)");
-    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis.");
+    SetParameterDescription("tilesizey", "Size of tiles along the Y-axis for tile-wise processing.");
     SetDefaultParameterInt("tilesizey", 500);
     SetMinimumParameterIntValue("tilesizey", 1);
 
diff --git a/Modules/Applications/AppSegmentation/app/otbLargeScaleMeanShift.cxx b/Modules/Applications/AppSegmentation/app/otbLargeScaleMeanShift.cxx
new file mode 100644
index 0000000000000000000000000000000000000000..d0dfadb1a535ce0c3acafecb650258c3c4d855e1
--- /dev/null
+++ b/Modules/Applications/AppSegmentation/app/otbLargeScaleMeanShift.cxx
@@ -0,0 +1,233 @@
+/*
+ * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+ *
+ * This file is part of Orfeo Toolbox
+ *
+ *     https://www.orfeo-toolbox.org/
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "otbWrapperCompositeApplication.h"
+#include "otbWrapperApplicationFactory.h"
+
+namespace otb
+{
+namespace Wrapper
+{
+
+/**
+ * \class LargeScaleMeanShift
+ *
+ * \brief All-in-one application for the LSMS framework
+ *
+ * This application gathers the 4 steps of the large-scale MeanShift
+ * segmentation framework.
+ * 
+ */
+class LargeScaleMeanShift : public CompositeApplication
+{
+public:
+  /** Standard class typedefs. */
+  typedef LargeScaleMeanShift           Self;
+  typedef CompositeApplication          Superclass;
+  typedef itk::SmartPointer<Self>       Pointer;
+  typedef itk::SmartPointer<const Self> ConstPointer;
+
+/** Standard macro */
+  itkNewMacro(Self);
+
+  itkTypeMacro(LargeScaleMeanShift, otb::CompositeApplication);
+
+private:
+  void DoInit() ITK_OVERRIDE
+    {
+    SetName("LargeScaleMeanShift");
+    SetDescription("Large-scale segmentation using MeanShift");
+
+    // Documentation
+    SetDocName("Large-Scale MeanShift");
+    SetDocLongDescription("This application chains together the 4 steps of the "
+      "MeanShit framework, that is the MeanShiftSmoothing [1], the "
+      "LSMSSegmentation [2], the LSMSSmallRegionsMerging [3] and the "
+      "LSMSVectorization [4].\n\n"
+      "This application can be a preliminary step for an object-based analysis.\n\n"
+      "It generates a vector data file containing the regions extracted with "
+      "the MeanShift algorithm. The spatial and range radius parameters allow "
+      "to adapt the sensitivity of the algorithm depending on the image dynamic "
+      "and resolution. There is a step to remove small regions whose size "
+      "(in pixels) is less than the given 'minsize' parameter. These regions "
+      "are merged to a similar neighbor region. In the output vectors, there "
+      "are additional fields to describe each region. In particular the mean "
+      "and standard deviation (for each band) is computed for each region "
+      "using the input image as support. If an optional 'imfield' image is "
+      "given, it will be used as support image instead."
+      );
+    SetDocLimitations("None");
+    SetDocAuthors("OTB-Team");
+    SetDocSeeAlso("[1] MeanShiftSmoothing\n"
+      "[2] LSMSSegmentation\n"
+      "[3] LSMSSmallRegionsMerging\n"
+      "[4] LSMSVectorization");
+
+    AddDocTag(Tags::Segmentation);
+    AddDocTag("LSMS");
+
+    ClearApplications();
+    AddApplication("MeanShiftSmoothing", "smoothing", "Smoothing step");
+    AddApplication("LSMSSegmentation", "segmentation", "Segmentation step");
+    AddApplication("LSMSSmallRegionsMerging", "merging", "Small region merging step");
+    AddApplication("LSMSVectorization", "vectorization", "Vectorization step");
+
+    ShareParameter("in","smoothing.in");
+    ShareParameter("spatialr","smoothing.spatialr");
+    ShareParameter("ranger","smoothing.ranger");
+    ShareParameter("minsize","merging.minsize");
+
+    ShareParameter("tilesizex","segmentation.tilesizex");
+    ShareParameter("tilesizey","segmentation.tilesizey");
+
+    AddParameter(ParameterType_Choice, "mode","Output mode");
+    SetParameterDescription("mode", "Type of segmented output");
+
+    AddChoice("mode.vector", "Segmentation as vector output");
+    SetParameterDescription("mode.vector","In this mode, the application will "
+      "produce a vector file or database and compute field values for each "
+      "region");
+
+    AddParameter(ParameterType_InputImage, "mode.vector.imfield", "Support image for field computation");
+    SetParameterDescription( "mode.vector.imfield", "This is an optional support image "
+      "that can be used to compute field values in each region. Otherwise, the "
+      "input image is used as support." );
+    MandatoryOff("mode.vector.imfield");
+
+    ShareParameter("mode.vector.out","vectorization.out");
+
+    AddChoice("mode.raster", "Standard segmentation with labeled raster output");
+    SetParameterDescription("mode.raster","In this mode, the application will produce a standard labeled raster.");
+
+    ShareParameter("mode.raster.out","merging.out",
+      "The output raster image",
+      "It corresponds to the output of the small region merging step.");
+
+    AddParameter( ParameterType_Empty, "cleanup", "Temporary files cleaning" );
+    EnableParameter( "cleanup" );
+    SetParameterDescription( "cleanup",
+      "If activated, the application will try to clean all temporary files it created" );
+    MandatoryOff( "cleanup" );
+
+    // Setup RAM
+    ShareParameter("ram","smoothing.ram");
+    Connect("merging.ram","smoothing.ram");
+    Connect("vectorization.ram","smoothing.ram");
+
+    Connect("merging.tilesizex","segmentation.tilesizex");
+    Connect("merging.tilesizey","segmentation.tilesizey");
+    Connect("vectorization.tilesizex","segmentation.tilesizex");
+    Connect("vectorization.tilesizey","segmentation.tilesizey");
+
+    // TODO : this is not exactly true, we used to choose the smoothed image instead
+    Connect("merging.in","smoothing.in");
+
+    // Setup constant parameters
+    GetInternalApplication("smoothing")->SetParameterString("foutpos","foo");
+    GetInternalApplication("smoothing")->EnableParameter("foutpos");
+
+    // Doc example parameter settings
+    SetDocExampleParameterValue("in", "QB_1_ortho.tif");
+    SetDocExampleParameterValue("spatialr", "4");
+    SetDocExampleParameterValue("ranger", "80");
+    SetDocExampleParameterValue("minsize", "16");
+    SetDocExampleParameterValue("mode.vector.out", "regions.shp");
+
+    SetOfficialDocLink();
+    }
+
+  void DoUpdateParameters() ITK_OVERRIDE
+  {}
+
+  void DoExecute() ITK_OVERRIDE
+    {
+    bool isVector(GetParameterString("mode") == "vector");
+    std::string outPath(isVector ?
+      GetParameterString("mode.vector.out"):
+      GetParameterString("mode.raster.out"));
+    std::vector<std::string> tmpFilenames;
+    tmpFilenames.push_back(outPath+std::string("_labelmap.tif"));
+    tmpFilenames.push_back(outPath+std::string("_labelmap.geom"));
+    ExecuteInternal("smoothing");
+    // in-memory connexion here (saves 1 additional update for foutpos)
+    GetInternalApplication("segmentation")->SetParameterInputImage("in",
+      GetInternalApplication("smoothing")->GetParameterOutputImage("fout"));
+    GetInternalApplication("segmentation")->SetParameterInputImage("inpos",
+      GetInternalApplication("smoothing")->GetParameterOutputImage("foutpos"));
+    // temporary file output here
+    GetInternalApplication("segmentation")->SetParameterString("out",
+      tmpFilenames[0]);
+    // take half of previous radii
+    GetInternalApplication("segmentation")->SetParameterFloat("spatialr",
+      0.5 * (double)GetInternalApplication("smoothing")->GetParameterInt("spatialr"));
+    GetInternalApplication("segmentation")->SetParameterFloat("ranger",
+      0.5 * GetInternalApplication("smoothing")->GetParameterFloat("ranger"));
+    GetInternalApplication("segmentation")->ExecuteAndWriteOutput();
+
+    GetInternalApplication("merging")->SetParameterString("inseg",
+      tmpFilenames[0]);
+    EnableParameter("mode.raster.out");
+    if (isVector)
+      {
+      tmpFilenames.push_back(outPath+std::string("_labelmap_merged.tif"));
+      tmpFilenames.push_back(outPath+std::string("_labelmap_merged.geom"));
+      GetInternalApplication("merging")->SetParameterString("out",
+        tmpFilenames[2]);
+      GetInternalApplication("merging")->ExecuteAndWriteOutput();
+      if (IsParameterEnabled("mode.vector.imfield") &&
+          HasValue("mode.vector.imfield"))
+        {
+        GetInternalApplication("vectorization")->SetParameterString("in",
+          GetParameterString("mode.vector.imfield"));
+        }
+      else
+        {
+        GetInternalApplication("vectorization")->SetParameterString("in",
+          GetParameterString("in"));
+        }
+      GetInternalApplication("vectorization")->SetParameterString("inseg",
+        tmpFilenames[2]);
+      ExecuteInternal("vectorization");
+      }
+    else
+      {
+      GetInternalApplication("merging")->ExecuteAndWriteOutput();
+      }
+    DisableParameter("mode.raster.out");
+
+    if( IsParameterEnabled( "cleanup" ) )
+      {
+      otbAppLogINFO( <<"Final clean-up ..." );
+      for (unsigned int i=0 ; i<tmpFilenames.size() ; ++i)
+        {
+        if(itksys::SystemTools::FileExists(tmpFilenames[i].c_str()))
+          {
+          itksys::SystemTools::RemoveFile(tmpFilenames[i].c_str());
+          }
+        }
+      }
+    }
+
+};
+
+} // end of namespace Wrapper
+} // end of namespace otb
+
+OTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleMeanShift)
diff --git a/Modules/Applications/AppSegmentation/app/otbMeanShiftSmoothing.cxx b/Modules/Applications/AppSegmentation/app/otbMeanShiftSmoothing.cxx
index 6f34edd86e8fee07d85cde3147e195f0436abd83..1219f24c1a9876a30ba77a55277442247a43e26b 100644
--- a/Modules/Applications/AppSegmentation/app/otbMeanShiftSmoothing.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbMeanShiftSmoothing.cxx
@@ -49,61 +49,118 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("MeanShiftSmoothing");
-    SetDescription("Perform mean shift filtering");
+    SetDescription("This application smooths an image using the MeanShift algorithm.");
 
     // Documentation
-    SetDocName("Exact Large-Scale Mean-Shift segmentation, step 1 (smoothing)");
-    SetDocLongDescription("This application performs mean shift fitlering (multi-threaded).");
-    SetDocLimitations("With mode search option, the result will slightly depend on thread number.");
+    SetDocName("MeanShift Smoothing");
+    SetDocLongDescription("MeanShift [1,2,3] is an iterative edge-preserving image smoothing"
+                          " algorithm often used in image processing and as a first step for"
+                          " image segmentation. The MeanShift algorithm can be applied to"
+                          " multispectral images.\n\n"
+                          "At first iteration, for any given pixel of the input image, the"
+                          " filtered value correspond to the average spectral signature of"
+                          " neighborhood pixels that are both spatially closer than the spatial"
+                          " radius parameter (spatialr) and with spectral signature that have an euclidean"
+                          " distance to the input pixel lower than the range radius (ranger), that is,"
+                          " pixels that are both close in space and in spectral signatures."
+                          " Subsequent iterations will repeat this process by considering that"
+                          " the pixel signature corresponds to the average spectral signature"
+                          " computed during previous iteration, and that the pixel position"
+                          " corresponds to the average position of pixels used to compute the"
+                          " average signature."
+                          "The algorithm stops when the maximum number of iterations (maxiter) is reached,"
+                          " or when the position and spectral signature does not change much"
+                          " between iterations, according to the convergence threshold (thres). If the"
+                          " modesearch option is used then convergence will also stops if the"
+                          " spatial position reaches a pixel that has already converged. This"
+                          " will speed-up convergence, at the expense of stability of the result.\n\n"
+
+                          "The application outputs the image of the final averaged spectral"
+                          " signatures (fout), and can also optionnaly output the 2D"
+                          " displacement field between input pixel position and final pixel"
+                          " position after convergence (foutpos).\n\n"
+
+                          "Note that computing an euclidean distance between spectral signatures"
+                          " may be innacurate and that techniques such as color space transform or image"
+                          " normalisation could be applied before using this application. Also"
+                          " note that most satellite images noise model is not gaussian, since"
+                          " noise variance linearly depends on luminance (the higher the"
+                          " luminance, the higher the noise variance). To account for such noise"
+                          " model, the application provides the range radius ramp option"
+                          " (rangeramp), which will vary the range radius linearly with the"
+                          " central pixel intensity. Default value is 1. (no ramp).\n\n"
+
+                          "This application is the first step of the large scale MeanShift method"
+                          " depicted in [4]. Both outputs (fout and foutpos) can be passed to the"
+                          " large scale MeanShift segmentation application [5]. If the"
+                          " application is used for large scale MeanShift, modesearch option should be off.");
+
+    SetDocLimitations("When modesearch is on, the application will yield slightly different"
+                      " results between executions, due to multi-threading. Results will also"
+                      " not be stable [4].");
+    
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
+    SetDocSeeAlso("[1] Comaniciu, D., & Meer, P. (2002). Mean shift: A robust approach"
+                  " toward feature space analysis. IEEE Transactions on pattern analysis"
+                  " and machine intelligence, 24(5), 603-619.\n"
+                  "[2] Comaniciu, D., & Meer, P. (1997, June). Robust analysis of feature"
+                  " spaces: color image segmentation. In Computer Vision and Pattern"
+                  " Recognition, 1997. Proceedings., 1997 IEEE Computer Society Conference"
+                  " on (pp. 750-755). IEEE.\n"
+                  "[3] Comaniciu, D., & Meer, P. (1999). Mean shift analysis and"
+                  " applications. In Computer Vision, 1999. The Proceedings of the Seventh"
+                  " IEEE International Conference on (Vol. 2, pp. 1197-1203). IEEE.\n"
+                  "[4] Michel, J., Youssefi, D., & Grizonnet, M. (2015). Stable"
+                  " mean-shift algorithm and its application to the segmentation of"
+                  " arbitrarily large remote sensing images. IEEE Transactions on"
+                  " Geoscience and Remote Sensing, 53(2), 952-964.\n"
+                  "[5] LSMSSegmentation application");
 
     AddDocTag(Tags::Filter);
     AddDocTag("LSMS");
 
     AddParameter(ParameterType_InputImage,   "in",     "Input Image");
-    SetParameterDescription( "in", "The input image." );
+    SetParameterDescription( "in", "The input image can be any single or multiband image. Beware of pontential imbalance between bands ranges as it may alter euclidean distance." );
 
-    AddParameter(ParameterType_OutputImage,  "fout",    "Filtered output");
-    SetParameterDescription( "fout", "The filtered output image." );
+    AddParameter(ParameterType_OutputImage,  "fout",    "Spectral filtered output");
+    SetParameterDescription( "fout", "This output image contains the final average spectral signatures of each pixel. The output type should be at least as wide as the input image type. Floating point encoding is advised. This output can be used as input image (in) of the LSMSSegmentation application [4,5]."  );
 
-    AddParameter(ParameterType_OutputImage,  "foutpos",    "Spatial image");
-    SetParameterDescription( "foutpos", " The spatial image output. Spatial image output is a displacement map (pixel position after convergence).");
+    AddParameter(ParameterType_OutputImage,  "foutpos",    "Spatial filtered displacement output");
+    SetParameterDescription( "foutpos", " This output image contains the 2D displacement between the input pixel spatial position and the final position after convergence. Floating point encoding is mandatory. This output can be used as input image (in) of the LSMSSegmentation application [4,5].");
     MandatoryOff("foutpos");
 
     AddRAMParameter();
 
     AddParameter(ParameterType_Int, "spatialr", "Spatial radius");
-    SetParameterDescription("spatialr", "Spatial radius of the neighborhood.");
+    SetParameterDescription("spatialr", "Radius of the spatial neighborhood for averaging. Higher values will result in more smoothing and higher processing time.");
     SetDefaultParameterInt("spatialr", 5);
     MandatoryOff("spatialr");
 
     AddParameter(ParameterType_Float, "ranger", "Range radius");
-    SetParameterDescription("ranger", "Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space.");
+    SetParameterDescription("ranger", "Threshold on spectral signature euclidean distance (expressed in radiometry unit) to consider neighborhood pixel for averaging. Higher values will be less edge-preserving (more similar to simple average in neighborhood), whereas lower values will result in less noise smoothing. Note that this parameter has no effect on processing time.");
     SetDefaultParameterFloat("ranger", 15.0);
     MandatoryOff("ranger");
 
     AddParameter(ParameterType_Float, "thres", "Mode convergence threshold");
-    SetParameterDescription("thres", "Algorithm iterative scheme will stop if mean-shift "
-                               "vector is below this threshold or if iteration number reached maximum number of iterations.");
+    SetParameterDescription("thres", "Algorithm will stop if update of average spectral signature and spatial position is below this threshold.");
     SetMinimumParameterFloatValue("thres", 0.0);
     SetDefaultParameterFloat("thres", 0.1);
     MandatoryOff("thres");
 
     AddParameter(ParameterType_Int, "maxiter", "Maximum number of iterations");
-    SetParameterDescription("maxiter", "Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.");
+    SetParameterDescription("maxiter", "Algorithm will stop if convergence threshold is not met after the maximum number of iterations.");
     SetDefaultParameterInt("maxiter", 100);
     SetMinimumParameterIntValue("maxiter", 1);
     MandatoryOff("maxiter");
 
-    AddParameter(ParameterType_Float, "rangeramp", "Range radius coefficient");
-    SetParameterDescription("rangeramp", "This coefficient makes dependent the ranger of the colorimetry of the filtered pixel : y = rangeramp*x+ranger.");
+    AddParameter(ParameterType_Float, "rangeramp", "Range radius ramp coefficient");
+    SetParameterDescription("rangeramp", "Vary the range radius linearly with the central pixel intensity (experimental).");
     SetDefaultParameterFloat("rangeramp", 0.);
     SetMinimumParameterFloatValue("rangeramp", 0);
     MandatoryOff("rangeramp");
 
     AddParameter(ParameterType_Empty, "modesearch", "Mode search.");
-    SetParameterDescription("modesearch", "If activated pixel iterative convergence is stopped if the path crosses an already converged pixel. Be careful, with this option, the result will slightly depend on thread number");
+    SetParameterDescription("modesearch", "If activated pixel iterative convergence is stopped if the path crosses an already converged pixel. Be careful, with this option, the result will slightly depend on thread number and the results will not be stable (see [4] for more details).");
     DisableParameter("modesearch");
 
 
diff --git a/Modules/Applications/AppSegmentation/app/otbSegmentation.cxx b/Modules/Applications/AppSegmentation/app/otbSegmentation.cxx
index c8c975c57148fcd2ad4c2c7f5ed4d878dd9ffab8..5b3bfd2361f211e9dccf19b383542596fd1b994a 100644
--- a/Modules/Applications/AppSegmentation/app/otbSegmentation.cxx
+++ b/Modules/Applications/AppSegmentation/app/otbSegmentation.cxx
@@ -39,6 +39,7 @@
 #include "otbOGRLayerStreamStitchingFilter.h"
 
 #include "otbGeoInformationConversion.h"
+#include "otbClampImageFilter.h"
 
 //Utils
 #include "itksys/SystemTools.hxx"
@@ -129,6 +130,8 @@ public:
   <FloatImageType,
    WatershedSegmentationFilterType>      StreamingVectorizedWatershedFilterType;
 
+  typedef otb::ClampImageFilter<FloatImageType, UInt32ImageType> ClampFilterType;
+
   /** Standard macro */
   itkNewMacro(Self);
   itkTypeMacro(Segmentation, otb::Application);
@@ -352,8 +355,12 @@ private:
 
   template<class TInputImage, class TSegmentationFilter>
   FloatVectorImageType::SizeType
-  GenericApplySegmentation(otb::StreamingImageToOGRLayerSegmentationFilter<TInputImage,
-                           TSegmentationFilter> * streamingVectorizedFilter, TInputImage * inputImage, const otb::ogr::Layer& layer, const unsigned int outputNb)
+  GenericApplySegmentation(
+    otb::StreamingImageToOGRLayerSegmentationFilter<
+      TInputImage,TSegmentationFilter> * streamingVectorizedFilter,
+    TInputImage * inputImage,
+    const otb::ogr::Layer& layer,
+    const unsigned int outputNb)
   {
     // Retrieve tile size parameter
     const unsigned int tileSize = static_cast<unsigned int> (this->GetParameterInt("mode.vector.tilesize"));
@@ -369,7 +376,7 @@ private:
 
     if (segModeType == "vector" && HasValue("mode.vector.inmask"))
       {
-      streamingVectorizedFilter->SetInputMask(this->GetParameterUInt32Image("mode.vector.inmask"));
+      streamingVectorizedFilter->SetInputMask(m_ClampFilter->GetOutput());
       otbAppLogINFO(<<"Use a mask as input." << std::endl);
       }
     streamingVectorizedFilter->SetOGRLayer(layer);
@@ -422,7 +429,9 @@ private:
       DisableParameter("mode.raster.out");
       EnableParameter("mode.vector.out");
 
-      AddProcess(streamingVectorizedFilter->GetStreamer(), "Computing " + (dynamic_cast <ChoiceParameter *> (this->GetParameterByKey("filter")))->GetChoiceKey(GetParameterInt("filter")) + " segmentation");
+      AddProcess(streamingVectorizedFilter->GetStreamer(), "Computing "
+        + this->GetParameterString("filter")
+        + " segmentation");
 
       streamingVectorizedFilter->Initialize(); //must be called !
       streamingVectorizedFilter->Update(); //must be called !
@@ -435,7 +444,9 @@ private:
       EnableParameter("mode.raster.out");
 
       streamingVectorizedFilter->GetSegmentationFilter()->SetInput(inputImage);
-      SetParameterOutputImage<UInt32ImageType> ("mode.raster.out", dynamic_cast<UInt32ImageType *> (streamingVectorizedFilter->GetSegmentationFilter()->GetOutputs().at(outputNb).GetPointer()));
+      SetParameterOutputImage<UInt32ImageType> ("mode.raster.out",
+        dynamic_cast<UInt32ImageType*>(
+          streamingVectorizedFilter->GetSegmentationFilter()->GetOutputs().at(outputNb).GetPointer()));
       //TODO add progress reporting in raster mode
       // AddProcess(dynamic_cast <OutputImageParameter *> (GetParameterByKey("mode.raster.out"))->GetWriter(),
       //            "Computing " + (dynamic_cast <ChoiceParameter *>
@@ -468,7 +479,6 @@ private:
       //projection ref conversion to ESRI need to be tested in case of .shp
       if ((dataSourceName.find(".shp") != std::string::npos) && (!projRef.empty()))
         {
-
         if (!(otb::GeoInformationConversion::IsESRIValidWKT(projRef)))
           {
           otbAppLogFATAL(<<"Image projection reference "<<std::endl<< projRef);
@@ -494,57 +504,59 @@ private:
         OGRFieldDefn field(this->GetParameterString("mode.vector.fieldname").c_str(), OFTInteger);
         layer.CreateField(field, true);
         }
-      else
-        if (outmode == "ulovw")
+      else if (outmode == "ulovw")
+        {
+        // Create the datasource
+        ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerOverwrite);
+
+        // and create the layer since we are in overwrite mode, the
+        // datasource is blank
+        layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
+        // And create the field
+        OGRFieldDefn field(this->GetParameterString("mode.vector.fieldname").c_str(), OFTInteger);
+        layer.CreateField(field, true);
+        }
+      else if (outmode == "ulu")
+        {
+        // Create the datasource
+        ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerUpdate);
+        // and create the layer since we are in overwrite mode, the
+        // datasource is blank
+        layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
+
+        // And create the field if necessary
+        std::string fieldName = this->GetParameterString("mode.vector.fieldname");
+        OGRFeatureDefn & ogrFeatureDfn = layer.GetLayerDefn();
+
+        if (-1 == ogrFeatureDfn.GetFieldIndex(fieldName.c_str()))
           {
-          // Create the datasource
-          ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerOverwrite);
-
-          // and create the layer since we are in overwrite mode, the
-          // datasource is blank
-          layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
-          // And create the field
-          OGRFieldDefn field(this->GetParameterString("mode.vector.fieldname").c_str(), OFTInteger);
+          OGRFieldDefn field(fieldName.c_str(), OFTInteger);
           layer.CreateField(field, true);
-
           }
-        else
-          if (outmode == "ulu")
-            {
-            // Create the datasource
-            ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerUpdate);
-            // and create the layer since we are in overwrite mode, the
-            // datasource is blank
-            layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
-
-            // And create the field if necessary
-            std::string fieldName = this->GetParameterString("mode.vector.fieldname");
-            OGRFeatureDefn & ogrFeatureDfn = layer.GetLayerDefn();
-
-            if (-1 == ogrFeatureDfn.GetFieldIndex(fieldName.c_str()))
-              {
-              OGRFieldDefn field(fieldName.c_str(), OFTInteger);
-              layer.CreateField(field, true);
-              }
-
-            }
-          else
-            if (outmode == "ulco")
-              {
-              // Create the datasource
-              ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerCreateOnly);
-
-              // and create the layer since we are in overwrite mode, the
-              // datasource is blank
-              layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
-              // And create the field
-              OGRFieldDefn field(this->GetParameterString("mode.vector.fieldname").c_str(), OFTInteger);
-              layer.CreateField(field, true);
-              }
-            else
-              {
-              otbAppLogFATAL(<<"outmode not handled yet: "<< outmode);
-              }
+        }
+      else if (outmode == "ulco")
+        {
+        // Create the datasource
+        ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::Update_LayerCreateOnly);
+
+        // and create the layer since we are in overwrite mode, the
+        // datasource is blank
+        layer = ogrDS->CreateLayer(GetParameterString("mode.vector.layername"), &oSRS, wkbMultiPolygon, options);
+        // And create the field
+        OGRFieldDefn field(this->GetParameterString("mode.vector.fieldname").c_str(), OFTInteger);
+        layer.CreateField(field, true);
+        }
+      else
+        {
+        otbAppLogFATAL(<<"outmode not handled yet: "<< outmode);
+        }
+      }
+
+    // handle mask
+    if (HasValue("mode.vector.inmask"))
+      {
+      m_ClampFilter = ClampFilterType::New();
+      m_ClampFilter->SetInput( this->GetParameterFloatImage("mode.vector.inmask"));
       }
 
     // The actual stream size used
@@ -554,108 +566,105 @@ private:
       {
       otbAppLogINFO(<<"Use connected component segmentation."<<std::endl);
       ConnectedComponentStreamingVectorizedSegmentationOGRType::Pointer
-          ccVectorizationFilter = ConnectedComponentStreamingVectorizedSegmentationOGRType::New();
+        ccVectorizationFilter = ConnectedComponentStreamingVectorizedSegmentationOGRType::New();
 
       if (HasValue("mode.vector.inmask"))
         {
         ccVectorizationFilter->GetSegmentationFilter()->SetMaskImage(
-                                                                     this->GetParameterUInt32Image("mode.vector.inmask"));
+          m_ClampFilter->GetOutput());
         }
 
       ccVectorizationFilter->GetSegmentationFilter()->GetFunctor().SetExpression(GetParameterString("filter.cc.expr"));
-      streamSize = GenericApplySegmentation<FloatVectorImageType, ConnectedComponentSegmentationFilterType> (
-                                                                                                             ccVectorizationFilter,
-                                                                                                             this->GetParameterFloatVectorImage(
-                                                                                                                                                "in"),
-                                                                                                             layer, 0);
+      streamSize = GenericApplySegmentation<FloatVectorImageType,ConnectedComponentSegmentationFilterType>(
+        ccVectorizationFilter,
+        this->GetParameterFloatVectorImage("in"),
+        layer,
+        0);
       }
-      else
-        if (segType == "meanshift")
-          {
-          otbAppLogINFO(<<"Use threaded Mean-shift segmentation."<<std::endl);
-
-          MeanShiftVectorizedSegmentationOGRType::Pointer
-              meanShiftVectorizationFilter = MeanShiftVectorizedSegmentationOGRType::New();
-
-          //segmentation parameters
-          const unsigned int
-              spatialRadius = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.spatialr"));
-          const float rangeRadius = static_cast<float> (this->GetParameterFloat("filter.meanshift.ranger"));
-          const unsigned int
-              minimumObjectSize = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.minsize"));
-
-          const float threshold = this->GetParameterFloat("filter.meanshift.thres");
-          const unsigned int
-              maxIterNumber = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.maxiter"));
-
-          meanShiftVectorizationFilter->GetSegmentationFilter()->SetSpatialBandwidth(spatialRadius);
-          meanShiftVectorizationFilter->GetSegmentationFilter()->SetRangeBandwidth(rangeRadius);
-          meanShiftVectorizationFilter->GetSegmentationFilter()->SetMaxIterationNumber(maxIterNumber);
-          meanShiftVectorizationFilter->GetSegmentationFilter()->SetThreshold(threshold);
-          meanShiftVectorizationFilter->GetSegmentationFilter()->SetMinRegionSize(minimumObjectSize);
-
-          streamSize = this->GenericApplySegmentation<FloatVectorImageType, MeanShiftSegmentationFilterType> (
-                                                                                                              meanShiftVectorizationFilter,
-                                                                                                              this->GetParameterFloatVectorImage(
-                                                                                                                                                 "in"),
-                                                                                                              layer, 0);
-          }
-        else
-          if (segType == "watershed")
-            {
-            otbAppLogINFO(<<"Using watershed segmentation."<<std::endl);
-
-            AmplitudeFilterType::Pointer amplitudeFilter = AmplitudeFilterType::New();
-
-            amplitudeFilter->SetInput(this->GetParameterFloatVectorImage("in"));
+    else if (segType == "meanshift")
+      {
+      otbAppLogINFO(<<"Use threaded Mean-shift segmentation."<<std::endl);
+
+      MeanShiftVectorizedSegmentationOGRType::Pointer
+          meanShiftVectorizationFilter = MeanShiftVectorizedSegmentationOGRType::New();
+
+      //segmentation parameters
+      const unsigned int
+          spatialRadius = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.spatialr"));
+      const float rangeRadius = static_cast<float> (this->GetParameterFloat("filter.meanshift.ranger"));
+      const unsigned int
+          minimumObjectSize = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.minsize"));
+
+      const float threshold = this->GetParameterFloat("filter.meanshift.thres");
+      const unsigned int
+          maxIterNumber = static_cast<unsigned int> (this->GetParameterInt("filter.meanshift.maxiter"));
+
+      meanShiftVectorizationFilter->GetSegmentationFilter()->SetSpatialBandwidth(spatialRadius);
+      meanShiftVectorizationFilter->GetSegmentationFilter()->SetRangeBandwidth(rangeRadius);
+      meanShiftVectorizationFilter->GetSegmentationFilter()->SetMaxIterationNumber(maxIterNumber);
+      meanShiftVectorizationFilter->GetSegmentationFilter()->SetThreshold(threshold);
+      meanShiftVectorizationFilter->GetSegmentationFilter()->SetMinRegionSize(minimumObjectSize);
+
+      streamSize = this->GenericApplySegmentation<FloatVectorImageType,MeanShiftSegmentationFilterType>(
+        meanShiftVectorizationFilter,
+        this->GetParameterFloatVectorImage("in"),
+        layer,
+        0);
+      }
+    else if (segType == "watershed")
+      {
+      otbAppLogINFO(<<"Using watershed segmentation."<<std::endl);
 
-            GradientMagnitudeFilterType::Pointer gradientMagnitudeFilter = GradientMagnitudeFilterType::New();
-            gradientMagnitudeFilter->SetInput(amplitudeFilter->GetOutput());
+      AmplitudeFilterType::Pointer amplitudeFilter = AmplitudeFilterType::New();
 
-            StreamingVectorizedWatershedFilterType::Pointer
-                watershedVectorizedFilter = StreamingVectorizedWatershedFilterType::New();
+      amplitudeFilter->SetInput(this->GetParameterFloatVectorImage("in"));
 
-            watershedVectorizedFilter->GetSegmentationFilter()->SetThreshold(
-                                                                             GetParameterFloat(
-                                                                                               "filter.watershed.threshold"));
-            watershedVectorizedFilter->GetSegmentationFilter()->SetLevel(GetParameterFloat("filter.watershed.level"));
+      GradientMagnitudeFilterType::Pointer gradientMagnitudeFilter = GradientMagnitudeFilterType::New();
+      gradientMagnitudeFilter->SetInput(amplitudeFilter->GetOutput());
 
-            streamSize = this->GenericApplySegmentation<FloatImageType, WatershedSegmentationFilterType> (
-                                                                                                          watershedVectorizedFilter,
-                                                                                                          gradientMagnitudeFilter->GetOutput(),
-                                                                                                          layer, 0);
-            }
+      StreamingVectorizedWatershedFilterType::Pointer
+          watershedVectorizedFilter = StreamingVectorizedWatershedFilterType::New();
 
-        else
-          if (segType == "mprofiles")
-            {
-            otbAppLogINFO(<<"Using multiscale geodesic morphology segmentation."<<std::endl);
+      watershedVectorizedFilter->GetSegmentationFilter()->SetThreshold(
+        GetParameterFloat("filter.watershed.threshold"));
+      watershedVectorizedFilter->GetSegmentationFilter()->SetLevel(GetParameterFloat("filter.watershed.level"));
 
-            unsigned int profileSize = GetParameterInt("filter.mprofiles.size");
-            unsigned int initialValue = GetParameterInt("filter.mprofiles.start");
-            unsigned int step = GetParameterInt("filter.mprofiles.step");
-            double       sigma = GetParameterFloat("filter.mprofiles.sigma");
+      streamSize = this->GenericApplySegmentation<FloatImageType,WatershedSegmentationFilterType>(
+        watershedVectorizedFilter,
+        gradientMagnitudeFilter->GetOutput(),
+        layer,
+        0);
+      }
+    else if (segType == "mprofiles")
+      {
+      otbAppLogINFO(<<"Using multiscale geodesic morphology segmentation."<<std::endl);
 
+      unsigned int profileSize = GetParameterInt("filter.mprofiles.size");
+      unsigned int initialValue = GetParameterInt("filter.mprofiles.start");
+      unsigned int step = GetParameterInt("filter.mprofiles.step");
+      double       sigma = GetParameterFloat("filter.mprofiles.sigma");
 
-            AmplitudeFilterType::Pointer amplitudeFilter = AmplitudeFilterType::New();
 
-            amplitudeFilter->SetInput(this->GetParameterFloatVectorImage("in"));
+      AmplitudeFilterType::Pointer amplitudeFilter = AmplitudeFilterType::New();
 
-            MorphoVectorizedSegmentationOGRType::Pointer morphoVectorizedSegmentation = MorphoVectorizedSegmentationOGRType::New();
-            morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileStart(initialValue);
-            morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileSize(profileSize);
-            morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileStep(step);
-            morphoVectorizedSegmentation->GetSegmentationFilter()->SetSigma(sigma);
+      amplitudeFilter->SetInput(this->GetParameterFloatVectorImage("in"));
 
-            streamSize = GenericApplySegmentation<FloatImageType, MorphologicalProfilesSegmentationFilterType> (
-        morphoVectorizedSegmentation,                                                                     amplitudeFilter->GetOutput(),
-                                                                                                             layer, 0);
+      MorphoVectorizedSegmentationOGRType::Pointer morphoVectorizedSegmentation = MorphoVectorizedSegmentationOGRType::New();
+      morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileStart(initialValue);
+      morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileSize(profileSize);
+      morphoVectorizedSegmentation->GetSegmentationFilter()->SetProfileStep(step);
+      morphoVectorizedSegmentation->GetSegmentationFilter()->SetSigma(sigma);
 
-            }
-          else
-            {
-            otbAppLogFATAL(<<"non defined filtering method "<<GetParameterInt("filter")<<std::endl);
-            }
+      streamSize = GenericApplySegmentation<FloatImageType,MorphologicalProfilesSegmentationFilterType>(
+        morphoVectorizedSegmentation,
+        amplitudeFilter->GetOutput(),
+        layer,
+        0);
+      }
+    else
+      {
+      otbAppLogFATAL(<<"non defined filtering method "<<GetParameterInt("filter")<<std::endl);
+      }
 
     if (segModeType == "vector")
       {
@@ -676,26 +685,27 @@ private:
         AddProcess(fusionFilter, "Stitching polygons");
         fusionFilter->GenerateData();
 
-       //REPACK the Layer in case of Shapefile.
-       //This request will remove features marked as deleted in the .dbf filename,
-       //and recomputed FID for each features (without holes).
+        //REPACK the Layer in case of Shapefile.
+        //This request will remove features marked as deleted in the .dbf filename,
+        //and recomputed FID for each features (without holes).
         //Note : the GetDriver() Method has not been encapsulated in otb::ogr::DataSource,
         //so we must access the OGR pointer by using .ogr()
 
         std::string driverName(otb::ogr::version_proxy::GetDriverNameFromDataSource(&ogrDS->ogr()));
-       if ( driverName.find("ESRI Shapefile") != std::string::npos)
-         {
-           otbAppLogINFO(<<"REPACK the Shapefile ..."<<std::endl);
-           //In Shapefile format, the name of the DaaSource is also the name of the Layer.
-           std::string shpLayerName = itksys::SystemTools::GetFilenameWithoutExtension(GetParameterString("mode.vector.out"));
-
-           std::string repack("REPACK ");
-           repack = repack + shpLayerName;
-           ogrDS->ExecuteSQL(repack, ITK_NULLPTR, ITK_NULLPTR);
-         }
-       }
+        if ( driverName.find("ESRI Shapefile") != std::string::npos)
+          {
+          otbAppLogINFO(<<"REPACK the Shapefile ..."<<std::endl);
+          //In Shapefile format, the name of the DaaSource is also the name of the Layer.
+          std::string shpLayerName = itksys::SystemTools::GetFilenameWithoutExtension(GetParameterString("mode.vector.out"));
+          std::string repack("REPACK ");
+          repack = repack + shpLayerName;
+          ogrDS->ExecuteSQL(repack, ITK_NULLPTR, ITK_NULLPTR);
+          }
+        }
       }
   }
+
+  ClampFilterType::Pointer m_ClampFilter;
 };
 }
 }
diff --git a/Modules/Applications/AppSegmentation/test/CMakeLists.txt b/Modules/Applications/AppSegmentation/test/CMakeLists.txt
index 090a2562ef000e91787672ced1a327d2cf4cd9bb..e04c3bbc1e328924e605ab1fd77fce88dcf800dc 100644
--- a/Modules/Applications/AppSegmentation/test/CMakeLists.txt
+++ b/Modules/Applications/AppSegmentation/test/CMakeLists.txt
@@ -293,3 +293,18 @@ otb_test_application(NAME     apTvSeHooverCompareSegmentationTest
                               --ignore-lines-with 2 outgt: outms:
                      )
 
+#----------- LargeScaleMeanShift TESTS ----------------
+otb_test_application(NAME     apTvSeLargeScaleMeanShiftTest
+                     APP      LargeScaleMeanShift
+                     OPTIONS  -in ${EXAMPLEDATA}/QB_1_ortho.tif
+                              -spatialr 3
+                              -ranger 80
+                              -minsize 16
+                              -tilesizex 100
+                              -tilesizey 100
+                              -mode vector
+                              -mode.vector.out ${TEMP}/apTvSeLargeScaleMeanShiftTestOut.shp
+                     VALID    --compare-ogr ${NOTOL}
+                              ${BASELINE_FILES}/apTvSeLargeScaleMeanShiftTestOut.shp
+                              ${TEMP}/apTvSeLargeScaleMeanShiftTestOut.shp
+                     )
diff --git a/Modules/Applications/AppStereo/app/otbBlockMatching.cxx b/Modules/Applications/AppStereo/app/otbBlockMatching.cxx
index 8b19cfabd052bd1abf2806821615347a4bfe67e2..eaf57ea79a2c47f194d73db7c8e2cdad7db717c2 100644
--- a/Modules/Applications/AppStereo/app/otbBlockMatching.cxx
+++ b/Modules/Applications/AppStereo/app/otbBlockMatching.cxx
@@ -127,82 +127,145 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("BlockMatching");
-    SetDescription("Performs block-matching to estimate pixel-wise disparities between two images");
+    SetDescription("Performs block-matching to estimate pixel-wise disparities"
+      " between two images.");
 
     SetDocName("Pixel-wise Block-Matching");
-    SetDocLongDescription("This application allows one to performs block-matching to estimate pixel-wise disparities "
-      "between two images. One must chose block-matching method and input"
-      " masks (related to the left and right input image) of pixels for which the disparity should be investigated. "
-      "Additionally, two criteria can be optionally used to disable disparity investigation for some pixel: a "
-      "no-data value, and a threshold on the local variance. This allows one to speed-up computation by avoiding to "
-      "investigate disparities that will not be reliable anyway. For efficiency reasons, if the optimal metric values"
-      " image is desired, it will be concatenated to the output image (which will then have three bands : horizontal "
-      "disparity, vertical disparity and metric value). One can split these images afterward.");
+    SetDocLongDescription("This application allows one to performs "
+      "block-matching to estimate pixel-wise disparities for a pair of images "
+      "in epipolar geometry.\n\n"
+      "This application is part of the stereovision pipeline. It can be used "
+      "after having computed epipolar grids (with StereoRectificationGridGenerator)"
+      " and resampled each input image into epipolar geometry (with "
+      "GridBasedImageResampling).\n\n"
+      "The application searches locally for the displacement between a reference"
+      " image and a secondary image. The correspondance is evaluated for each "
+      "pixel, based on a pair of local neighborhood windows. The displacement "
+      "evaluated can be 1D (along lines) or 2D. Parameters allows to set the "
+      "minimum and maximum disparities to search (both for horizontal and "
+      "vertical directions). A winner-take-all approach is used to select the "
+      "best match. There are different metrics implemented to evaluate the "
+      "match between two local windows:\n"
+      "  * SSD : Sum of Squared Distances\n"
+      "  * NCC : Normalized Cross-Correlation\n"
+      "  * Lp  : Lp pseudo norm\n"
+      "\n"                    
+      "Once the best integer disparity is found, an optional step of sub-pixel "
+      "disparity estimation can be performed, with various algorithms "
+      "(triangular interpolation, parabollic interpolation, dichotimic search)."
+      " As post-processing, there is an optional step of median filtering on "
+      "the disparities. One can chose input masks (related to the left and "
+      "right input image) of pixels for which the disparity should be "
+      "investigated. Additionally, two criteria can be optionally used to "
+      "disable disparity investigation for some pixel: a no-data value, and a "
+      "threshold on the local variance. This allows one to speed-up computation"
+      " by avoiding to investigate disparities that will not be reliable anyway"
+      ". For efficiency reasons, if the image of optimal metric values is "
+      "desired, it will be concatenated to the output image (which will then "
+      "have three bands : horizontal disparity, vertical disparity and metric "
+      "value). One can split these images afterward.");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso("otbStereoRectificationGridGenerator");
+    SetDocSeeAlso("[1] StereoRectificationGridGenerator\n"
+      "[2] GridBasedImageResampling");
 
     AddDocTag(Tags::Stereo);
 
     AddParameter(ParameterType_Group,"io","Input and output data");
-    SetParameterDescription("io","This group of parameters allows setting the input and output images.");
+    SetParameterDescription("io","This group of parameters allows setting the "
+      "input and output images.");
 
     AddParameter(ParameterType_InputImage,"io.inleft","Left input image");
-    SetParameterDescription("io.inleft","The left input image (reference)");
+    SetParameterDescription("io.inleft","The left input image (reference).\n"
+      "It should have the same size and same physical space as the right input."
+      " This image can be generated by GridBasedImageResampling");
 
     AddParameter(ParameterType_InputImage,"io.inright","Right input image");
-    SetParameterDescription("io.inright","The right input (secondary)");
+    SetParameterDescription("io.inright","The right input (secondary).\n"
+      "It should have the same size and same physical space as the left input."
+      " This image can be generated by GridBasedImageResampling");
 
     AddParameter(ParameterType_OutputImage, "io.out", "The output disparity map");
-    SetParameterDescription("io.out","An image containing the estimated disparities as well as the metric values if the option is used");
-
-    AddParameter(ParameterType_OutputImage, "io.outmask", "The output mask corresponding to all criterions");
-    SetParameterDescription("io.outmask","A mask image corresponding to all citerions (see masking parameters). Only required if variance threshold or nodata criterions are set.");
+    SetParameterDescription("io.out","An image containing the estimated "
+      "disparities as well as the metric values if the option is used. If no "
+      "metric is output and no sub-pixel interpolation is done, pixel type can"
+      "be a signed integer. In the other cases, floating point pixel is "
+      "advised.");
+
+    AddParameter(ParameterType_OutputImage, "io.outmask", "The output mask "
+      "corresponding to all criterions");
+    SetParameterDescription("io.outmask","An output mask image corresponding to"
+      " all citerions (see masking parameters). Only required if variance "
+      "threshold or nodata criterions are set. Output pixel type is unsigned "
+      "8bit by default.");
     SetDefaultOutputPixelType("io.outmask",ImagePixelType_uint8);
     DisableParameter("io.outmask");
     MandatoryOff("io.outmask");
 
-    AddParameter(ParameterType_Empty,"io.outmetric","Output optimal metric values as well");
-    SetParameterDescription("io.outmetric","If used, the output image will have a second component with metric optimal values");
+    AddParameter(ParameterType_Empty,"io.outmetric","Flag to output optimal "
+      "metric values as well");
+    SetParameterDescription("io.outmetric","If enabled, the output image will "
+      "have a third component with metric optimal values");
 
     AddParameter(ParameterType_Group,"mask","Image masking parameters");
-    SetParameterDescription("mask","This group of parameters allows determining the masking parameters to prevent disparities estimation for some pixels of the left image");
-
-    AddParameter(ParameterType_InputImage,"mask.inleft","Discard left pixels from mask image");
-    SetParameterDescription("mask.inleft","This parameter allows providing a custom mask for the left image.Block matching will be only perform on pixels inside the mask.");
+    SetParameterDescription("mask","This group of parameters allows determining"
+      " the masking parameters to prevent disparities estimation for some "
+      "pixels of the left image");
+
+    AddParameter(ParameterType_InputImage,"mask.inleft",
+      "Mask to discard left pixels");
+    SetParameterDescription("mask.inleft","This parameter allows providing a "
+      "custom mask for the left image. Block matching will be only perform on "
+      "pixels inside the mask (non-zero values).");
     MandatoryOff("mask.inleft");
 
-    AddParameter(ParameterType_InputImage,"mask.inright","Discard right pixels from mask image");
-    SetParameterDescription("mask.inright","This parameter allows providing a custom mask for the right image.Block matching will be perform only on pixels inside the mask.");
+    AddParameter(ParameterType_InputImage,"mask.inright",
+      "Mask to discard right pixels");
+    SetParameterDescription("mask.inright","This parameter allows providing a "
+      "custom mask for the right image. Block matching will be perform only on "
+      "pixels inside the mask (non-zero values).");
     MandatoryOff("mask.inright");
 
-    AddParameter(ParameterType_Float,"mask.nodata","Discard pixels with no-data value");
-    SetParameterDescription("mask.nodata","This parameter allows discarding pixels whose value is equal to the user-defined no-data value.");
+    AddParameter(ParameterType_Float,"mask.nodata",
+      "Discard pixels with no-data value");
+    SetParameterDescription("mask.nodata","This parameter allows discarding "
+      "pixels whose value is equal to the user-defined no-data value.");
     MandatoryOff("mask.nodata");
     SetDefaultParameterFloat("mask.nodata",0.);
     DisableParameter("mask.nodata");
 
-    AddParameter(ParameterType_Float,"mask.variancet","Discard pixels with low local variance");
-    SetParameterDescription("mask.variancet","This parameter allows discarding pixels whose local variance is too small (the size of the neighborhood is given by the radius parameter)");
+    AddParameter(ParameterType_Float,"mask.variancet",
+      "Discard pixels with low local variance");
+    SetParameterDescription("mask.variancet","This parameter allows discarding"
+      " pixels whose local variance is too small (the size of the neighborhood"
+      " is given by the radius parameter)");
     MandatoryOff("mask.variancet");
     SetDefaultParameterFloat("mask.variancet",100.);
     DisableParameter("mask.variancet");
 
     AddParameter(ParameterType_Group,"bm","Block matching parameters");
-    SetParameterDescription("bm","This group of parameters allow tuning the block-matching behaviour");
+    SetParameterDescription("bm","This group of parameters allow tuning the "
+      "block-matching behaviour");
 
     AddParameter(ParameterType_Choice,   "bm.metric", "Block-matching metric");
+    SetParameterDescription("bm.metric",
+      "Metric to evaluate matching between two local windows.");
+
     AddChoice("bm.metric.ssd","Sum of Squared Distances");
-    SetParameterDescription("bm.metric.ssd","Sum of squared distances between pixels value in the metric window");
+    SetParameterDescription("bm.metric.ssd","Sum of squared distances between"
+      " pixels value in the metric window");
 
     AddChoice("bm.metric.ncc","Normalized Cross-Correlation");
-    SetParameterDescription("bm.metric.ncc","Normalized Cross-Correlation between the left and right windows");
+    SetParameterDescription("bm.metric.ncc","Normalized Cross-Correlation "
+      "between the left and right windows");
 
     AddChoice("bm.metric.lp","Lp pseudo-norm");
-    SetParameterDescription("bm.metric.lp","Lp pseudo-norm between the left and right windows");
+    SetParameterDescription("bm.metric.lp","Lp pseudo-norm between the left and"
+      " right windows.");
 
     AddParameter(ParameterType_Float,"bm.metric.lp.p","p value" );
-    SetParameterDescription("bm.metric.lp.p", "Value of the p parameter in Lp pseudo-norm (must be positive)");
+    SetParameterDescription("bm.metric.lp.p", "Value of the p parameter in Lp"
+      " pseudo-norm (must be positive).");
     SetDefaultParameterFloat("bm.metric.lp.p", 1.0);
     SetMinimumParameterFloatValue("bm.metric.lp.p", 0.0);
 
@@ -227,43 +290,61 @@ private:
     SetParameterDescription("bm.subpixel", "Estimate disparities with sub-pixel precision");
 
     AddChoice("bm.subpixel.none", "None");
-    SetParameterDescription("bm.subpixel.none", "No sub-pixel ");
+    SetParameterDescription("bm.subpixel.none", "No sub-pixel search");
 
-    AddChoice("bm.subpixel.parabolic", "Parabolic");
-    SetParameterDescription("bm.subpixel.parabolic", "Parabolic fit");
+    AddChoice("bm.subpixel.parabolic", "Parabolic fit");
+    SetParameterDescription("bm.subpixel.parabolic", "The metric values closest"
+      " to the best match are used in order to fit a parabola to the local "
+      "extremum of the metric surface. The peak position of this parabola is "
+      "output.");
 
-    AddChoice("bm.subpixel.triangular", "Triangular");
-    SetParameterDescription("bm.subpixel.triangular", "Triangular fit");
+    AddChoice("bm.subpixel.triangular", "Triangular fit");
+    SetParameterDescription("bm.subpixel.triangular", "The metric values "
+      "closest to the best match are used in order to fit a triangular peak to "
+      "the local extremum of the metric surface. The peak position of this "
+      "triangle is output.");
 
-    AddChoice("bm.subpixel.dichotomy", "Dichotomy");
-    SetParameterDescription("bm.subpixel.dichotomy", "Dichotomic search");
+    AddChoice("bm.subpixel.dichotomy", "Dichotomy search");
+    SetParameterDescription("bm.subpixel.dichotomy", "An iterative dichotomic "
+      "search is performed to find the best sub-pixel position. The window in "
+      "the right image is resampled at sub-pixel positions to estimate the match.");
 
     AddParameter(ParameterType_Int,"bm.step", "Computation step");
-    SetParameterDescription("bm.step", "Location step between computed disparities");
+    SetParameterDescription("bm.step", "Location step between computed "
+      "disparities. Disparities will be computed every 'step' pixels in the "
+      "left image (step for both rows and columns). For instance, a value of 1 "
+      "corresponds to the classic dense disparity map.");
     SetDefaultParameterInt("bm.step",1);
     SetMinimumParameterIntValue("bm.step",1);
     MandatoryOff("bm.step");
 
     AddParameter(ParameterType_Int,"bm.startx","X start index");
-    SetParameterDescription("bm.startx","X start index of the subsampled grid (wrt the input image grid)");
+    SetParameterDescription("bm.startx","X start index of the subsampled grid "
+      "(wrt the input image grid). See parameter bm.step");
     SetDefaultParameterInt("bm.startx",0);
     MandatoryOff("bm.startx");
 
     AddParameter(ParameterType_Int,"bm.starty","Y start index");
-    SetParameterDescription("bm.starty","Y start index of the subsampled grid (wrt the input image grid)");
+    SetParameterDescription("bm.starty","Y start index of the subsampled grid "
+      "(wrt the input image grid). See parameter bm.step");
     SetDefaultParameterInt("bm.starty",0);
     MandatoryOff("bm.starty");
 
-    AddParameter(ParameterType_Group,"bm.medianfilter","Median filtering");
-    SetParameterDescription("bm.medianfilter","Use a median filter to get a smooth disparity map");
+    AddParameter(ParameterType_Group,"bm.medianfilter",
+      "Median filtering of disparity map");
+    SetParameterDescription("bm.medianfilter","Use a median filter to get a "
+      "smooth disparity map");
 
     AddParameter(ParameterType_Int,"bm.medianfilter.radius", "Radius");
-    SetParameterDescription("bm.medianfilter.radius", "Radius for median filter");
+    SetParameterDescription("bm.medianfilter.radius", "Radius (in pixels) for "
+      "median filter");
     MandatoryOff("bm.medianfilter.radius");
     DisableParameter("bm.medianfilter.radius");
 
-    AddParameter(ParameterType_Float,"bm.medianfilter.incoherence", "Incoherence threshold");
-    SetParameterDescription("bm.medianfilter.incoherence", "Incoherence threshold between original and filtered disparity");
+    AddParameter(ParameterType_Float,"bm.medianfilter.incoherence",
+      "Incoherence threshold");
+    SetParameterDescription("bm.medianfilter.incoherence", "Incoherence "
+      "threshold between original and filtered disparity");
     MandatoryOff("bm.medianfilter.incoherence");
     DisableParameter("bm.medianfilter.incoherence");
 
@@ -272,42 +353,60 @@ private:
     SetParameterDescription("bm.initdisp.none", "No initial disparity used");
 
     AddChoice("bm.initdisp.uniform", "Uniform initial disparity");
-    SetParameterDescription("bm.initdisp.uniform", "Use an uniform initial disparity estimate");
+    SetParameterDescription("bm.initdisp.uniform", "Use an uniform initial "
+      "disparity estimate");
 
-    AddParameter(ParameterType_Int, "bm.initdisp.uniform.hdisp", "Horizontal initial disparity");
-    SetParameterDescription("bm.initdisp.uniform.hdisp", "Value of the uniform horizontal disparity initial estimate (in pixels)");
+    AddParameter(ParameterType_Int, "bm.initdisp.uniform.hdisp",
+      "Horizontal initial disparity");
+    SetParameterDescription("bm.initdisp.uniform.hdisp", "Value of the uniform "
+      "horizontal disparity initial estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.uniform.hdisp", 0);
 
-    AddParameter(ParameterType_Int, "bm.initdisp.uniform.vdisp", "Vertical initial disparity");
-    SetParameterDescription("bm.initdisp.uniform.vdisp", "Value of the uniform vertical disparity initial estimate (in pixels)");
+    AddParameter(ParameterType_Int, "bm.initdisp.uniform.vdisp",
+      "Vertical initial disparity");
+    SetParameterDescription("bm.initdisp.uniform.vdisp", "Value of the uniform "
+      "vertical disparity initial estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.uniform.vdisp", 0);
 
-    AddParameter(ParameterType_Int, "bm.initdisp.uniform.hrad", "Horizontal exploration radius");
-    SetParameterDescription("bm.initdisp.uniform.hrad", "Horizontal exploration radius around the initial disparity estimate (in pixels)");
+    AddParameter(ParameterType_Int, "bm.initdisp.uniform.hrad",
+      "Horizontal exploration radius");
+    SetParameterDescription("bm.initdisp.uniform.hrad", "Horizontal exploration"
+      " radius around the initial disparity estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.uniform.hrad", 0);
     DisableParameter("bm.initdisp.uniform.hrad");
 
-    AddParameter(ParameterType_Int, "bm.initdisp.uniform.vrad", "Vertical exploration radius");
-    SetParameterDescription("bm.initdisp.uniform.vrad", "Vertical exploration radius around the initial disparity estimate (in pixels)");
+    AddParameter(ParameterType_Int, "bm.initdisp.uniform.vrad",
+      "Vertical exploration radius");
+    SetParameterDescription("bm.initdisp.uniform.vrad", "Vertical exploration "
+      "radius around the initial disparity estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.uniform.vrad", 0);
     DisableParameter("bm.initdisp.uniform.vrad");
 
     AddChoice("bm.initdisp.maps", "Initial disparity maps");
-    SetParameterDescription("bm.initdisp.maps", "Use initial disparity maps");
+    SetParameterDescription("bm.initdisp.maps", "Use initial disparity maps to "
+      "define the exploration area. This area in the right image is centered on"
+      " the current position shifted by the initial disparity estimate, and has"
+      " a given exploration radius in horizontal and vertical directions.");
 
-    AddParameter(ParameterType_InputImage, "bm.initdisp.maps.hmap", "Horizontal initial disparity map");
-    SetParameterDescription("bm.initdisp.maps.hmap", "Map of the initial horizontal disparities");
+    AddParameter(ParameterType_InputImage, "bm.initdisp.maps.hmap",
+      "Horizontal initial disparity map");
+    SetParameterDescription("bm.initdisp.maps.hmap", "Map of the initial "
+      "horizontal disparities");
 
-    AddParameter(ParameterType_InputImage, "bm.initdisp.maps.vmap", "Vertical initial disparity map");
-    SetParameterDescription("bm.initdisp.maps.vmap", "Map of the initial vertical disparities");
+    AddParameter(ParameterType_InputImage, "bm.initdisp.maps.vmap",
+      "Vertical initial disparity map");
+    SetParameterDescription("bm.initdisp.maps.vmap", "Map of the initial "
+      "vertical disparities");
 
     AddParameter(ParameterType_Int, "bm.initdisp.maps.hrad", "Horizontal exploration radius");
-    SetParameterDescription("bm.initdisp.maps.hrad", "Horizontal exploration radius around the initial disparity estimate (in pixels)");
+    SetParameterDescription("bm.initdisp.maps.hrad", "Horizontal exploration "
+      "radius around the initial disparity estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.maps.hrad", 0);
     DisableParameter("bm.initdisp.maps.hrad");
 
     AddParameter(ParameterType_Int, "bm.initdisp.maps.vrad", "Vertical exploration radius");
-    SetParameterDescription("bm.initdisp.maps.vrad", "Vertical exploration radius around the initial disparity estimate (in pixels)");
+    SetParameterDescription("bm.initdisp.maps.vrad", "Vertical exploration "
+      "radius around the initial disparity estimate (in pixels)");
     SetDefaultParameterInt("bm.initdisp.maps.vrad", 0);
     DisableParameter("bm.initdisp.maps.vrad");
 
diff --git a/Modules/Applications/AppStereo/app/otbDisparityMapToElevationMap.cxx b/Modules/Applications/AppStereo/app/otbDisparityMapToElevationMap.cxx
index 6f626cf70ae661ec1fc534772fae3874703c71eb..6302a912f14fdaf910a80970825a70a384ef8807 100644
--- a/Modules/Applications/AppStereo/app/otbDisparityMapToElevationMap.cxx
+++ b/Modules/Applications/AppStereo/app/otbDisparityMapToElevationMap.cxx
@@ -65,39 +65,71 @@ private:
   void DoInit() ITK_OVERRIDE
   {
     SetName("DisparityMapToElevationMap");
-    SetDescription("Projects a disparity map into a regular elevation map");
+    SetDescription("Projects a disparity map into a regular elevation map.");
 
     SetDocName("Disparity map to elevation map");
-    SetDocLongDescription("This application uses a disparity map computed from a stereo image pair to produce an "
-      "elevation map on the ground area covered by the stereo pair. The needed inputs are : the disparity map, "
-      "the stereo pair (in original geometry) and the epipolar deformation grids. These grids have to link the "
-      "original geometry (stereo pair) and the epipolar geometry (disparity map). ");
-    SetDocLimitations("None");
+    SetDocLongDescription("This application uses a disparity map computed from "
+      "a stereo image pair to produce an elevation map on the ground area "
+      "covered by the stereo pair.\n\n"
+      "This application is part of the stereo reconstruction pipeline. It can "
+      "be used after having computed the disparity map with BlockMatching.\n\n"
+      "The needed inputs are : the disparity map, the stereo pair (in original"
+      " geometry) and the epipolar deformation grids. These grids (computed by "
+      "StereoRectificationGridGenerator) have to contain the transform between "
+      "the original geometry (stereo pair) and the epipolar geometry (disparity"
+      " map). The algorithm for each disparity is the following :\n"
+      "  * skip if position is discarded by the disparity mask\n"
+      "  * compute left ray : transform the current position from epipolar "
+      "geometry to left sensor geometry (left rectification grid)\n"
+      "  * compute right ray : shift the current position with current "
+      "disparity and transform from epipolar geometry to right sensor (right "
+      "rectification grid)\n"
+      "  * estimate best 3D intersection between left and right rays\n"
+      "  * for the ground cell of the obtained 3D point, keep its elevation if "
+      "greater than current elevation (keeps the maximum of elevations of all "
+      "3D points in each cell)\n"
+      "\n"
+      "Minimum and maximum elevations settings are here to bound the "
+      "reconstructed DEM.");
+    SetDocLimitations("The epipolar deformation grid should be able to entirely"
+      " fit in memory.");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso("otbStereoRectificationGridGenerator otbBlockMatching");
+    SetDocSeeAlso("[1] StereoRectificationGridGenerator\n"
+      "[2] BlockMatching");
 
     AddDocTag(Tags::Stereo);
 
     AddParameter(ParameterType_Group,"io","Input and output data");
-    SetParameterDescription("io","This group of parameters allows one to set input images, output images and grids.");
+    SetParameterDescription("io","This group of parameters allows one to set "
+      "input images, output images and grids.");
 
     AddParameter(ParameterType_InputImage,"io.in","Input disparity map");
-    SetParameterDescription("io.in","The input disparity map (horizontal disparity in first band, vertical in second)");
+    SetParameterDescription("io.in","The input disparity map (horizontal "
+      "disparity in first band, vertical in second). This map can be computed "
+      "by BlockMatching application.");
 
     AddParameter(ParameterType_InputImage,"io.left","Left sensor image");
-    SetParameterDescription("io.left","Left image in original (sensor) geometry");
+    SetParameterDescription("io.left","Left image in original (sensor) geometry"
+      ". Only the geometric model of this image will be used, not the pixel "
+      "values.");
 
     AddParameter(ParameterType_InputImage,"io.right","Right sensor image");
-    SetParameterDescription("io.right","Right image in original (sensor) geometry");
+    SetParameterDescription("io.right","Right image in original (sensor) "
+      "geometry. Only the geometric model of this image will be used, not the "
+      "pixel values.");
 
     AddParameter(ParameterType_InputImage,"io.lgrid","Left Grid");
-    SetParameterDescription("io.lgrid","Left epipolar grid (deformation grid between sensor et disparity spaces)");
+    SetParameterDescription("io.lgrid","Left epipolar grid (deformation grid "
+      "between left sensor et disparity spaces)");
 
     AddParameter(ParameterType_InputImage,"io.rgrid","Right Grid");
-    SetParameterDescription("io.rgrid","Right epipolar grid (deformation grid between sensor et disparity spaces)");
+    SetParameterDescription("io.rgrid","Right epipolar grid (deformation grid "
+      "between rigth sensor et disparity spaces)");
 
     AddParameter(ParameterType_OutputImage,"io.out","Output elevation map");
-    SetParameterDescription("io.out", "Output elevation map in ground projection");
+    SetParameterDescription("io.out", "Output elevation map in ground "
+      "projection. Elevation values are in meters. Floating point pixel type "
+      "are expected.");
 
     AddParameter(ParameterType_Float,"step","DEM step");
     SetParameterDescription("step","Spacing of the output elevation map (in meters)");
@@ -112,7 +144,8 @@ private:
     SetDefaultParameterFloat("hmax",100.0);
 
     AddParameter(ParameterType_InputImage,"io.mask","Disparity mask");
-    SetParameterDescription("io.mask","Masked disparity cells won't be projected");
+    SetParameterDescription("io.mask","Masked disparity pixels won't be "
+      "projected (mask values equal to zero)");
     MandatoryOff("io.mask");
 
     ElevationParametersHandler::AddElevationParameters(this, "elev");
diff --git a/Modules/Applications/AppStereo/app/otbFineRegistration.cxx b/Modules/Applications/AppStereo/app/otbFineRegistration.cxx
index d24627f06f90b7f8bd8beaccb4b5ffe58ddc4ffe..a7fed89a0e400d60eeeae15067c35f10e9e76293 100644
--- a/Modules/Applications/AppStereo/app/otbFineRegistration.cxx
+++ b/Modules/Applications/AppStereo/app/otbFineRegistration.cxx
@@ -120,7 +120,16 @@ private:
     SetDescription("Estimate disparity map between two images.");
 
     SetDocName("Fine Registration");
-    SetDocLongDescription("Estimate disparity map between two images. Output image contain x offset, y offset and metric value.");
+    SetDocLongDescription("This application computes a disparity map between "
+      "two images that correspond to the same scene. It is intended for case "
+      "where small misregistration between images should be estimated and fixed"
+      ". The search is performed in 2D.\n\n"
+      "The algorithm uses an iterative approach to estimate a best match "
+      "between local patches. The typical use case is registration betwween "
+      "similar bands, or between two acquisitions. The output image contains "
+      "X and Y offsets, as well as the metric value. A sub-pixel accuracy can "
+      "be expected. The input images should have the same size and same "
+      "physical space.");
     SetDocLimitations("None");
     SetDocAuthors("OTB-Team");
     SetDocSeeAlso(" ");
@@ -134,7 +143,9 @@ private:
     SetParameterDescription( "sec", "The secondary image." );
 
     AddParameter(ParameterType_OutputImage,  "out",   "Output Image");
-    SetParameterDescription( "out", "The output image." );
+    SetParameterDescription( "out", "The output image contains 3 bands, for X "
+      "offset, Y offset and the metric value. It may contain a 4th one with the"
+      " validity mask (if used)." );
 
     AddParameter(ParameterType_Int,  "erx",   "Exploration Radius X");
     SetParameterDescription( "erx", "The exploration radius along x (in pixels)" );
@@ -145,15 +156,18 @@ private:
     SetMinimumParameterIntValue("ery", 0);
 
     AddParameter(ParameterType_Int,  "mrx",   "Metric Radius X");
-    SetParameterDescription( "mrx", "Radius along x (in pixels) of the metric computation window" );
+    SetParameterDescription( "mrx", "Radius along x (in pixels) of the metric "
+      "computation window" );
     SetMinimumParameterIntValue("mrx", 0);
 
     AddParameter(ParameterType_Int,  "mry",   "Metric Radius Y");
-    SetParameterDescription( "mry", "Radius along y (in pixels) of the metric computation window" );
+    SetParameterDescription( "mry", "Radius along y (in pixels) of the metric "
+      "computation window" );
     SetMinimumParameterIntValue("mry", 0);
 
     AddParameter(ParameterType_InputImage,  "w",   "Image To Warp");
-    SetParameterDescription( "w", "The image to warp after disparity estimation is completed" );
+    SetParameterDescription( "w", "The image to warp after disparity estimation"
+    " is completed." );
     MandatoryOff("w");
 
     AddParameter(ParameterType_OutputImage,  "wo",   "Output Warped Image");
@@ -161,65 +175,81 @@ private:
     MandatoryOff("wo");
 
     AddParameter(ParameterType_Float,  "cox",   "Coarse Offset X");
-    SetParameterDescription( "cox", "Coarse offset along x (in physical space) between the two images" );
+    SetParameterDescription( "cox", "Coarse offset along x (in physical space)"
+      " between the two images, used as an initial offset for all pixels." );
     SetDefaultParameterFloat("cox", 0.0);
     MandatoryOff("cox");
 
     AddParameter(ParameterType_Float,  "coy",   "Coarse Offset Y");
-    SetParameterDescription( "coy", "Coarse offset along y (in physical space) between the two images" );
+    SetParameterDescription( "coy", "Coarse offset along y (in physical space)"
+      " between the two images, used as an initial offset for all pixels." );
     SetDefaultParameterFloat("coy", 0.0);
     MandatoryOff("coy");
 
     AddParameter(ParameterType_Float,  "ssrx",   "Sub-Sampling Rate X");
-    SetParameterDescription( "ssrx", "Generates a result at a coarser resolution with a given sub-sampling rate along X" );
+    SetParameterDescription( "ssrx", "Generates a result at a coarser "
+      "resolution with a given sub-sampling rate along X" );
     SetDefaultParameterFloat("ssrx", 1.0);
     SetMinimumParameterFloatValue("ssrx", 1.0);
     MandatoryOff("ssrx");
 
     AddParameter(ParameterType_Float,  "ssry",   "Sub-Sampling Rate Y");
-    SetParameterDescription( "ssry", "Generates a result at a coarser resolution with a given sub-sampling rate along Y" );
+    SetParameterDescription( "ssry", "Generates a result at a coarser "
+      "resolution with a given sub-sampling rate along Y" );
     SetDefaultParameterFloat("ssry", 1.0);
     SetMinimumParameterFloatValue("ssry", 1.0);
     MandatoryOff("ssry");
 
     AddParameter(ParameterType_Float,  "rgsx",   "Reference Gaussian Smoothing X");
-    SetParameterDescription( "rgsx", "Performs a gaussian smoothing of the reference image. Parameter is gaussian sigma (in pixels) in X direction." );
+    SetParameterDescription( "rgsx", "Performs a gaussian smoothing of the "
+      "reference image. Parameter is gaussian sigma (in pixels) in X direction." );
     MandatoryOff("rgsx");
 
     AddParameter(ParameterType_Float,  "rgsy",   "Reference Gaussian Smoothing Y");
-    SetParameterDescription( "rgsy", "Performs a gaussian smoothing of the reference image. Parameter is gaussian sigma (in pixels) in Y direction." );
+    SetParameterDescription( "rgsy", "Performs a gaussian smoothing of the "
+      "reference image. Parameter is gaussian sigma (in pixels) in Y direction." );
     MandatoryOff("rgsy");
 
     AddParameter(ParameterType_Float,  "sgsx",   "Secondary Gaussian Smoothing X");
-    SetParameterDescription( "sgsx", "Performs a gaussian smoothing of the secondary image. Parameter is gaussian sigma (in pixels) in X direction." );
+    SetParameterDescription( "sgsx", "Performs a gaussian smoothing of the "
+      "secondary image. Parameter is gaussian sigma (in pixels) in X direction." );
     MandatoryOff("sgsx");
 
     AddParameter(ParameterType_Float,  "sgsy",   "Secondary Gaussian Smoothing Y");
-    SetParameterDescription( "sgsy", "Performs a gaussian smoothing of the secondary image. Parameter is gaussian sigma (in pixels) in Y direction." );
+    SetParameterDescription( "sgsy", "Performs a gaussian smoothing of the "
+      "secondary image. Parameter is gaussian sigma (in pixels) in Y direction." );
     MandatoryOff("sgsy");
 
     AddParameter(ParameterType_String,  "m",   "Metric");
-    SetParameterDescription( "m", "Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation" );
+    SetParameterDescription( "m", "Choose the metric used for block matching. "
+      "Available metrics are cross-correlation (CC), cross-correlation with "
+      "subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal "
+      "square difference (MRSD) and mutual information (MI). Default is "
+      "cross-correlation" );
     MandatoryOff("m");
 
     AddParameter(ParameterType_Float,  "spa",   "SubPixelAccuracy");
-    SetParameterDescription( "spa", "Metric extrema location will be refined up to the given accuracy. Default is 0.01" );
+    SetParameterDescription( "spa", "Metric extrema location will be refined up"
+      " to the given accuracy. Default is 0.01" );
     SetDefaultParameterFloat("spa", 0.01);
     SetMinimumParameterFloatValue("spa", 0.0);
     MandatoryOff("spa");
 
     AddParameter(ParameterType_Float,  "cva",   "ConvergenceAccuracy");
-    SetParameterDescription( "cva", "Metric extrema will be refined up to the given accuracy. Default is 0.01" );
+    SetParameterDescription( "cva", "Metric extrema will be refined up to the"
+      " given accuracy. Default is 0.01" );
     SetDefaultParameterFloat("cva", 0.01);
     SetMinimumParameterFloatValue("cva", 0.0);
     MandatoryOff("cva");
 
     AddParameter(ParameterType_Float,  "vmlt",   "Validity Mask Lower Threshold");
-    SetParameterDescription( "vmlt", "Lower threshold to obtain a validity mask." );
+    SetParameterDescription( "vmlt", "Lower threshold to compute the validity "
+      "mask. This mask will be the 4th output band." );
     MandatoryOff("vmlt");
 
     AddParameter(ParameterType_Float,  "vmut",   "Validity Mask Upper Threshold");
-    SetParameterDescription( "vmut", "Upper threshold to obtain a validity mask." );
+    SetParameterDescription( "vmut", "Upper threshold to obtain a validity "
+      "mask. This mask will be the 4th output band." );
     MandatoryOff("vmut");
 
     AddRAMParameter();
diff --git a/Modules/Applications/AppStereo/app/otbGeneratePlyFile.cxx b/Modules/Applications/AppStereo/app/otbGeneratePlyFile.cxx
index fde86538aef54ca2e7bf7ff6b903325f4ed2665c..928b1da3e6f9303a2c72fb39ce97e335e063abd1 100644
--- a/Modules/Applications/AppStereo/app/otbGeneratePlyFile.cxx
+++ b/Modules/Applications/AppStereo/app/otbGeneratePlyFile.cxx
@@ -58,19 +58,38 @@ private:
     SetDescription("Generate a 3D Ply file from a DEM and a color image.");
 
     SetDocName("Ply 3D files generation");
-    SetDocLongDescription("Generate a 3D Ply file from a DEM and a color image.");
-    SetDocLimitations(" ");
+    SetDocLongDescription("The application converts an image containing "
+      "elevations into a PLY file, which is a file format to store 3D models. "
+      "This format is adpated for visualization on software such as MeshLab [2]"
+      " or CloudCompare [3]\n\n"
+      "This application is part of the stereo reconstruction framework. The "
+      "input data can be produced by the application DisparityMapToElevationMap.\n\n"
+      "There are two types of supported input images:\n"
+      "  * A DEM image, with a ground projection, containing elevation values. "
+      "Each elevation value can be considered as a 3D point.\n"
+      "  * A 3D grid image, containing 5 bands (the first 3 are the 3D "
+      "coordinates of each point, the 5th is a validity mask where valid values"
+      " are larger or equal to 1)\n"
+      "\n"
+      "The user shall also give a support image that contains color values for"
+      " each 3D point. The color values will be embedded in the PLY file.");
+    SetDocLimitations("The input DEM image has to entirely fit into memory.");
     SetDocAuthors("OTB-Team");
-    SetDocSeeAlso(" ");
+    SetDocSeeAlso("- [1] DisparityMapToElevationMap \n"
+      "- [2] http://www.meshlab.net/ \n"
+      "- [3] http://www.cloudcompare.org/");
 
     AddDocTag(Tags::Geometry);
 
-    AddParameter(ParameterType_InputImage,"indem","The input DEM");
-    SetParameterDescription("indem", "The input DEM");
+    AddParameter(ParameterType_InputImage,"indem","The input DEM image");
+    SetParameterDescription("indem", "The image should be either a projected "
+      "DEM or a 3D grid containing 3D point coordinates and a validity mask.");
 
     AddParameter(ParameterType_Choice,"mode", "Conversion Mode");
     AddChoice("mode.dem","DEM");
-    SetParameterDescription("mode.dem","DEM conversion mode");
+    SetParameterDescription("mode.dem","DEM conversion mode (the projection "
+      "information of the DEM is used to derive the X and Y coordinates of each"
+      " point)");
 
     AddChoice("mode.3dgrid","3D grid");
     SetParameterDescription("mode.3dgrid","3D grid conversion mode");
@@ -79,10 +98,14 @@ private:
     MapProjectionParametersHandler::AddMapProjectionParameters(this, "map");
 
     AddParameter(ParameterType_InputImage,"incolor","The input color image");
-    SetParameterDescription("incolor", "The input color image");
+    SetParameterDescription("incolor", "If the color image has 4 bands it will "
+      "be interpreted as Red, Green, Blue, NIR. In other cases, only the first "
+      "one is used (gray scale colors). The color values are expected in the "
+      "range 0 - 255, and will be embedded with each 3D ""point of the PLY file.");
 
     AddParameter(ParameterType_OutputFilename,"out","The output Ply file");
-    SetParameterDescription("out","The output Ply file");
+    SetParameterDescription("out","The output Ply file will contain as many 3D "
+      "points as pixels in the input DEM.");
 
     // Doc example
     SetDocExampleParameterValue("indem","image_dem.tif");
diff --git a/Modules/Applications/AppTest/test/otbWrapperApplicationDocTests.cxx b/Modules/Applications/AppTest/test/otbWrapperApplicationDocTests.cxx
index b90ed3ec7225d5fe5c00ffb5983147dd87afd8a0..636b3808081b19a9c69c740b4f0f7954be5db90f 100644
--- a/Modules/Applications/AppTest/test/otbWrapperApplicationDocTests.cxx
+++ b/Modules/Applications/AppTest/test/otbWrapperApplicationDocTests.cxx
@@ -27,6 +27,68 @@
 using otb::Wrapper::Application;
 using otb::Wrapper::ApplicationRegistry;
 
+typedef std::pair<std::string,std::string> DocElement;
+
+bool CheckNonEmpty(const DocElement & elem)
+{
+  bool ret = true;
+  if (elem.second == "")
+    {
+    std::cout << "  /!\\ Missing "<< elem.first << std::endl;
+    ret = false;
+    }
+  return ret;
+}
+
+bool CheckMinimumSize(const DocElement & elem, unsigned int size)
+{
+  bool ret = true;
+  if (elem.second.size() < size)
+    {
+    std::cout<<"  /!\\ " << elem.first <<" too small..."<<std::endl;
+    ret = false;
+    }
+  return ret;
+}
+
+bool CheckNoNewline(const DocElement & elem)
+{
+  bool ret = true;
+  if (elem.second.find('\n') != std::string::npos)
+    {
+    std::cout << "  /!\\ "<< elem.first << " should not contain newlines"<<std::endl;
+    ret = false;
+    }
+  return ret;
+}
+
+bool CheckNoTrailingNewline(const DocElement & elem)
+{
+  bool ret = true;
+  std::string whitespace(" \t\f\v\r");
+  size_t pos = elem.second.find_last_not_of(whitespace);
+  if (pos != std::string::npos && elem.second.at(pos) == '\n')
+    {
+    std::cout << "  /!\\ "<< elem.first << " should not end with a newline" << std::endl;
+    ret = false;
+    }
+  return ret;
+}
+
+bool CheckMultiline(const DocElement & elem)
+{
+  bool ret = true;
+  std::string whitespace(" \t\f\v\r");
+  size_t pos = elem.second.find('\n');
+  size_t lastPos = elem.second.find_last_not_of(whitespace);
+  if (pos == std::string::npos || pos == lastPos)
+    {
+    std::cout << "  /!\\ "<< elem.first << " should not be a single line" << std::endl;
+    ret = false;
+    }
+  return ret;
+}
+
 int otbWrapperApplicationDocTest(int argc, char* argv[])
 {
   if (argc < 2)
@@ -69,46 +131,34 @@ int otbWrapperApplicationDocTest(int argc, char* argv[])
       }
 
     // Check doc element...
-    if( std::string(app->GetName()) == "" )
-      {
-      std::cout<<"Missing Name."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDocName()) == "" )
-      {
-      std::cout<<"Missing Doc Name."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDescription()) == "" )
-      {
-      std::cout<<"Missing Description."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDocLongDescription()) == "" )
-      {
-      std::cout<<"Missing DocLongDescription."<<std::endl;
-      isOK = false;
-      }
-    else if( std::string(app->GetDocLongDescription()).size() < 30 )
-      {
-      std::cout<<"DocLongDescription too small..."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDocAuthors()) == "" )
-      {
-      std::cout<<"Missing DocAuthors."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDocLimitations()) == "" )
-      {
-      std::cout<<"Missing DocLimitations."<<std::endl;
-      isOK = false;
-      }
-    if( std::string(app->GetDocSeeAlso()) == "" )
-      {
-      std::cout<<"Missing DocSeeAlso."<<std::endl;
-      isOK = false;
-      }
+    DocElement name("Name",app->GetName());
+    DocElement docName("Doc Name",app->GetDocName());
+    DocElement description("Description",app->GetDescription());
+    DocElement longDescription("Long description",app->GetDocLongDescription());
+    DocElement authors("DocAuthors",app->GetDocAuthors());
+    DocElement limitations("DocLimitations",app->GetDocLimitations());
+    DocElement seeAlso("DocSeeAlso",app->GetDocSeeAlso());
+
+    isOK = CheckNonEmpty(name) && isOK;
+    isOK = CheckNoNewline(name) && isOK;
+
+    isOK = CheckNonEmpty(docName) && isOK;
+    isOK = CheckNoNewline(docName) && isOK;
+
+    isOK = CheckNonEmpty(description) && isOK;
+
+    isOK = CheckNonEmpty(longDescription) && isOK;
+    isOK = CheckMinimumSize(longDescription,30) && isOK;
+    isOK = CheckNoTrailingNewline(longDescription) && isOK;
+    //isOK = CheckMultiline(longDescription) && isOK;
+
+    isOK = CheckNonEmpty(authors) && isOK;
+
+    isOK = CheckNonEmpty(limitations) && isOK;
+
+    isOK = CheckNonEmpty(seeAlso) && isOK;
+    // TODO : check format of SeeAlso section
+
     if( app->GetDocTags().size() == 0 )
       {
       std::cout<<"Missing DocTags."<<std::endl;
diff --git a/Modules/Core/Common/include/otbUnaryFunctorImageFilter.h b/Modules/Core/Common/include/otbUnaryFunctorImageFilter.h
index 798d8fe6c5aaa75994a24a3718ca84e529be51a4..2217de58baf54d756792382afc2c6080ccda5ddd 100644
--- a/Modules/Core/Common/include/otbUnaryFunctorImageFilter.h
+++ b/Modules/Core/Common/include/otbUnaryFunctorImageFilter.h
@@ -32,7 +32,7 @@ namespace otb
  * Add the capability to change the number of channel when operation on
  * VectorImage compared to the itk::UnaryFunctorImageFilter
  *
- * The number of channel is provided by the functor: TFunction::OutputSize. If
+ * The number of channel is provided by the functor: TFunction::GetOutputSize. If
  * this number is lower or equal to zero, the behavior of the itk::UnaryFunctorImageFilter
  * remains unchanged.
  *
diff --git a/Modules/Core/Common/src/otbConfigure.h.in b/Modules/Core/Common/src/otbConfigure.h.in
index d6968cb48f9ac97df74af529d277c4525d5ac2b0..5194398344bab96a44eb4bb622fda9dc1bf0ae46 100644
--- a/Modules/Core/Common/src/otbConfigure.h.in
+++ b/Modules/Core/Common/src/otbConfigure.h.in
@@ -31,3 +31,7 @@
 #cmakedefine OTB_SHOW_ALL_MSG_DEBUG
 
 #cmakedefine OTB_USE_GDAL_20
+
+#cmakedefine OTB_USE_OPENMP
+
+#cmakedefine OTB_USE_SSE_FLAGS
diff --git a/Modules/Core/SpatialObjects/include/otbLineSpatialObject.h b/Modules/Core/SpatialObjects/include/otbLineSpatialObject.h
index cc04dacdd8526f661aa9209b94cdff9e3fb44aa9..a4adf2d0548ce1eb525d6b1804eb484455d12961 100644
--- a/Modules/Core/SpatialObjects/include/otbLineSpatialObject.h
+++ b/Modules/Core/SpatialObjects/include/otbLineSpatialObject.h
@@ -64,6 +64,8 @@ public:
   typedef std::vector<LinePointType>                     PointListType;
   typedef itk::VectorContainer<unsigned long, PointType> PointContainerType;
   typedef itk::SmartPointer<PointContainerType>          PointContainerPointer;
+  typedef itk::SizeValueType SizeValueType;
+  typedef itk::IdentifierType IdentifierType;
 
   /** Returns a reference to the list of the Line points.*/
   PointListType& GetPoints(void);
@@ -72,19 +74,19 @@ public:
   void SetPoints(PointListType& newPoints);
 
   /** Return a point in the list given the index */
-  const SpatialObjectPointType* GetPoint(unsigned long id) const ITK_OVERRIDE
+  const SpatialObjectPointType* GetPoint(IdentifierType id) const ITK_OVERRIDE
   {
     return &(m_Points[id]);
   }
 
   /** Return a point in the list given the index */
-  SpatialObjectPointType* GetPoint(unsigned long id) ITK_OVERRIDE
+  SpatialObjectPointType* GetPoint(IdentifierType id) ITK_OVERRIDE
   {
     return &(m_Points[id]);
   }
 
   /** Return the number of points in the list */
-  itk::SizeValueType GetNumberOfPoints(void) const ITK_OVERRIDE
+  SizeValueType GetNumberOfPoints(void) const ITK_OVERRIDE
   {
     return m_Points.size();
   }
diff --git a/Modules/Feature/Descriptors/test/otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii.cxx b/Modules/Feature/Descriptors/test/otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii.cxx
index 4a2a416e5f9903b969816ecc22b52a059c419d90..d5f0f32747e42ebc0a7eb6a119a1d12628b34f2b 100644
--- a/Modules/Feature/Descriptors/test/otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii.cxx
+++ b/Modules/Feature/Descriptors/test/otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii.cxx
@@ -36,9 +36,9 @@ bool CMP(std::vector<float>  a, std::vector<float>  b)
   return lexicographical_compare(a.begin(), a.begin() + 2, b.begin(), b.begin() + 2);
 }
 
-int otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii(int itkNotUsed(argc), char * argv[])
+int
+otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii( int itkNotUsed( argc ), char * argv[] )
 {
-
   const char * infname = argv[1];
   const char * outfname = argv[2];
 
@@ -59,7 +59,7 @@ int otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii(int itkNotUsed(a
   typedef PointSetType::PointDataContainer PointDataContainerType;
   typedef PointDataContainerType::Iterator PointDataIteratorType;
 
-  typedef std::vector<float>          siftDataVector;
+  typedef std::vector< RealType > siftDataVector;
   typedef std::vector<siftDataVector> ImageDataType;   //Kind of PointSet with vectors
 
   // Instantiating object
@@ -76,10 +76,29 @@ int otbImageToFastSIFTKeyPointSetFilterOutputInterestPointAscii(int itkNotUsed(a
   PointsIteratorType    pIt = filter->GetOutput()->GetPoints()->Begin();
   PointDataIteratorType pDataIt = filter->GetOutput()->GetPointData()->Begin();
 
+  assert(
+    filter->GetOutput()->GetPoints()->Size() ==
+    filter->GetOutput()->GetPointData()->Size() );
+
   std::ofstream outfile(outfname);
 
   outfile << "Number of scales: " << scales << std::endl;
-  outfile << "Number of SIFT key points: " << filter->GetOutput()->GetNumberOfPoints() << std::endl;
+
+  outfile << "Number of SIFT key points: "
+	  << filter->GetOutput()->GetNumberOfPoints()
+	  << std::endl;
+
+  outfile << "Number of points: "
+	  << filter->GetOutput()->GetPoints()->Size()
+	  << std::endl;
+
+  outfile << "Number of points data: "
+	  << filter->GetOutput()->GetPointData()->Size()
+	  << std::endl;
+
+  if( filter->GetOutput()->GetPoints()->Size() !=
+      filter->GetOutput()->GetPointData()->Size() )
+    return EXIT_FAILURE;
 
   // Copy the PointSet to std::vector< std::vector >
   while (pIt != filter->GetOutput()->GetPoints()->End())
diff --git a/Modules/Filtering/ImageManipulation/include/otbBinaryFunctorImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbBinaryFunctorImageFilter.h
new file mode 100644
index 0000000000000000000000000000000000000000..e0e246aee5f7e787c0d4b994874bd42f75c01d06
--- /dev/null
+++ b/Modules/Filtering/ImageManipulation/include/otbBinaryFunctorImageFilter.h
@@ -0,0 +1,84 @@
+/*=========================================================================
+
+  Program:   ORFEO Toolbox
+  Language:  C++
+  Date:      $Date$
+  Version:   $Revision$
+
+
+  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
+  See OTBCopyright.txt for details.
+
+
+     This software is distributed WITHOUT ANY WARRANTY; without even
+     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+     PURPOSE.  See the above copyright notices for more information.
+
+=========================================================================*/
+#ifndef otbBinaryFunctorImageFilter_h
+#define otbBinaryFunctorImageFilter_h
+
+#include "itkBinaryFunctorImageFilter.h"
+
+namespace otb
+{
+/**
+ * \class BinaryFunctorImageFilter
+ * \brief Implements pixel-wise generic operation on two images.
+ *
+ * Add the capability to change the number of channel when operation on
+ * VectorImage compared to the itk::BinaryFunctorImageFilter
+ *
+ * The number of channel is provided by the functor: TFunction::GetOutputSize. If
+ * this number is lower or equal to zero, the behavior of the itk::BinaryFunctorImageFilter
+ * remains unchanged.
+ *
+ * \sa itk::BinaryFunctorImageFilter
+ *
+ * \ingroup OTBImageManipulation
+ */
+template <class TInputImage1, class TInputImage2, class TOutputImage, class TFunction>
+class ITK_EXPORT BinaryFunctorImageFilter : public itk::BinaryFunctorImageFilter<TInputImage1, TInputImage2, TOutputImage, TFunction>
+{
+public:
+  /** Standard class typedefs. */
+  typedef BinaryFunctorImageFilter                                            Self;
+  typedef itk::BinaryFunctorImageFilter<TInputImage1, TInputImage2, TOutputImage, TFunction> Superclass;
+  typedef itk::SmartPointer<Self>                                            Pointer;
+  typedef itk::SmartPointer<const Self>                                      ConstPointer;
+
+  /** Method for creation through the object factory. */
+  itkNewMacro(Self);
+
+  /** Run-time type information (and related methods). */
+  itkTypeMacro(BinaryFunctorImageFilter, itk::BinaryFunctorImageFilter);
+
+protected:
+  BinaryFunctorImageFilter() {};
+  ~BinaryFunctorImageFilter() ITK_OVERRIDE {}
+
+  /** BinaryFunctorImageFilter can produce an image which has a different number of bands
+   * than its input image.  As such, BinaryFunctorImageFilter
+   * needs to provide an implementation for
+   * GenerateOutputInformation() in order to inform the pipeline
+   * execution model.  The original documentation of this method is
+   * below.
+   *
+   * \sa ProcessObject::GenerateOutputInformaton()  */
+  void GenerateOutputInformation() ITK_OVERRIDE
+  {
+    Superclass::GenerateOutputInformation();
+    typename Superclass::OutputImagePointer outputPtr = this->GetOutput();
+    outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info
+      this->GetFunctor().GetOutputSize());
+  }
+
+private:
+  BinaryFunctorImageFilter(const Self &); //purposely not implemented
+  void operator =(const Self&); //purposely not implemented
+
+};
+
+} // end namespace otb
+
+#endif
diff --git a/Modules/Filtering/ImageManipulation/include/otbTernaryFunctorImageFilter.h b/Modules/Filtering/ImageManipulation/include/otbTernaryFunctorImageFilter.h
new file mode 100644
index 0000000000000000000000000000000000000000..3e6d3f540505708893faa290c511633e55d4b462
--- /dev/null
+++ b/Modules/Filtering/ImageManipulation/include/otbTernaryFunctorImageFilter.h
@@ -0,0 +1,84 @@
+/*=========================================================================
+
+  Program:   ORFEO Toolbox
+  Language:  C++
+  Date:      $Date$
+  Version:   $Revision$
+
+
+  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
+  See OTBCopyright.txt for details.
+
+
+     This software is distributed WITHOUT ANY WARRANTY; without even
+     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+     PURPOSE.  See the above copyright notices for more information.
+
+=========================================================================*/
+#ifndef otbTernaryFunctorImageFilter_h
+#define otbTernaryFunctorImageFilter_h
+
+#include "itkTernaryFunctorImageFilter.h"
+
+namespace otb
+{
+/**
+ * \class TernaryFunctorImageFilter
+ * \brief Implements pixel-wise generic operation on three images.
+ *
+ * Add the capability to change the number of channel when operation on
+ * VectorImage compared to the itk::TernaryFunctorImageFilter
+ *
+ * The number of channel is provided by the functor: TFunction::GetOutputSize. If
+ * this number is lower or equal to zero, the behavior of the itk::TernaryFunctorImageFilter
+ * remains unchanged.
+ *
+ * \sa itk::TernaryFunctorImageFilter
+ *
+ * \ingroup OTBImageManipulation
+ */
+template <class TInputImage1, class TInputImage2, class TInputImage3, class TOutputImage, class TFunction>
+class ITK_EXPORT TernaryFunctorImageFilter : public itk::TernaryFunctorImageFilter<TInputImage1, TInputImage2, TInputImage3, TOutputImage, TFunction>
+{
+public:
+  /** Standard class typedefs. */
+  typedef TernaryFunctorImageFilter                                            Self;
+  typedef itk::TernaryFunctorImageFilter<TInputImage1, TInputImage2, TInputImage3, TOutputImage, TFunction> Superclass;
+  typedef itk::SmartPointer<Self>                                            Pointer;
+  typedef itk::SmartPointer<const Self>                                      ConstPointer;
+
+  /** Method for creation through the object factory. */
+  itkNewMacro(Self);
+
+  /** Run-time type information (and related methods). */
+  itkTypeMacro(TernaryFunctorImageFilter, itk::TernaryFunctorImageFilter);
+
+protected:
+  TernaryFunctorImageFilter() {};
+  ~TernaryFunctorImageFilter() ITK_OVERRIDE {}
+
+  /** TernaryFunctorImageFilter can produce an image which has a different number of bands
+   * than its input image.  As such, TernaryFunctorImageFilter
+   * needs to provide an implementation for
+   * GenerateOutputInformation() in order to inform the pipeline
+   * execution model.  The original documentation of this method is
+   * below.
+   *
+   * \sa ProcessObject::GenerateOutputInformaton()  */
+  void GenerateOutputInformation() ITK_OVERRIDE
+  {
+    Superclass::GenerateOutputInformation();
+    typename Superclass::OutputImagePointer outputPtr = this->GetOutput();
+    outputPtr->SetNumberOfComponentsPerPixel( // propagate vector length info
+      this->GetFunctor().GetOutputSize());
+  }
+
+private:
+  TernaryFunctorImageFilter(const Self &); //purposely not implemented
+  void operator =(const Self&); //purposely not implemented
+
+};
+
+} // end namespace otb
+
+#endif
diff --git a/Modules/Filtering/Polarimetry/test/CMakeLists.txt b/Modules/Filtering/Polarimetry/test/CMakeLists.txt
index 73045f5cd8b40c0395a34604f11abb85dceeaa24..d1c77627cf5316b3353b3eab49f760faca17a690 100644
--- a/Modules/Filtering/Polarimetry/test/CMakeLists.txt
+++ b/Modules/Filtering/Polarimetry/test/CMakeLists.txt
@@ -74,7 +74,7 @@ otb_add_test(NAME saTvVectorMultiChannelsPolarimetricSynthesisFilter COMMAND otb
   --compare-image ${EPSILON_7}   ${BASELINE}/saTvMultiPolarimetricSynthesis1.tif
   ${TEMP}/resMultiPolarimetricSynthesis1.tif
   otbVectorMultiChannelsPolarimetricSynthesisFilter
-  ${INPUTDATA}/RSAT2_AltonaExtract_1000_1000_100_100.hdr
+  ${INPUTDATA}/RSAT2_AltonaExtract_1000_1000_100_100.tif
   ${TEMP}/resMultiPolarimetricSynthesis1.tif
   10.0     # PsiI
   0.0     # KhiI
diff --git a/Modules/Hyperspectral/EndmembersExtraction/include/otbVcaImageFilter.txx b/Modules/Hyperspectral/EndmembersExtraction/include/otbVcaImageFilter.txx
index 919e3a6d322dc4d5d9cc2e2cf88d16fc457f8629..014ff8e7eef8cc32e52e8154eb583dbab4142020 100644
--- a/Modules/Hyperspectral/EndmembersExtraction/include/otbVcaImageFilter.txx
+++ b/Modules/Hyperspectral/EndmembersExtraction/include/otbVcaImageFilter.txx
@@ -233,7 +233,7 @@ void VCAImageFilter<TImage>::GenerateData()
   vnl_matrix<PrecisionType> A(m_NumberOfEndmembers, m_NumberOfEndmembers);
   A.fill(0);
   A(m_NumberOfEndmembers - 1, 0) = 1;
-  typename RandomVariateGeneratorType::Pointer randomGen = RandomVariateGeneratorType::New();
+  typename RandomVariateGeneratorType::Pointer randomGen = RandomVariateGeneratorType::GetInstance();
 
   for (unsigned int i = 0; i < m_NumberOfEndmembers; ++i)
     {
diff --git a/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx b/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx
index 4e3b75a54835bd4fdd132f431fecc2336806d0fe..812c938e6b86b6dd5005abc9939e5275b639f8e5 100644
--- a/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx
+++ b/Modules/IO/IOGDAL/src/otbGDALImageIO.cxx
@@ -1766,19 +1766,26 @@ void GDALImageIO::InternalWriteImageInformation(const void* buffer)
   /* -------------------------------------------------------------------- */
   /*  Set the six coefficients of affine geoTransform                     */
   /* -------------------------------------------------------------------- */
-  itk::VariableLengthVector<double> geoTransform(6);
-  /// Reporting origin and spacing
-  // Beware : GDAL origin is at the corner of the top-left pixel
-  // whereas OTB/ITK origin is at the centre of the top-left pixel
-  geoTransform[0] = m_Origin[0] - 0.5*m_Spacing[0];
-  geoTransform[3] = m_Origin[1] - 0.5*m_Spacing[1];
-  geoTransform[1] = m_Spacing[0];
-  geoTransform[5] = m_Spacing[1];
-
-  // FIXME: Here component 1 and 4 should be replaced by the orientation parameters
-  geoTransform[2] = 0.;
-  geoTransform[4] = 0.;
-  dataset->SetGeoTransform(const_cast<double*>(geoTransform.GetDataPointer()));
+  if ( vcl_abs(m_Origin[0] - 0.5) > Epsilon
+    || vcl_abs(m_Origin[1] - 0.5) > Epsilon
+    || vcl_abs(m_Spacing[0] - 1.0) > Epsilon
+    || vcl_abs(m_Spacing[1] - 1.0) > Epsilon )
+    {
+    // Only set the geotransform if it is not identity (it may erase GCP)
+    itk::VariableLengthVector<double> geoTransform(6);
+    /// Reporting origin and spacing
+    // Beware : GDAL origin is at the corner of the top-left pixel
+    // whereas OTB/ITK origin is at the centre of the top-left pixel
+    geoTransform[0] = m_Origin[0] - 0.5*m_Spacing[0];
+    geoTransform[3] = m_Origin[1] - 0.5*m_Spacing[1];
+    geoTransform[1] = m_Spacing[0];
+    geoTransform[5] = m_Spacing[1];
+
+    // FIXME: Here component 1 and 4 should be replaced by the orientation parameters
+    geoTransform[2] = 0.;
+    geoTransform[4] = 0.;
+    dataset->SetGeoTransform(const_cast<double*>(geoTransform.GetDataPointer()));
+    }
 
   /* -------------------------------------------------------------------- */
   /*      Report metadata.                                                */
diff --git a/Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx b/Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx
index 8248ef8a1df7019224761445e628f1f59e3d573a..53b61999699415cf18f36e1f182cf698560fbe4a 100644
--- a/Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx
+++ b/Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx
@@ -211,7 +211,7 @@ void OGRIOHelper
     otb::VectorDataKeywordlist kwl;
     for (int fieldNum = 0; fieldNum < feature->GetFieldCount(); ++fieldNum)
       {
-      if (feature->IsFieldSet(fieldNum))
+      if (ogr::version_proxy::IsFieldSetAndNotNull(feature, fieldNum))
         {
         kwl.AddField(feature->GetFieldDefnRef(fieldNum), feature->GetRawFieldRef(fieldNum));
         }
diff --git a/Modules/IO/ImageIO/test/CMakeLists.txt b/Modules/IO/ImageIO/test/CMakeLists.txt
index d8374f8955993381a7db0634300990f485c57964..b7ca467925b827739c0b7e23def8267a7d4306ca 100644
--- a/Modules/IO/ImageIO/test/CMakeLists.txt
+++ b/Modules/IO/ImageIO/test/CMakeLists.txt
@@ -458,13 +458,13 @@ otb_add_test(NAME ioTvStreamingImageFileWriterCalculateNumberOfDivisions_SetNumb
   )
 
 otb_add_test(NAME ioTvStreamingImageFileWriterCalculateNumberOfDivisions_SetTileDimensionTiledStreaming COMMAND otbImageIOTestDriver
-  --compare-image ${EPSILON_9}   ${INPUTDATA}/ToulouseQuickBird_Extrait_1500_3750.tif
+  --compare-image ${EPSILON_9}   ${INPUTDATA}/QB_Toulouse_Ortho_PAN_WGS84.tif
   ${TEMP}/ioStreamingImageFileWriterCalculateNumberOfDivisions_SetTileDimensionTiledStreaming.tif
   otbImageFileWriterTestCalculateNumberOfDivisions
-  ${INPUTDATA}/ToulouseQuickBird_Extrait_1500_3750.tif
+  ${INPUTDATA}/QB_Toulouse_Ortho_PAN_WGS84.tif
   ${TEMP}/ioStreamingImageFileWriterCalculateNumberOfDivisions_SetTileDimensionTiledStreaming.tif
   SetTileDimensionTiledStreaming
-  32
+  256
   )
 
 otb_add_test(NAME ioTvStreamingImageFileWriterCalculateNumberOfDivisions_SetNumberOfDivisionsTiledStreamingS COMMAND otbImageIOTestDriver
diff --git a/Modules/IO/TestKernel/src/otbTestHelper.cxx b/Modules/IO/TestKernel/src/otbTestHelper.cxx
index dfdd2345b95d7649b02cf56091b80d7a309f7769..9c1559a7138dbd3da2f5917ee6d2fe66d4dae441 100644
--- a/Modules/IO/TestKernel/src/otbTestHelper.cxx
+++ b/Modules/IO/TestKernel/src/otbTestHelper.cxx
@@ -1941,7 +1941,7 @@ void TestHelper::DumpOGRFeature(FILE* fpOut, OGRFeature* feature, char** papszOp
               poFDefn->GetNameRef(),
               OGRFieldDefn::GetFieldTypeName(poFDefn->GetType()));
 
-      if (feature->IsFieldSet(iField)) fprintf(fpOut, "%s\n", feature->GetFieldAsString(iField));
+      if (ogr::version_proxy::IsFieldSetAndNotNull(feature, iField)) fprintf(fpOut, "%s\n", feature->GetFieldAsString(iField));
       else fprintf(fpOut, "(null)\n");
 
       }
diff --git a/Modules/IO/TestKernel/test/CMakeLists.txt b/Modules/IO/TestKernel/test/CMakeLists.txt
index d0195c9e670427a31401d46e2c06641fdf24b033..945167830db96ed3722bb8f8ad5c9851da980194 100644
--- a/Modules/IO/TestKernel/test/CMakeLists.txt
+++ b/Modules/IO/TestKernel/test/CMakeLists.txt
@@ -32,6 +32,38 @@ set(OTBTestKernelTests
 
 add_executable(otbTestKernelTestDriver ${OTBTestKernelTests})
 target_link_libraries(otbTestKernelTestDriver ${OTBTestKernel-Test_LIBRARIES})
+
+# So the story here is that -Wl,-no-needed is a default linker flag on only on Ubuntu
+# (debian or archlinux does not use this). This will exclude a lot of libraries from linking into
+# executable.
+# #ITK_LIBRARIES in a superbuild now contains the following libraries.
+# "itkdouble-conversion itksys itkvcl itknetlib itkv3p_netlib itkvnl itkvnl_algo
+# ITKVNLInstantiation ITKCommon itkNetlibSlatec ITKStatistics ITKTransform ITKLabelMap
+# ITKMesh ITKMetaIO ITKSpatialObjects ITKPath ITKQuadEdgeMesh ITKIOImageBase ITKOptimizers
+# ITKPolynomials ITKBiasCorrection ITKFFT ITKKLMRegionGrowing ITKOptimizersv4 ITKWatersheds"
+
+# OTBITK module will find all of these components in Modules/ThirdParty/ITK/otb-module-init.cmake
+# But due to default -Wl,-as-needed flag many of them are ignored.
+# see the documentation of GNU ld -as-needed for details on this behaviour.
+
+# Our problem is that we need these ignored ones in the some header-only modules.
+# Eg: Modules/Core/LabelMap
+# This module depends on ITKLabelMap but does not link with it as it doesn't create any module (lib, exe)
+# All it use is a couple of headers from ITKLabelMap. So removing that dependency is out of question.
+
+# At this point, possible solution are follows:
+# 1. use -Wl,-as-no-needed to CMAKE_LINKER FLAGS and be done with it. (all executable contains many used libs)
+# 2. glob all libITK*, libitk* in the package script. (ugly and I don't agree)
+# 3. make a dummy executable and link that with all of OTB libs and use -Wl,-no-as-needed in that
+# 4. pick one of the random test executable and only add -Wl,-no-as-needed to it. (still a hack)
+# ..
+# ...
+# RK: I finally decided to go with 4th option.
+# Take an existing test executable otbTestKernelTestDriver and force -Wl,-no-as-needed.
+if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+  set_target_properties(otbTestKernelTestDriver PROPERTIES LINK_FLAGS "-Wl,-no-as-needed")
+endif()
+
 otb_module_target_label(otbTestKernelTestDriver)
 otb_add_test(NAME tsTvCompareAscii2 COMMAND otbTestKernelTestDriver
   --compare-ascii ${NOTOL}
diff --git a/Modules/Learning/LearningBase/include/otbMachineLearningModel.h b/Modules/Learning/LearningBase/include/otbMachineLearningModel.h
index c5fb59f28c9fa5931351921309b5ac35cbf46b48..552880cb9a83a4e43b7e29ae75689613633e5ef0 100644
--- a/Modules/Learning/LearningBase/include/otbMachineLearningModel.h
+++ b/Modules/Learning/LearningBase/include/otbMachineLearningModel.h
@@ -22,8 +22,8 @@
 #define otbMachineLearningModel_h
 
 #include "itkObject.h"
-#include "itkVariableLengthVector.h"
 #include "itkListSample.h"
+#include "otbMachineLearningModelTraits.h"
 
 namespace otb
 {
@@ -66,6 +66,7 @@ namespace otb
  *
  * \ingroup OTBLearningBase
  */
+
 template <class TInputValue, class TTargetValue, class TConfidenceValue = double >
 class ITK_EXPORT MachineLearningModel
   : public itk::Object
@@ -81,22 +82,22 @@ public:
 
   /**\name Input related typedefs */
   //@{
-  typedef TInputValue                                   InputValueType;
-  typedef itk::VariableLengthVector<InputValueType>     InputSampleType;
-  typedef itk::Statistics::ListSample<InputSampleType>  InputListSampleType;
+  typedef typename MLMSampleTraits<TInputValue>::ValueType  InputValueType;
+  typedef typename MLMSampleTraits<TInputValue>::SampleType InputSampleType;
+  typedef itk::Statistics::ListSample<InputSampleType>      InputListSampleType;
   //@}
 
   /**\name Target related typedefs */
   //@{
-  typedef TTargetValue                                  TargetValueType;
-  typedef itk::FixedArray<TargetValueType,1>            TargetSampleType;
-  typedef itk::Statistics::ListSample<TargetSampleType> TargetListSampleType;
+  typedef typename MLMTargetTraits<TTargetValue>::ValueType  TargetValueType;
+  typedef typename MLMTargetTraits<TTargetValue>::SampleType TargetSampleType;
+  typedef itk::Statistics::ListSample<TargetSampleType>      TargetListSampleType;
   //@}
 
   /**\name Confidence value typedef */
-  typedef TConfidenceValue                                  ConfidenceValueType;
-  typedef itk::FixedArray<ConfidenceValueType,1>            ConfidenceSampleType;
-  typedef itk::Statistics::ListSample<ConfidenceSampleType> ConfidenceListSampleType;
+  typedef typename MLMTargetTraits<TConfidenceValue>::ValueType  ConfidenceValueType;
+  typedef typename MLMTargetTraits<TConfidenceValue>::SampleType ConfidenceSampleType;
+  typedef itk::Statistics::ListSample<ConfidenceSampleType>      ConfidenceListSampleType;
 
   /**\name Standard macros */
   //@{
diff --git a/Modules/Learning/LearningBase/include/otbMachineLearningModelTraits.h b/Modules/Learning/LearningBase/include/otbMachineLearningModelTraits.h
new file mode 100644
index 0000000000000000000000000000000000000000..e9bc4cec29b9b3b45891e0265d63009bff34b76e
--- /dev/null
+++ b/Modules/Learning/LearningBase/include/otbMachineLearningModelTraits.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+ *
+ * This file is part of Orfeo Toolbox
+ *
+ *     https://www.orfeo-toolbox.org/
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef otbMachineLearningModelTraits_h
+#define otbMachineLearningModelTraits_h
+
+
+#include "itkVariableLengthVector.h"
+#include "itkFixedArray.h"
+#include "itkIsNumber.h"
+#include "itkMetaProgrammingLibrary.h"
+
+namespace otb
+{
+
+/**
+ * This is the struct defining the sample implementation for
+ * MachineLearningModel. It offers two type definitions: SampleType
+ * and ValueType.
+ *
+ * \tparam TInput : input sample type (can be either a scalar type or
+ * a VariableLenghtVector
+ * \tparam isNumber either TrueType or FalseType for partial
+ * specialization
+  
+ */
+template <typename TInput, typename isNumber> struct MLMSampleTraitsImpl;
+
+
+/// \cond SPECIALIZATION_IMPLEMENTATION
+// For Numbers
+template <typename TInput> struct MLMSampleTraitsImpl<TInput, itk::mpl::TrueType> {
+  typedef TInput                             ValueType;
+   typedef itk::VariableLengthVector<TInput> SampleType;
+};
+
+// For Vectors
+template <typename TInput> struct MLMSampleTraitsImpl<TInput, itk::mpl::FalseType> {
+  typedef typename TInput::ValueType        ValueType;
+  typedef TInput                            SampleType;
+};
+/// \endcond
+
+/**
+ * Simplified implementation of SampleTraits using MLMSampleTraitsImpl
+ */
+template <typename TInput> using MLMSampleTraits = MLMSampleTraitsImpl< TInput, typename itk::mpl::IsNumber<TInput>::Type >;
+
+
+/**
+ * This is the struct defining the sample implementation for
+ * MachineLearningModel. It offers two type definitions: TargetType
+ * and ValueType.
+ *
+ * \tparam TInput : input sample type (can be either a scalar type or
+ * a VariableLenghtVector or a FixedArray
+ * \tparam isNumber either TrueType or FalseType for partial
+ * specialization
+  
+ */
+template <typename TInput, typename isNumber> struct MLMTargetTraitsImpl;
+
+
+/// \cond SPECIALIZATION_IMPLEMENTATION
+// For Numbers
+template <typename TInput> struct MLMTargetTraitsImpl<TInput, itk::mpl::TrueType> {
+  typedef TInput                             ValueType;
+  typedef itk::FixedArray<TInput,1>          SampleType;
+};
+
+// For Vectors
+template <typename TInput> struct MLMTargetTraitsImpl<TInput, itk::mpl::FalseType> {
+  typedef typename TInput::ValueType        ValueType;
+  typedef TInput                            SampleType;
+};
+/// \endcond
+
+/**
+ * Simplified implementation of TargetTraits using MLMTargetTraitsImpl
+ */
+template <typename TInput> using MLMTargetTraits = MLMTargetTraitsImpl< TInput, typename itk::mpl::IsNumber<TInput>::Type >;
+
+
+} // End namespace otb
+
+#endif
diff --git a/Modules/Learning/LearningBase/test/CMakeLists.txt b/Modules/Learning/LearningBase/test/CMakeLists.txt
index 74a67d44dddd939201c134f28be152281b85a7a2..d1d16c3e65801e606c6e6903538b65264a4483a6 100644
--- a/Modules/Learning/LearningBase/test/CMakeLists.txt
+++ b/Modules/Learning/LearningBase/test/CMakeLists.txt
@@ -29,6 +29,7 @@ otbDecisionTreeWithRealValues.cxx
 otbSEMClassifierNew.cxx
 otbDecisionTreeNew.cxx
 otbKMeansImageClassificationFilterNew.cxx
+otbMachineLearningModelTemplates.cxx
 )
 
 add_executable(otbLearningBaseTestDriver ${OTBLearningBaseTests})
diff --git a/Modules/Learning/LearningBase/test/otbMachineLearningModelTemplates.cxx b/Modules/Learning/LearningBase/test/otbMachineLearningModelTemplates.cxx
new file mode 100644
index 0000000000000000000000000000000000000000..96d35e014394d6b0d6836a90ddcbf3a2303db4bf
--- /dev/null
+++ b/Modules/Learning/LearningBase/test/otbMachineLearningModelTemplates.cxx
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+ *
+ * This file is part of Orfeo Toolbox
+ *
+ *     https://www.orfeo-toolbox.org/
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <otbMachineLearningModel.h>
+
+typedef otb::MachineLearningModel<float,short>          MachineLearningModelType1;
+typedef MachineLearningModelType1::InputValueType       InputValueType1;
+typedef MachineLearningModelType1::InputSampleType      InputSampleType1;
+typedef MachineLearningModelType1::InputListSampleType  InputListSampleType1;
+typedef MachineLearningModelType1::TargetValueType      TargetValueType1;
+typedef MachineLearningModelType1::TargetSampleType     TargetSampleType1;
+typedef MachineLearningModelType1::TargetListSampleType TargetListSampleType1;
+
+typedef otb::MachineLearningModel<float,itk::VariableLengthVector<double> > MachineLearningModelType2;
+typedef MachineLearningModelType2::InputValueType       InputValueType2;
+typedef MachineLearningModelType2::InputSampleType      InputSampleType2;
+typedef MachineLearningModelType2::InputListSampleType  InputListSampleType2;
+typedef MachineLearningModelType2::TargetValueType      TargetValueType2;
+typedef MachineLearningModelType2::TargetSampleType     TargetSampleType2;
+typedef MachineLearningModelType2::TargetListSampleType TargetListSampleType2;
+
+
+
diff --git a/Modules/Learning/Sampling/include/otbImageSampleExtractorFilter.txx b/Modules/Learning/Sampling/include/otbImageSampleExtractorFilter.txx
index 8e3850392e50d3cf6ca64eae74d49d4e1dd0133c..d5faa1064cb5c5a589dba2d64f5909d07007ff24 100644
--- a/Modules/Learning/Sampling/include/otbImageSampleExtractorFilter.txx
+++ b/Modules/Learning/Sampling/include/otbImageSampleExtractorFilter.txx
@@ -175,6 +175,7 @@ PersistentImageSampleExtractorFilter<TInputImage>
   IndexType imgIndex;
   PixelType imgPixel;
   double imgComp;
+
   ogr::Layer::const_iterator featIt = layerForThread.begin();
   for(; featIt!=layerForThread.end(); ++featIt)
     {
diff --git a/Modules/Remote/Mosaic.remote.cmake b/Modules/Remote/Mosaic.remote.cmake
index adfa72d32c7efb2f6171a63b2110352a0f141774..c6f4a068dfbc4a348c9ca7bd1370a02682353100 100644
--- a/Modules/Remote/Mosaic.remote.cmake
+++ b/Modules/Remote/Mosaic.remote.cmake
@@ -5,5 +5,5 @@ A more detailed description can be found on the project website:
 https://github.com/remicres/otb-mosaic
 "
   GIT_REPOSITORY https://github.com/remicres/otb-mosaic.git
-  GIT_TAG 516dfa7e7b91aa0263e495ee6b3878a03ced9173
+  GIT_TAG master
 )
diff --git a/Modules/Remote/SertitObject.remote.cmake b/Modules/Remote/SertitObject.remote.cmake
index 429896f222016846533a6270a059804ec4143285..e424926127c501f9886aeb0d0efbd11561dfb24d 100644
--- a/Modules/Remote/SertitObject.remote.cmake
+++ b/Modules/Remote/SertitObject.remote.cmake
@@ -26,5 +26,5 @@ median, variance, kurtosis, skewness. The result could be use to perform further
 object-oriented image analysis.
 "
   GIT_REPOSITORY https://github.com/sertit/SertitObject.git
-  GIT_TAG 9088356af5835e0a8de9946bd508735f3e55cb83
+  GIT_TAG 49b6540c774ddb7c2d56e39f6f118c4dfb9b8bd3
 )
diff --git a/Modules/ThirdParty/GeoTIFF/otb-module.cmake b/Modules/ThirdParty/GeoTIFF/otb-module.cmake
index 0f331ec1574388189090987f879cea0e05cef9ab..8fbc7b52481a0374426fbede32743bae1da7b6d4 100644
--- a/Modules/ThirdParty/GeoTIFF/otb-module.cmake
+++ b/Modules/ThirdParty/GeoTIFF/otb-module.cmake
@@ -27,4 +27,6 @@ otb_module(OTBGeoTIFF
     
   DESCRIPTION
     "${DOCUMENTATION}"
+
+  EXCLUDE_FROM_DEFAULT
   )
diff --git a/Modules/ThirdParty/OpenCV/CMakeLists.txt b/Modules/ThirdParty/OpenCV/CMakeLists.txt
index 224f7318f21b3db89e7fb3848f8658727102bef3..e6b73b5096c68ac822737f74298ba491cd390d6d 100644
--- a/Modules/ThirdParty/OpenCV/CMakeLists.txt
+++ b/Modules/ThirdParty/OpenCV/CMakeLists.txt
@@ -27,7 +27,5 @@ set(OTBOpenCV_LIBRARIES "${OPENCV_LIBRARIES}")
 set(OTBOpenCV_INCLUDE_DIRS
   ${OTBOpenCV_BINARY_DIR}/src
   )
-set(OTBOpenCV_EXPORT_CODE_BUILD "find_package(OpenCV REQUIRED)")
-set(OTBOpenCV_EXPORT_CODE_INSTALL ${OTBOpenCV_EXPORT_CODE_BUILD})
 
 otb_module_impl()
diff --git a/Modules/ThirdParty/OpenGL/CMakeLists.txt b/Modules/ThirdParty/OpenGL/CMakeLists.txt
index cfbdd8cbfe568598f93eb4eef577f2f2cc635b30..99ab638244cb409a0a60c4d43706906777c12d97 100644
--- a/Modules/ThirdParty/OpenGL/CMakeLists.txt
+++ b/Modules/ThirdParty/OpenGL/CMakeLists.txt
@@ -23,5 +23,12 @@ set(OTBOpenGL_THIRD_PARTY 1)
 
 set(OTBOpenGL_SYSTEM_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR})
 set(OTBOpenGL_LIBRARIES ${OPENGL_LIBRARIES})
+set(OTBOpenGL_EXPORT_CODE_INSTALL "
+set(OTBOpenGL_LIBRARIES)
+set(OTBOpenGL_INCLUDE_DIRS)
+find_package(OpenGL REQUIRED)
+set(OTBOpenGL_LIBRARIES \${OPENGL_LIBRARIES})
+set(OTBOpenGL_SYSTEM_INCLUDE_DIRS \${OPENGL_INCLUDE_DIR})
+")
 
 otb_module_impl()
diff --git a/Modules/ThirdParty/Qt4/otb-module-init.cmake b/Modules/ThirdParty/Qt4/otb-module-init.cmake
index d121d0689fec2907c69d87a76512fe176b18b351..951a96171c3e9701d6556c8ddfe8b013248960a5 100644
--- a/Modules/ThirdParty/Qt4/otb-module-init.cmake
+++ b/Modules/ThirdParty/Qt4/otb-module-init.cmake
@@ -18,7 +18,7 @@
 # limitations under the License.
 #
 
-find_package( Qt4 REQUIRED QtCore QtGui QtOpenGL QtXml )
+find_package( Qt4 REQUIRED QtCore QtGui QtOpenGL) # QtXml )
 mark_as_advanced( QT_QMAKE_EXECUTABLE )
-set( QT_USE_QTXML 1 )
+#set( QT_USE_QTXML 1 )
 include( ${QT_USE_FILE} )
diff --git a/Modules/ThirdParty/SPTW/otb-module.cmake b/Modules/ThirdParty/SPTW/otb-module.cmake
index eca0cb9b79963f110975bbe003094cf5f72720a1..a1dc674bd5b571e9beaa2d67929291914236b3be 100644
--- a/Modules/ThirdParty/SPTW/otb-module.cmake
+++ b/Modules/ThirdParty/SPTW/otb-module.cmake
@@ -24,6 +24,7 @@ otb_module(OTBSPTW
   DEPENDS
     OTBMPI
     OTBGDAL
+    OTBTIFF
 
   TEST_DEPENDS
 
diff --git a/Modules/ThirdParty/SPTW/src/CMakeLists.txt b/Modules/ThirdParty/SPTW/src/CMakeLists.txt
index 5e0feb3b3564cce128322633b60a77aab1107512..fcc9539ece8e4d8f92e11a6edde50ebbbdb73b00 100644
--- a/Modules/ThirdParty/SPTW/src/CMakeLists.txt
+++ b/Modules/ThirdParty/SPTW/src/CMakeLists.txt
@@ -28,7 +28,11 @@ set(OTBSPTW_MAIN_SRCS sptw.cc)
 
 
 add_library(otbSPTW ${OTBSPTW_MAIN_SRCS})
-target_link_libraries(otbSPTW)
+target_link_libraries(otbSPTW
+  ${OTBMPI_LIBRARIES}
+  ${OTBGDAL_LIBRARIES}
+  ${OTBTIFF_LIBRARIES}
+  )
 include_directories(${CMAKE_CURRENT_SOURCE_DIR})
 
 #Install TARGET & FILES for otb-lib
diff --git a/Modules/ThirdParty/SiftFast/src/CMakeLists.txt b/Modules/ThirdParty/SiftFast/src/CMakeLists.txt
index d96230c769a1286c55d4e6e9fe8390de445b53cd..2c6dc502edfb4c1e5c4df806b7db366c2d55e4de 100644
--- a/Modules/ThirdParty/SiftFast/src/CMakeLists.txt
+++ b/Modules/ThirdParty/SiftFast/src/CMakeLists.txt
@@ -51,12 +51,8 @@ if( CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX )
             message(FATAL_ERROR "Impossible to compile libsiftfast. Contact OTB development team")
         endif()
         set(OTB_DISABLE_FAST_FUNCTIONS_VALUE 1)
-    else()
-        message(STATUS "Try to compile libsiftfast.cpp done.")
     endif()
 
-  set(CMAKE_CXX_FLAGS_RELEASE "-O3 -g")
-  add_definitions(" -Wall -fPIC ")
 
   # check for x86-64 system
   check_cxx_source_runs("
@@ -72,120 +68,30 @@ if( CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX )
     return 0;
   }"
   IS_X86_64)
-
-  if( IS_X86_64 )
-    add_definitions("-D__x86_64__")
-  endif()
 else()
   set(IS_X86_64 0)
 endif()
 
-if(OTB_DISABLE_FAST_FUNCTIONS_VALUE)
-    add_definitions(-DOTB_DISABLE_FAST_FUNCTIONS)
-endif()
-
-
-include(CheckIncludeFile)
-include(CheckLibraryExists)
-include(CheckCXXSourceRuns)
-include(CheckCXXCompilerFlag)
-
-# if( UNIX OR CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX )
-#   set(STDC_LIBRARY stdc++)
-# else()
-#   set(STDC_LIBRARY)
-# endif()
+#set(CMAKE_CXX_FLAGS_RELEASE "-O3 -g")
+#add_xxdefinitions(" -Wall -fPIC ")
 
-# check for SSE extensions
+add_library(otbsiftfast libsiftfast.cpp)
 if( CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX )
-  set(SSE_FLAGS)
-
-  set(CMAKE_REQUIRED_FLAGS "-msse2")
-  check_cxx_source_runs("
-    #include <emmintrin.h>
-
-    int main()
-    {
-        __m128d a, b;
-        double vals[2] = {0};
-        a = _mm_loadu_pd(vals);
-        b = _mm_add_pd(a,a);
-        _mm_storeu_pd(vals,b);
-        return 0;
-     }"
-     HAS_SSE2_EXTENSIONS)
-
-  set(CMAKE_REQUIRED_FLAGS "-msse")
-  check_cxx_source_runs("
-    #include <xmmintrin.h>
-    int main()
-    {
-        __m128 a, b;
-        float vals[4] = {0};
-        a = _mm_loadu_ps(vals);
-        b = a;
-        b = _mm_add_ps(a,b);
-        _mm_storeu_ps(vals,b);
-        return 0;
-    }"
-    HAS_SSE_EXTENSIONS)
-
-  set(CMAKE_REQUIRED_FLAGS)
-
-  if(HAS_SSE2_EXTENSIONS)
-    message(STATUS "Using SSE2 extensions")
-    set(SSE_FLAGS "-msse2 -mfpmath=sse")
-  elseif(HAS_SSE_EXTENSIONS)
-    message(STATUS "Using SSE extensions")
-    set(SSE_FLAGS "-msse -mfpmath=sse")
-  endif()
-
-  add_definitions(${SSE_FLAGS})
-elseif(MSVC)
-    if(CMAKE_SIZEOF_VOID_P EQUAL 8)
-      message(STATUS "Not using SSE2 extensions on x64")
-    else()
-      check_cxx_source_runs("
-       #include <emmintrin.h>
-       
-        int main()
-        {
-          __m128d a, b;
-          double vals[2] = {0};
-          a = _mm_loadu_pd(vals);
-          b = _mm_add_pd(a,a);
-          _mm_storeu_pd(vals,b);
-          return 0;
-        }"
-      HAS_SSE2_EXTENSIONS)
-     
-      if( HAS_SSE2_EXTENSIONS )
-        message(STATUS "Using SSE2 extensions")
-        add_definitions( "/arch:SSE2 /fp:fast -D__SSE__ -D__SSE2__" )
-      endif()
-    endif()
+  #  target_link_libraries(otbsiftfast m stdc++)
+  target_link_libraries(otbsiftfast m)
 endif()
 
-#set(Boost_ADDITIONAL_VERSIONS "1.40" "1.39" "1.38" "1.37.0" "1.37" "1.35.0" "1.34.1" "1.34.0" "1.34" "1.33.1" "1.33.0" "1.33")
-#if( NOT $ENV{BOOST_INCLUDEDIR} STREQUAL "" )
-#  set(Boost_INCLUDE_DIR $ENV{BOOST_INCLUDEDIR})
-#endif()
-#if( NOT $ENV{BOOST_LIBRARYDIR} STREQUAL "" )
-#  set(Boost_LIBRARY_DIRS $ENV{BOOST_LIBRARYDIR})
-#endif()
-#find_package(Boost COMPONENTS python)
-
-#if( Boost_FOUND )
-#  message(STATUS "found boost version: ${Boost_VERSION}")
-#else()
-#  message(STATUS "Could not find boost libraries!")
-#endif()
 
-add_library(otbsiftfast libsiftfast.cpp)
+if(IS_X86_64)
+  set_target_properties(otbsiftfast
+    PROPERTIES COMPILE_FLAGS "-D__x86_64__")
+endif()
 
-if( CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX )
-#  target_link_libraries(otbsiftfast m stdc++)
-  target_link_libraries(otbsiftfast m)
+#set_source_files_properties(<file> PROPERTIES COMPILE_FLAGS <flags>)
+
+if(OTB_DISABLE_FAST_FUNCTIONS_VALUE)
+  set_target_properties(otbsiftfast
+    PROPERTIES COMPILE_FLAGS "-DOTB_DISABLE_FAST_FUNCTIONS")
 endif()
 
 #set_target_properties(otbsiftfast PROPERTIES OUTPUT_NAME  siftfast CLEAN_DIRECT_OUTPUT 1)
@@ -195,20 +101,9 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR})
 #set_target_properties(siftfast PROPERTIES COMPILE_FLAGS "-DDVPROFILE")
 #target_link_libraries(siftfast libsiftfast)
 
-# check for OpenMP
-find_package(OpenMP)
-if(OPENMP_FOUND)
-  message(STATUS "Enabling OpenMP support")
-  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
-  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
-else()
-  message(STATUS "Disabling OpenMP support")
-endif()
-
 #Install TARGET & FILES for otb-lib
 if(OTB_LIBRARY_PROPERTIES)
-  set_target_properties(otbsiftfast PROPERTIES ${OTB_LIBRARY_PROPERTIES})
+  set_target_properties(otbsiftfast PROPERTIES ${OTB_LIBRARY_PROPERTIES}) 
 endif()
 
 install(TARGETS otbsiftfast
diff --git a/Modules/ThirdParty/TIFF/CMakeLists.txt b/Modules/ThirdParty/TIFF/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d3cb2a3a7b53cb2896ad1509c90e7f3195305398
--- /dev/null
+++ b/Modules/ThirdParty/TIFF/CMakeLists.txt
@@ -0,0 +1,26 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+project(OTBTIFF)
+
+set(OTBTIFF_SYSTEM_INCLUDE_DIRS ${TIFF_INCLUDE_DIRS})
+set(OTBTIFF_LIBRARIES "${TIFF_LIBRARIES}")
+
+otb_module_impl()
diff --git a/Modules/ThirdParty/TIFF/otb-module-init.cmake b/Modules/ThirdParty/TIFF/otb-module-init.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..93a99b67b9e593352f69510e69a97e91fc4abf46
--- /dev/null
+++ b/Modules/ThirdParty/TIFF/otb-module-init.cmake
@@ -0,0 +1,21 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+find_package ( TIFF REQUIRED )
diff --git a/Modules/ThirdParty/TIFF/otb-module.cmake b/Modules/ThirdParty/TIFF/otb-module.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..a0662801804720735275fc8ef276decf750e5035
--- /dev/null
+++ b/Modules/ThirdParty/TIFF/otb-module.cmake
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+set(DOCUMENTATION "This module imports TIFF to the build system")
+
+otb_module(OTBTIFF
+  DEPENDS
+    
+  TEST_DEPENDS
+    
+  DESCRIPTION
+    "${DOCUMENTATION}"
+
+  EXCLUDE_FROM_DEFAULT
+  )
diff --git a/Modules/Wrappers/ApplicationEngine/include/otbWrapperApplication.h b/Modules/Wrappers/ApplicationEngine/include/otbWrapperApplication.h
index 3d944f931ca7f268d8b0b07389f97bf5cf289af6..aa0cdd076ad93109e8acd054fc920c4a3892304e 100644
--- a/Modules/Wrappers/ApplicationEngine/include/otbWrapperApplication.h
+++ b/Modules/Wrappers/ApplicationEngine/include/otbWrapperApplication.h
@@ -167,7 +167,7 @@ public:
   /* Get the internal application parameter specified
    *
    * WARNING: this method may disappear from the API */
-  const Parameter* GetParameterByKey(std::string parameter) const;
+  const Parameter* GetParameterByKey(std::string parameter, bool follow=true) const;
 
   /* Returns the description of a parameter */
   std::string GetParameterName(std::string paramKey);
@@ -284,8 +284,21 @@ public:
 
   void SetParameterEmpty(std::string parameter, bool value, bool hasUserValueFlag = true);
 
+  /** Checks if the application is ready to be executed. It checks that there
+   *  is no parameter missing
+   */
   bool IsApplicationReady();
 
+  /** Checks if a parameter 'key' is missing.
+   *
+   * A parameter is missing when all the following conditions are true :
+   *   - the parameter is mandatory
+   *   - the parameter has Role_Input
+   *   - the parameter is not a group
+   *   - the parameter has no value
+   *   - the parameter ancestors are mandatory or enabled.
+   */
+  bool IsParameterMissing(const std::string &key) const;
 
   /* Set an default integer value, must used in the
    * DoInit when setting a value by default
@@ -695,7 +708,10 @@ public:
    */
   ComplexImagePixelType GetParameterComplexOutputImagePixelType(std::string parameter);
 
-  otb::Logger* GetLogger();
+  otb::Logger* GetLogger() const;
+
+  /** Sets the logger instance of the application (use with caution) */
+  void SetLogger(otb::Logger *logger);
 
   itk::ProcessObject* GetProgressSource() const;
 
diff --git a/Modules/Wrappers/ApplicationEngine/include/otbWrapperCompositeApplication.h b/Modules/Wrappers/ApplicationEngine/include/otbWrapperCompositeApplication.h
index 3dae3b16346ec255054ddf14c6d5cfc711fe7215..859e6a81e733f238b81e51a80bf8bf665d72d653 100644
--- a/Modules/Wrappers/ApplicationEngine/include/otbWrapperCompositeApplication.h
+++ b/Modules/Wrappers/ApplicationEngine/include/otbWrapperCompositeApplication.h
@@ -149,10 +149,6 @@ private:
 
   InternalAppContainer m_AppContainer;
 
-  itk::StdStreamLogOutput::Pointer  m_LogOutput;
-
-  std::ostringstream m_Oss;
-
   AddProcessCommandType::Pointer    m_AddProcessCommand;
 };
 
diff --git a/Modules/Wrappers/ApplicationEngine/src/otbWrapperApplication.cxx b/Modules/Wrappers/ApplicationEngine/src/otbWrapperApplication.cxx
index 7a7b45bb34e6b7b329b8ce174bd916d9a2f24c4d..178a8d55608661aa4253607f272cd54b5bddb6ad 100644
--- a/Modules/Wrappers/ApplicationEngine/src/otbWrapperApplication.cxx
+++ b/Modules/Wrappers/ApplicationEngine/src/otbWrapperApplication.cxx
@@ -36,6 +36,7 @@
 #include "otbWrapperInputProcessXMLParameter.h"
 #include "otbWrapperRAMParameter.h"
 #include "otbWrapperProxyParameter.h"
+#include "otbWrapperParameterKey.h"
 
 
 #include "otbWrapperAddProcessToWatchEvent.h"
@@ -74,11 +75,19 @@ Application::~Application()
 {
 }
 
-otb::Logger* Application::GetLogger()
+otb::Logger* Application::GetLogger() const
 {
   return m_Logger;
 }
 
+void Application::SetLogger(otb::Logger *logger)
+{
+  if (m_Logger != logger)
+    {
+    m_Logger = logger;
+    }
+}
+
 std::vector<std::string>
 Application::GetParametersKeys(bool recursive)
 {
@@ -297,11 +306,11 @@ void Application::SetParameterUserValue(std::string paramKey, bool value)
   GetParameterByKey(paramKey)->SetUserValue(value);
 }
 
-const Parameter* Application::GetParameterByKey(std::string name) const
+const Parameter* Application::GetParameterByKey(std::string name, bool follow) const
 {
   // GetParameterList is non const...
   Application* _this = const_cast<Application*>(this);
-  return _this->GetParameterByKey(name);
+  return _this->GetParameterByKey(name,follow);
 }
 
 void Application::Init()
@@ -1599,57 +1608,50 @@ Application::IsApplicationReady()
        it != paramList.end();
        ++it)
     {
-    // Check all Input Parameters with Input Role
-    if (GetParameterByKey(*it)->GetRole() == Role_Input)
+    // Check all parameters
+    if (IsParameterMissing(*it))
       {
-      // When a parameter is mandatory :
-      // return false when does not have value and:
-      //  - The param is root
-      //  - The param is not root and belonging to a Mandatory Group
-      //    which is activated
-      if ( !this->HasValue(*it)  && IsMandatory(*it) )
-        {
-        if( GetParameterByKey(*it)->IsRoot() )
-          {
-          otbDebugMacro("MISSING : "<< (*it).c_str() << " ( Is Root)");
-          return false;
-          }
-        else
-          {
-          // check if the parameter is linked to a root parameter with a chain of active parameters
-          Parameter* currentParam = GetParameterByKey(*it)->GetRoot();
-          if (currentParam->IsRoot())
-            {
-            otbDebugMacro("MISSING : "<< (*it).c_str() << " ( Is Level 1)");
-            return false;
-            }
-
-          int level = 1;
-
-          while (!currentParam->IsRoot())
-            {
-            if (!currentParam->GetActive())
-              {
-              // the missing parameter is not on an active branch : we can ignore it
-              break;
-              }
-            currentParam = currentParam->GetRoot();
-
-            level++;
+      ready = false;
+      break;
+      }
+    }
+  return ready;
+}
 
-            if (currentParam->IsRoot())
-              {
-              // the missing parameter is on an active branch : we need it
-              otbDebugMacro("MISSING : "<< (*it).c_str() << " ( Is Level "<< level<<")");
-              return false;
-              }
-            }
-          }
+bool
+Application::IsParameterMissing(const std::string &key) const
+{
+  bool ret(false);
+  const Parameter* param = GetParameterByKey(key);
+  if (param->GetRole() == Role_Input &&
+      GetParameterType(key) != ParameterType_Group &&
+      param->GetMandatory() &&
+      !param->HasValue())
+    {
+    ret = true;
+    ParameterKey paramKey(key);
+    std::vector<std::string> split = paramKey.Split();
+    std::string currentRoot(key);
+    unsigned int level = 1;
+    while (level < split.size())
+      {
+      currentRoot.resize(currentRoot.find_last_of("."));
+      param = GetParameterByKey(currentRoot);
+      if (!param->GetActive() && !param->GetMandatory())
+        {
+        // the missing parameter is not on an active branch : we can ignore it
+        ret = false;
+        break;
         }
+      level++;
+      }
+    if (ret)
+      {
+      // the missing parameter is on an active branch : we need it
+      otbDebugMacro("MISSING : "<< key << " (Level "<< split.size()<<")");
       }
     }
-
-  return ready;
+  return ret;
 }
 
 void
diff --git a/Modules/Wrappers/ApplicationEngine/src/otbWrapperChoiceParameter.cxx b/Modules/Wrappers/ApplicationEngine/src/otbWrapperChoiceParameter.cxx
index 1ebb88d529cb5648416a466f98dc4a1dec8ec527..2f64625f58a08987b4db3c4940c8d1b978d2e3f6 100644
--- a/Modules/Wrappers/ApplicationEngine/src/otbWrapperChoiceParameter.cxx
+++ b/Modules/Wrappers/ApplicationEngine/src/otbWrapperChoiceParameter.cxx
@@ -44,7 +44,7 @@ ChoiceParameter::AddChoice( std::string choicekey, std::string choiceName )
   choice.m_AssociatedParameter->SetName(choiceName);
   choice.m_AssociatedParameter->SetRoot(this);
   choice.m_AssociatedParameter->SetKey(choicekey);
-  
+  choice.m_AssociatedParameter->SetMandatory(false);
   m_ChoiceList.push_back(choice);
 
   // check if the new choice matches the m_CurrentChoice : if so the group should be active.
diff --git a/Modules/Wrappers/ApplicationEngine/src/otbWrapperCompositeApplication.cxx b/Modules/Wrappers/ApplicationEngine/src/otbWrapperCompositeApplication.cxx
index 741bcb03974feef556c01fd1be194be907d3bf40..db216594f54992949895a4158aadc5e3137f15eb 100644
--- a/Modules/Wrappers/ApplicationEngine/src/otbWrapperCompositeApplication.cxx
+++ b/Modules/Wrappers/ApplicationEngine/src/otbWrapperCompositeApplication.cxx
@@ -32,8 +32,6 @@ namespace Wrapper
 
 CompositeApplication::CompositeApplication()
 {
-  m_LogOutput = itk::StdStreamLogOutput::New();
-  m_LogOutput->SetStream(m_Oss);
   m_AddProcessCommand = AddProcessCommandType::New();
   m_AddProcessCommand->SetCallbackFunction(this, &CompositeApplication::LinkWatchers);
 }
@@ -65,8 +63,7 @@ CompositeApplication
   container.App = ApplicationRegistry::CreateApplication(appType);
   container.Desc = desc;
   // Setup logger
-  container.App->GetLogger()->AddLogOutput(m_LogOutput);
-  container.App->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
+  container.App->SetLogger(this->GetLogger());
   container.App->AddObserver(AddProcessToWatchEvent(), m_AddProcessCommand.GetPointer());
   m_AppContainer[key] = container;
   return true;
@@ -179,40 +176,14 @@ CompositeApplication
 ::ExecuteInternal(std::string key)
 {
   otbAppLogINFO(<< GetInternalAppDescription(key) <<"...");
-  try
-    {
-    GetInternalApplication(key)->Execute();
-    }
-  catch(...)
-    {
-    this->GetLogger()->Write( itk::LoggerBase::FATAL, std::string("\n") + m_Oss.str() );
-    throw;
-    }
-  if(!m_Oss.str().empty())
-    {
-    otbAppLogINFO(<< "\n" << m_Oss.str());
-    m_Oss.str(std::string(""));
-    }
+  GetInternalApplication(key)->Execute();
 }
 
 void
 CompositeApplication
 ::UpdateInternalParameters(std::string key)
 {
-  try
-    {
-    GetInternalApplication(key)->UpdateParameters();
-    }
-  catch(...)
-    {
-    this->GetLogger()->Write( itk::LoggerBase::FATAL, std::string("\n") + m_Oss.str() );
-    throw;
-    }
-  if(!m_Oss.str().empty())
-    {
-    otbAppLogINFO(<< "\n" << m_Oss.str());
-    m_Oss.str(std::string(""));
-    }
+  GetInternalApplication(key)->UpdateParameters();
 }
 
 } // end namespace Wrapper
diff --git a/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx b/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx
index 686d4d58cf65f248024accc8ad306cda13d73e4a..736ad395b5255f46e4ff29d725bbeb64f38f5e36 100644
--- a/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx
+++ b/Modules/Wrappers/CommandLine/src/otbWrapperCommandLineLauncher.cxx
@@ -582,99 +582,23 @@ CommandLineLauncher::ParamResultType CommandLineLauncher::LoadParameters()
   for (unsigned int i = 0; i < appKeyList.size(); i++)
     {
     const std::string paramKey(appKeyList[i]);
-    Parameter::Pointer param = m_Application->GetParameterByKey(paramKey);
     ParameterType type = m_Application->GetParameterType(paramKey);
-    const bool paramExists(m_Parser->IsAttributExists(std::string("-").append(paramKey), m_VExpression));
-    std::vector<std::string> values;
-
-    // When a parameter is mandatory :
-    // it must be set if :
-    //  - The param is root
-    //  - The param is not root and belonging to a Mandatory Group
-    //    which is activated
-    bool mustBeSet = false;
-    const bool hasValue = m_Application->HasValue(paramKey);
-
-    //skip if mandatory parameters are missing because we have it already in XML
-    if(!paramInXMLExists)
-      {
-      if( param->GetMandatory() == true && param->GetRole() != Role_Output && type != ParameterType_Group)
-        {
-        // check if the parameter is linked to a root parameter with a chain of active parameters
-        if( param->IsRoot() || param->GetRoot()->IsRoot())
-          {
-          // the parameter is a root or inside a group at root level
-          mustBeSet = true;
-          }
-        else
-          {
-          Parameter* currentParam = param->GetRoot();
-          while (!currentParam->IsRoot())
-            {
-            if (!currentParam->GetActive())
-              {
-              // the missing parameter is not on an active branch : we can ignore it
-              break;
-              }
-            currentParam = currentParam->GetRoot();
-
-            if (currentParam->IsRoot())
-              {
-              // the missing parameter is on an active branch : we need it
-              mustBeSet = true;
-              }
-            }
-          }
-        }
-      }
-
-    if( mustBeSet )
-    {
-      if (!paramExists)
-      {
-        // If key doesn't exist and parameter hasn't default value set...
-        if (!hasValue)
-        {
-          std::cerr << "ERROR: Missing mandatory parameter -" << paramKey << "." << std::endl;
-          return MISSINGMANDATORYPARAMETER;
-        }
-      }
-      else
-      {
-        values = m_Parser->GetAttribut(std::string("-").append(paramKey), m_VExpression);
-        if (values.size() == 0 && !m_Application->HasValue(paramKey))
-        {
-          std::cerr << "ERROR: Missing mandatory parameter -" << paramKey << "." << std::endl;
-          return MISSINGPARAMETERVALUE;
-        }
-      }
-    }
-    // Check if non mandatory parameter have values
-    else
+    if (m_Application->IsParameterMissing(paramKey))
       {
-      if( paramExists )
-        {
-        values = m_Parser->GetAttribut(std::string("-").append(paramKey), m_VExpression);
-        if (values.size() == 0)
-          {
-          std::cerr << "ERROR: Missing non-mandatory parameter -" << paramKey << "." << std::endl;
-          return MISSINGPARAMETERVALUE;
-          }
-        }
+      std::cerr << "ERROR: Missing mandatory parameter -" << paramKey << "." << std::endl;
+      return MISSINGMANDATORYPARAMETER;
       }
 
     // Check output paths validity
-    if (hasValue)
+    if (m_Application->HasValue(paramKey) &&
+        type == ParameterType_OutputFilename)
       {
-      if (type == ParameterType_OutputFilename)
+      std::string filename = m_Application->GetParameterString(paramKey);
+      itksys::String path = itksys::SystemTools::GetFilenamePath(filename);
+      if (path!="" && !itksys::SystemTools::FileIsDirectory(path.c_str()))
         {
-        std::string filename = m_Application->GetParameterString(paramKey);
-        itksys::String path = itksys::SystemTools::GetFilenamePath(filename);
-        if (path!="" && !itksys::SystemTools::FileIsDirectory(path.c_str()))
-          {
-          std::cerr <<"ERROR: Directory doesn't exist : "<< path.c_str() << std::endl;
-          return WRONGPARAMETERVALUE;
-          }
+        std::cerr <<"ERROR: Directory doesn't exist : "<< path.c_str() << std::endl;
+        return WRONGPARAMETERVALUE;
         }
       }
     }
@@ -813,47 +737,7 @@ std::string CommandLineLauncher::DisplayParameterHelp(const Parameter::Pointer &
 
   std::ostringstream oss;
 
-  // When a parameter is mandatory :
-  // it must be set if :
-  //  - The param is root
-  //  - The param is not root and belonging to a Mandatory Group
-  //    which is activated
-  bool isMissing = false;
-  if (!m_Parser->IsAttributExists(std::string("-").append(paramKey), m_VExpression))
-    {
-    if (!m_Application->HasValue(paramKey))
-      {
-      if( param->GetMandatory() && param->GetRole() != Role_Output )
-        {
-        if( param->IsRoot() || param->GetRoot()->IsRoot())
-          {
-          // the parameter is a root or inside a group at root level
-          isMissing = true;
-          }
-        else
-          {
-          Parameter* currentParam = param->GetRoot();
-          while (!currentParam->IsRoot())
-            {
-            if (!currentParam->GetActive())
-              {
-              // the missing parameter is not on an active branch : we can ignore it
-              break;
-              }
-            currentParam = currentParam->GetRoot();
-
-            if (currentParam->IsRoot())
-              {
-              // the missing parameter is on an active branch : we need it
-              isMissing = true;
-              }
-            }
-          }
-        }
-      }
-    }
-
-  if( isMissing )
+  if( m_Application->IsParameterMissing(paramKey) )
     {
     oss << "MISSING ";
     }
diff --git a/Packaging/CMakeLists.txt b/Packaging/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..55dee29e7d807e4ddffe3e60d5a5a85bcdeba706
--- /dev/null
+++ b/Packaging/CMakeLists.txt
@@ -0,0 +1,239 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+cmake_minimum_required(VERSION 3.3.0)
+
+project(OTBPackaging)
+
+include(CMakeParseArguments)
+include(CMakeDetermineSystem)
+include(GetPrerequisites)
+include(CTest)
+
+#setting this variable prints a lot of debug information
+set(PKG_DEBUG OFF)
+#set( PKG_DEBUG 1)
+
+set(CMAKE_BUILD_TYPE    Release)
+
+#user-defined variables and option
+option(OTB_WRAP_PYTHON "include python bindings in package" ON)
+set(SUPERBUILD_BINARY_DIR "" CACHE PATH "path to superbuild binary directory")
+set(SUPERBUILD_INSTALL_DIR "" CACHE PATH "path to superbuild install directory")
+set(DOWNLOAD_LOCATION "" CACHE PATH "path to superbuild download archives")
+
+#variables based on above user-defined variables 
+set(OTB_BINARY_DIR            "${SUPERBUILD_BINARY_DIR}/OTB/build")
+set(QT_TRANSLATIONS_DIR       "${SUPERBUILD_INSTALL_DIR}/translations")
+get_filename_component(PACKAGE_OTB_SRC_DIR ${OTBPackaging_SOURCE_DIR} PATH)
+set(SUPERBUILD_SOURCE_DIR     "${PACKAGE_OTB_SRC_DIR}/SuperBuild")
+
+
+set(LINUX FALSE)
+if( "${CMAKE_SYSTEM_NAME}"  MATCHES "Linux")
+  set(LINUX TRUE)
+endif()
+
+if(OTB_WRAP_PYTHON AND NOT PYTHON_EXECUTABLE)
+  find_package(PythonInterp REQUIRED)
+endif()
+
+find_program(FILE_COMMAND NAMES  "file")
+find_program(READLINK NAMES "readlink")
+find_program(ZIP_EXECUTABLE NAMES 7z 7za)
+
+#install prefix is same as SUPERBUILD_INSTALL_DIR. could be changed later
+set(CMAKE_INSTALL_PREFIX "${SUPERBUILD_INSTALL_DIR}")
+
+#set CMAKE_MODULE_PATH to be the current source directory.
+# This will allow to include all cmake files without full path and .cmake extension!
+set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR})
+
+#include superbuild_macro for get_version()
+include(${SUPERBUILD_SOURCE_DIR}/CMake/SuperBuild_Macro.cmake)
+
+#include superbuild_macro for OTB_TARGET_SYSTEM_ARCH_IS_X64 value
+include(${PACKAGE_OTB_SRC_DIR}/CMake/OTBCheckTargetSystemArch.cmake)
+
+# get itk version from External_itk.cmake if not on mingw
+# because mxe has different version
+get_version(
+  INPUT_FILE   "${SUPERBUILD_SOURCE_DIR}/CMake/External_itk.cmake"
+  MATCH_STRINGS "SB_ITK_VERSION_MAJOR" "SB_ITK_VERSION_MINOR"
+  PREFIX PKG
+  )
+set(PKG_ITK_SB_VERSION "${PKG_SB_ITK_VERSION_MAJOR}.${PKG_SB_ITK_VERSION_MINOR}")
+
+#get version of OTB from source_dir/CMakeLists.txt
+get_version(
+  INPUT_FILE   "${PACKAGE_OTB_SRC_DIR}/CMakeLists.txt"
+  MATCH_STRINGS "OTB_VERSION_MAJOR" "OTB_VERSION_MINOR" "OTB_VERSION_PATCH"
+  PREFIX PKG
+  )
+
+set(PKG_OTB_VERSION_STRING ${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}.${PKG_OTB_VERSION_PATCH})
+
+set(PACKAGE_LONG_NAME OrfeoToolBox)
+set(NAME_SUFFIX "" CACHE STRING "extra suffix for package name")
+set(PACKAGE_NAME OTB)
+if(NAME_SUFFIX)
+  set(PACKAGE_NAME OTB${NAME_SUFFIX})
+endif()
+if(APPLE)
+  set(PACKAGE_PLATFORM_NAME "Darwin")
+elseif(WIN32)
+  set(PACKAGE_PLATFORM_NAME "win")
+elseif(LINUX)
+  set(PACKAGE_PLATFORM_NAME "Linux")
+endif()
+set(PACKAGE_ARCH "32")
+if(OTB_TARGET_SYSTEM_ARCH_IS_X64)
+set(PACKAGE_ARCH "64")
+endif()
+
+# This directory is important.
+# We stage/keep files that goes into final package in this directory
+set(PKG_STAGE_DIR ${PACKAGE_NAME}-${PKG_OTB_VERSION_STRING}-${PACKAGE_PLATFORM_NAME}${PACKAGE_ARCH})
+
+set(PATCHELF_PROGRAM "${CMAKE_BINARY_DIR}/PATCHELF/src/patchelf/src/patchelf")
+include(External_patchelf)
+
+include(PackageGlobals)
+
+# Note that MANY or ALL of function use global variables set in this CMakeLists.txt
+# The order in which the functions in these "included" files are called is only important.
+# We tried not to share variables which are created inside functions or macro. In such cases,
+# function return the value. 
+
+include(setif_value_in_list)
+include(get_variables_ending_with)
+include(clear_cmakecache_variables)
+include(check_cmake_variables)
+include(configure_loader)
+include(search_library)
+include(prepare_search_dirs)
+include(prepare_file_list)
+include(process_file_recurse)
+include(install_without_message)
+include(install_rule)
+include(isfile_symlink)
+include(detect_using_file_command)
+include(install_otbapp_wrapper_scripts)
+include(cleanup_package)
+
+# below functions include many install commands which are installing
+# files under PKG_STAGE_DIR
+include(install_include_dirs)
+include(install_importlibs)
+include(install_python_bindings)
+include(install_share_dirs)
+include(install_cmake_files)
+include(install_qtdev_files)
+include(install_vstudio_files)
+include(installer_files)
+include(create_package)
+
+configure_loader(LOADER_PROGRAM LOADER_ARGS LOADER_REGEX)
+
+
+# creation of package is different from windows and unix like
+# WE KEEP THIS VARIABLE HERE BECAUSE IT IS USED IN
+# cleanup_package, create_package, testing.cmake
+# and check_cmake_variables
+
+# THIS IS JUST TO AVOID DUPLICATION
+if(WIN32)
+  set(PACKAGE_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PKG_STAGE_DIR}.zip")
+else()
+  set(PACKAGE_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${PKG_STAGE_DIR}.run")
+endif()
+
+check_cmake_variables()
+
+cleanup_package()
+
+set(HAVE_QT4 FALSE CACHE INTERNAL "HAVE_QT4")
+if(EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/otbApplicationLauncherQt${EXE_EXT}")
+  set(HAVE_QT4 TRUE)
+endif()
+
+set(HAVE_MVD FALSE  CACHE INTERNAL "HAVE_MVD")
+if(EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/monteverdi${EXE_EXT}")
+  set(HAVE_MVD TRUE)
+endif()
+
+set(HAVE_PYTHON FALSE CACHE INTERNAL "HAVE_PYTHON")
+if(EXISTS "${SUPERBUILD_INSTALL_DIR}/lib/otb/python/_otbApplication${PYMODULE_EXT}")
+  set(HAVE_PYTHON TRUE)
+endif()
+
+  #only for *nix
+if(UNIX)
+  file(WRITE ${CMAKE_BINARY_DIR}/make_symlinks   "#!/bin/sh\n")
+endif()
+
+#remove all *_USED|*_RESOLVED variables from CMakeCache.txt
+clear_cmakecache_variables()
+
+set(PKG_SEARCHDIRS)
+prepare_search_dirs(PKG_SEARCHDIRS)
+
+set(PKG_PEFILES)
+prepare_file_list(PKG_PEFILES)
+foreach(pfile ${PKG_PEFILES})
+  get_filename_component(pfile_name ${pfile} NAME)
+  process_file_recurse(${pfile_name})
+endforeach()
+
+install_include_dirs()
+
+install_importlibs()
+
+install_python_bindings()
+
+install_share_dirs()
+
+install_cmake_files()
+
+install_qtdev_files()
+
+install_vstudio_files()
+
+installer_files()
+
+create_package()
+
+if(BUILD_TESTING)
+  enable_testing()
+  include(testing.cmake)
+endif()
+
+
+
+
+#TODO: dummy targets. to be removed after merge
+add_custom_target(
+    PACKAGE-OTB
+    COMMAND
+    "${CMAKE_COMMAND}" --build . --target install
+    WORKING_DIRECTORY
+    "${CMAKE_BINARY_DIR}"
+    COMMENT "dummy target PACKAGE-OTB"
+    )
diff --git a/Packaging/CTestConfig.cmake b/Packaging/CTestConfig.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..ac2fbdca4ec3cd622a46eceef0b8fad5c9125b87
--- /dev/null
+++ b/Packaging/CTestConfig.cmake
@@ -0,0 +1,28 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+set(CTEST_PROJECT_NAME "OTB")
+set(CTEST_NIGHTLY_START_TIME "20:00:00 CEST")
+set(CTEST_DROP_METHOD "https")
+set(CTEST_DROP_SITE "dash.orfeo-toolbox.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=OTB")
+set(CTEST_DROP_SITE_CDASH TRUE)
+set(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 4096)
+set(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 4096)
diff --git a/Packaging/External_patchelf.cmake b/Packaging/External_patchelf.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..d16876373c11f65d6763faa0836171da2539db11
--- /dev/null
+++ b/Packaging/External_patchelf.cmake
@@ -0,0 +1,61 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+set(PATCHELF_PREFIX_DIR "${CMAKE_BINARY_DIR}/PATCHELF")
+set(PATCHELF_SOURCE_DIR  "${PATCHELF_PREFIX_DIR}/src/patchelf")
+# PATCHELF_BINARY_DIR is same as PATCHELF_SOURCE_DIR
+set(PATCHELF_INSTALL_DIR "${PATCHELF_PREFIX_DIR}/install/patchelf")
+set(PATCHELF_STAMP_DIR   "${PATCHELF_PREFIX_DIR}/stamp/patchelf")
+set(PATCHELF_TMP_DIR     "${PATCHELF_PREFIX_DIR}/tmp/patchelf")
+
+if( __EXTERNAL_PATCHELF__)
+  return()
+else()
+  set(__EXTERNAL_PATCHELF__ 1)
+endif()
+
+if(WIN32 OR APPLE)
+  add_custom_target(PATCHELF)
+  return()
+endif()
+
+include(ExternalProject)
+
+set(PATCHELF_ENV_COMMAND env CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} CXXFLAGS=-static)
+
+ExternalProject_Add(PATCHELF
+  PREFIX "${PATCHELF_PREFIX_DIR}"
+  URL                 "http://nixos.org/releases/patchelf/patchelf-0.9/patchelf-0.9.tar.bz2"
+  URL_MD5             d02687629c7e1698a486a93a0d607947
+  DOWNLOAD_DIR        "${DOWNLOAD_LOCATION}"
+  SOURCE_DIR          "${PATCHELF_SOURCE_DIR}"
+  BINARY_DIR          "${PATCHELF_SOURCE_DIR}"
+  INSTALL_DIR         "${PATCHELF_INSTALL_DIR}"
+  STAMP_DIR           "${PATCHELF_STAMP_DIR}"
+  TMP_DIR             "${PATCHELF_TMP_DIR}"
+  CONFIGURE_COMMAND
+  ${PATCHELF_ENV_COMMAND}
+  ${PATCHELF_SOURCE_DIR}/configure
+  INSTALL_COMMAND ""
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
+  )
+
diff --git a/SuperBuild/Packaging/Files/Monteverdi.icns b/Packaging/Files/Monteverdi.icns
similarity index 100%
rename from SuperBuild/Packaging/Files/Monteverdi.icns
rename to Packaging/Files/Monteverdi.icns
diff --git a/Packaging/Files/OTB Project.zip b/Packaging/Files/OTB Project.zip
new file mode 100644
index 0000000000000000000000000000000000000000..5e5b6d607f59e48ffd1afbe7f624ee9af245d8cf
Binary files /dev/null and b/Packaging/Files/OTB Project.zip differ
diff --git a/Packaging/Files/build_examples.cmake b/Packaging/Files/build_examples.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..46404dd2949cc1853f0ffc19f227b6ef7b466263
--- /dev/null
+++ b/Packaging/Files/build_examples.cmake
@@ -0,0 +1,97 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+if(NOT SRC_DIR)
+  message(FATAL_ERROR "SRC_DIR is not set")
+endif()
+
+set(PKG_DIR)
+get_filename_component(PKG_DIR ${CMAKE_CURRENT_LIST_DIR} PATH)
+set(TEST_DIR ${PKG_DIR}/ex_build)
+
+if(EXISTS "${TEST_DIR}")
+  execute_process(COMMAND ${CMAKE_COMMAND} -E remove_directory ${TEST_DIR})
+  execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory   ${TEST_DIR})
+else()
+  execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory   ${TEST_DIR})
+endif()
+message("TEST_DIR=${TEST_DIR}")
+message("PKG_DIR=${PKG_DIR}")
+message("SRC_DIR=${SRC_DIR}")
+
+set(cmake_gen)
+if(WIN32)
+  set(cmake_gen "-GNinja")
+endif()
+
+execute_process(
+  COMMAND ${CMAKE_COMMAND}
+  -DCMAKE_INSTALL_PREFIX=${PKG_DIR}
+  -DCMAKE_BUILD_TYPE=RelWithDebInfo
+  ${cmake_gen}
+  ${SRC_DIR}
+  WORKING_DIRECTORY ${TEST_DIR}
+  RESULT_VARIABLE configure_rv
+  OUTPUT_VARIABLE configure_ov
+  ERROR_VARIABLE  configure_ov
+  )
+
+if( configure_rv )
+  message(FATAL_ERROR "Configure FAILED. configure_ov:\n${configure_ov}")
+  return()
+else()
+  message("Configure PASSED. configure_ov:\n${configure_ov}")
+endif()
+
+# If you want to test building a third targert, use foreach.
+# the code is written in a way that it is easy to stuff these two
+# into a cmake foreach
+execute_process(COMMAND ${CMAKE_COMMAND}
+  --build ${TEST_DIR}
+  --config RelWithDebInfo
+  --target HelloWorldOTB
+  WORKING_DIRECTORY ${TEST_DIR}
+  RESULT_VARIABLE build_HelloWorldOTB_rv
+  OUTPUT_VARIABLE build_HelloWorldOTB_ov
+  ERROR_VARIABLE  build_HelloWorldOTB_ov
+  )
+
+if( build_HelloWorldOTB_rv )
+  message(FATAL_ERROR "Build FAILED. build_HelloWorldOTB_ov:\n${build_HelloWorldOTB_ov}")
+  return()
+else()
+  message("Build PASSED. build_HelloWorldOTB_ov:\n${build_HelloWorldOTB_ov}")
+endif()
+
+execute_process(COMMAND ${CMAKE_COMMAND}
+  --build ${TEST_DIR}
+  --config RelWithDebInfo
+  --target Pipeline
+  WORKING_DIRECTORY ${TEST_DIR}
+  RESULT_VARIABLE build_Pipeline_rv
+  OUTPUT_VARIABLE build_Pipeline_ov
+  ERROR_VARIABLE  build_Pipeline_ov
+  )
+
+if( build_Pipeline_rv )
+  message(FATAL_ERROR "Build FAILED. build_Pipeline_ov=${build_Pipeline_ov}")
+  return()
+else()
+  message("Build PASSED. build_Pipeline_ov=${build_Pipeline_ov}")  
+endif()
diff --git a/Packaging/Files/linux_pkgsetup.in b/Packaging/Files/linux_pkgsetup.in
new file mode 100644
index 0000000000000000000000000000000000000000..6c56a3b976e7a54cb041a244b4f917ff073ef125
--- /dev/null
+++ b/Packaging/Files/linux_pkgsetup.in
@@ -0,0 +1,89 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+set -e
+
+DIRNAME_0=$(dirname "$0")
+cd  "$DIRNAME_0"
+
+# NOTE: $OUT_DIR is also used in make_sylinks script (see below)
+# Avoid any pre-mature optimization on variable names here.
+
+OUT_DIR=$(pwd)
+
+PATCH_ELF_EXE="$OUT_DIR/patchelf"
+
+#do not move below block. it must be before "unset LD_LIBRARY_PATH" code
+#check if we have any python bindings
+set OTB_PYTHON_LIB_PATH=
+if [ -f "$OUT_DIR/lib/python/_otbApplication.so" ] ; then
+    sed -i "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/setup_python.sh"
+    chmod +x $OUT_DIR/setup_python.sh
+    . ./setup_python.sh
+    set OTB_PYTHON_LIB_PATH=$OUT_DIR/lib/python
+fi
+
+# No no interference with LD_LIBRARY_PATH
+unset LD_LIBRARY_PATH
+
+#RK: We cannot avoid -maxdepth 1 option in find command below because,
+# there are files in $OUT_DIR/lib/gtk which we CANNOT add new rpath
+BINARY_FILES=$(find $OTB_PYTHON_LIB_PATH $OUT_DIR/lib $OUT_DIR/bin $OUT_DIR/lib/otb/applications -maxdepth 1 -type f -exec file {} \; | grep -i elf|cut -f1 -d':')
+# run patchelf
+for bin_file in $BINARY_FILES; do
+    #echo "adding rpath to $bin_file"
+    if [ -f "$bin_file" ]; then
+        "$PATCH_ELF_EXE" "--set-rpath" "$OUT_DIR/lib" "$bin_file"
+    fi
+done
+
+#install uninstall_otb script
+echo "Installing uninstall script for OTB 'tools/uninstall_otb.sh'"
+sed -i -E "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/tools/uninstall_otb.sh"
+chmod +x "$OUT_DIR/tools/uninstall_otb.sh"
+
+sed -i -E  "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/monteverdi.sh"
+chmod +x "$OUT_DIR/monteverdi.sh"
+
+sed -i -E "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/mapla.sh"
+chmod +x "$OUT_DIR/mapla.sh"
+
+sed -i -E "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/otbenv.profile"
+chmod +x "$OUT_DIR/otbenv.profile"
+
+sed -i  -E "s,../lib,$OUT_DIR/lib,g" "$OUT_DIR/bin/qt.conf"
+
+#echo "Creating symbolic links..."
+. ./make_symlinks
+
+rm -f  "$OUT_DIR/make_symlinks"
+
+printf %s\\n ""
+printf %s\\n "source './otbenv.profile' file to set required environment variables"
+printf %s\\n "eg: '. $OUT_DIR/otbenv.profile'"
+printf %s\\n "You can also copy above line to  ~/.profile to keep changes permanently!"
+printf %s\\n "More documentation can be found in $OUT_DIR/README"
+
+
+#rm -f  "$OUT_DIR/make_symlinks"
+rm -f  "$OUT_DIR/patchelf"
+rm -f  "$OUT_DIR/setup_python.sh"
+rm -f  "$OUT_DIR/pkgsetup"
+
diff --git a/Packaging/Files/macx_pkgsetup.in b/Packaging/Files/macx_pkgsetup.in
new file mode 100755
index 0000000000000000000000000000000000000000..46606ffb164881b7afe4639c42cb1ff6ce3ab519
--- /dev/null
+++ b/Packaging/Files/macx_pkgsetup.in
@@ -0,0 +1,116 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+set -e
+
+DIRNAME_0=$(dirname "$0")
+cd  "$DIRNAME_0" || exit 1
+
+# NOTE: $OUT_DIR is also used in make_sylinks script (see below)
+# Avoid any pre-mature optimization on variable names here.
+
+OUT_DIR=$(pwd)
+
+#do not move below 3 lines. it must be before "unset LD_LIBRARY_PATH" code
+sed -i "" "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/setup_python.sh"
+chmod +x $OUT_DIR/setup_python.sh
+./setup_python.sh
+
+# find install_name_tool
+INSTALL_NAME_TOOL=$(which install_name_tool)
+if [ -z "$INSTALL_NAME_TOOL" ]; then
+    echo "install_name_tool does not exists.."
+    echo "please install install_name_tool and make sure it can be found from PATH"
+    exit 1;
+fi
+
+# no interference with DYLD_LIBRARY_PATH and DYLD_FALLBACK_LIBRARY_PATH
+unset DYLD_LIBRARY_PATH
+unset DYLD_FALLBACK_LIBRARY_PATH
+
+echo "Configuring..."
+
+LIB_FILES=$(find "$OUT_DIR/lib" -type f -exec file {} \; | grep -i "Mach-O"|cut -d ':' -f1)
+BIN_FILES=$(find "$OUT_DIR/bin" -type f -exec file {} \; | grep -i "Mach-O*.*executable"|cut -d ':' -f1)
+# run install_name_tool
+for input_file in $LIB_FILES $BIN_FILES; do
+    #echo "adding rpath to $OUT_DIR/$lib_file"
+    if [ -f "$input_file" ]; then
+      input_file_old_rpaths=$(otool -l "$input_file" | grep -A 3 "LC_RPATH" | grep -oE 'path .* \(offset' | cut -d ' ' -f 2)
+      for rpath_old in $input_file_old_rpaths; do
+        $INSTALL_NAME_TOOL "-delete_rpath" "$rpath_old" "$input_file"
+      done
+      $INSTALL_NAME_TOOL "-add_rpath" "$OUT_DIR/lib" "$input_file"
+    fi
+done
+
+#install uninstall_otb script
+echo "Installing uninstall script for OTB 'tools/uninstall_otb.sh'"
+sed -i "" "s,mapla.sh,Mapla.app -r,g" "$OUT_DIR/tools/uninstall_otb.sh"
+sed -i "" "s,monteverdi.sh,Monteverdi.app -r,g" "$OUT_DIR/tools/uninstall_otb.sh"
+sed -i "" "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/tools/uninstall_otb.sh"
+chmod +x "$OUT_DIR/tools/uninstall_otb.sh"
+
+mkdir "$OUT_DIR/template.app/Contents/MacOS"
+mkdir "$OUT_DIR/template.app/Contents/Resources"
+cp -r "$OUT_DIR/template.app" "$OUT_DIR/Mapla.app"
+cp -r "$OUT_DIR/template.app" "$OUT_DIR/Monteverdi.app"
+mv "$OUT_DIR/mapla.sh" "Mapla.app/Contents/MacOS/Mapla"
+mv "$OUT_DIR/monteverdi.sh" "Monteverdi.app/Contents/MacOS/Monteverdi"
+rm -fr "template.app"
+LONG_VERSION_STRING=@Monteverdi_VERSION_MAJOR@.@Monteverdi_VERSION_MINOR@.@Monteverdi_VERSION_PATCH@
+SHORT_VERSION_STRING=@Monteverdi_VERSION_MAJOR@.@Monteverdi_VERSION_MINOR@
+#sed qt.conf
+sed -i "" "s,../lib,$OUT_DIR/lib,g" "$OUT_DIR/bin/qt.conf"
+
+cp "$OUT_DIR/bin/qt.conf" "$OUT_DIR/Mapla.app/Contents/Resources/qt.conf"
+cp "$OUT_DIR/Monteverdi.icns" "Mapla.app/Contents/Resources/"
+sed -i "" "s,STARTUP_FILE,Mapla,g" "Mapla.app/Contents/Info.plist"
+sed -i "" "s,LONG_VERSION,$LONG_VERSION_STRING,g" "Mapla.app/Contents/Info.plist"
+sed -i "" "s,SHORT_VERSION,$SHORT_VERSION_STRING,g" "Mapla.app/Contents/Info.plist"
+sed -i "" "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/Mapla.app/Contents/MacOS/Mapla"
+chmod +x "$OUT_DIR/Mapla.app/Contents/MacOS/Mapla"
+
+cp "$OUT_DIR/bin/qt.conf" "$OUT_DIR/Monteverdi.app/Contents/Resources/qt.conf"
+cp "$OUT_DIR/Monteverdi.icns" "Monteverdi.app/Contents/Resources/"
+sed -i "" "s,STARTUP_FILE,Monteverdi,g" "Monteverdi.app/Contents/Info.plist"
+sed -i "" "s,LONG_VERSION,$LONG_VERSION_STRING,g" "Monteverdi.app/Contents/Info.plist"
+sed -i "" "s,SHORT_VERSION,$SHORT_VERSION_STRING,g" "Monteverdi.app/Contents/Info.plist"
+sed -i "" "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/Monteverdi.app/Contents/MacOS/Monteverdi"
+chmod +x "$OUT_DIR/Monteverdi.app/Contents/MacOS/Monteverdi"
+
+sed -i "" "s,OUT_DIR,$OUT_DIR,g" "$OUT_DIR/otbenv.profile"
+chmod +x "$OUT_DIR/otbenv.profile"
+
+printf %s\\n ""
+printf %s\\n "source './otbenv.profile' file to set required environment variables"
+printf %s\\n "eg: '. $OUT_DIR/otbenv.profile'"
+printf %s\\n "You can also copy above line to  ~/.profile to keep changes permanently!"
+printf %s\\n "More documentation can be found in $OUT_DIR/README"
+
+
+# echo "Creating symbolic links..."
+. "./make_symlinks"
+rm -f "$OUT_DIR/make_symlinks"
+rm -f "$OUT_DIR/setup_python.sh"
+rm -f "$OUT_DIR/Monteverdi.icns"
+rm -f "$OUT_DIR/pkgsetup"
+
+#open "$OUT_DIR"
diff --git a/Packaging/Files/mapla.bat b/Packaging/Files/mapla.bat
new file mode 100644
index 0000000000000000000000000000000000000000..1823697e43c9035a7fc7ccc80ae58da9f25bbc6b
--- /dev/null
+++ b/Packaging/Files/mapla.bat
@@ -0,0 +1,38 @@
+::
+:: Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+::
+:: This file is part of Orfeo Toolbox
+::
+::   https://www.orfeo-toolbox.org/
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+::   http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+:: Mapla launcher to set up proper environment
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+@echo off
+setlocal
+
+:: Get the directory of the current script
+set CURRENT_SCRIPT_DIR=%~dp0
+
+:: Setup environment
+call "%CURRENT_SCRIPT_DIR%otbenv.bat"
+
+:: Set current dir to HOME dir because Monteverdi generates temporary files and need write access
+cd %HOMEDRIVE%%HOMEPATH%
+
+:: Start Monteverdi
+start "Monteverdi Application Launcher" /B "%CURRENT_SCRIPT_DIR%bin\mapla.exe" %*
+
+endlocal
diff --git a/Packaging/Files/mapla.sh b/Packaging/Files/mapla.sh
new file mode 100755
index 0000000000000000000000000000000000000000..1164c66963792953cd23e7079ff2820e8f702076
--- /dev/null
+++ b/Packaging/Files/mapla.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+. OUT_DIR/otbenv.profile
+
+OUT_DIR/bin/mapla "$@"
diff --git a/Packaging/Files/monteverdi.bat b/Packaging/Files/monteverdi.bat
new file mode 100644
index 0000000000000000000000000000000000000000..4ffe60380efeae6730c5da3398c3b4bec8fbbbff
--- /dev/null
+++ b/Packaging/Files/monteverdi.bat
@@ -0,0 +1,38 @@
+::
+:: Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+::
+:: This file is part of Orfeo Toolbox
+::
+::    https://www.orfeo-toolbox.org/
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+::    http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+:: Monteverdi launcher to set up proper environment
+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+@echo off
+setlocal
+
+:: Get the directory of the current script
+set CURRENT_SCRIPT_DIR=%~dp0
+
+:: Setup environment
+call "%CURRENT_SCRIPT_DIR%otbenv.bat"
+
+:: Set current dir to HOME dir because Monteverdi generates temporary files and need write access
+cd %HOMEDRIVE%%HOMEPATH%
+
+:: Start Monteverdi
+start "Monteverdi Viewer" /B "%CURRENT_SCRIPT_DIR%bin\monteverdi.exe" %*
+
+endlocal
diff --git a/Packaging/Files/monteverdi.sh b/Packaging/Files/monteverdi.sh
new file mode 100755
index 0000000000000000000000000000000000000000..6ba6a2c4e8044e40ff46206527053b7d7e598a39
--- /dev/null
+++ b/Packaging/Files/monteverdi.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+. OUT_DIR/otbenv.profile
+
+OUT_DIR/bin/monteverdi "$@"
diff --git a/SuperBuild/Packaging/Files/otb_loader.cxx b/Packaging/Files/otb_loader.cxx
similarity index 100%
rename from SuperBuild/Packaging/Files/otb_loader.cxx
rename to Packaging/Files/otb_loader.cxx
diff --git a/Packaging/Files/otbenv.bash b/Packaging/Files/otbenv.bash
new file mode 100644
index 0000000000000000000000000000000000000000..50151f649790ef8855ce9158ae6de36ea211a2c0
--- /dev/null
+++ b/Packaging/Files/otbenv.bash
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# The below environment variables only affect current shell
+# So if you run again from a terminal. you need to run the script again
+# see how this is sourced in monteverdi.sh and mapla.sh
+
+CURRENT_DIR=$(cd -P -- "$(dirname -- "$BASH_SOURCE")" && printf '%s\n' "$(pwd -P)")
+
+unset LD_LIBRARY_PATH
+
+PATH=$CURRENT_DIR/bin:$PATH
+GDAL_DATA=$CURRENT_DIR/share/data
+GEOTIFF_CSV=$CURRENT_DIR/share/epsg_csv
+PYTHONPATH=$CURRENT_DIR/lib/python:$PYTHONPATH
+OTB_APPLICATION_PATH=$CURRENT_DIR/lib/otb/applications
+GDAL_DRIVER_PATH="disable"
+LC_NUMERIC=C
+
+export PATH
+export GDAL_DATA
+export GEOTIFF_CSV
+export PYTHONPATH
+export OTB_APPLICATION_PATH
+export GDAL_DRIVER_PATH
+export LC_NUMERIC
diff --git a/Packaging/Files/otbenv.bat b/Packaging/Files/otbenv.bat
new file mode 100644
index 0000000000000000000000000000000000000000..dbc42eea3155aa222d7143e16315302ca7e91a9a
--- /dev/null
+++ b/Packaging/Files/otbenv.bat
@@ -0,0 +1,30 @@
+::
+:: Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+::
+:: This file is part of Orfeo Toolbox
+::
+::   https://www.orfeo-toolbox.org/
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+::   http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+:: Setup environment for OTB package
+set CURRENT_SCRIPT_DIR=%~dp0
+
+set PATH=%CURRENT_SCRIPT_DIR%bin;%PATH%
+set GDAL_DATA=%CURRENT_SCRIPT_DIR%share\data
+set GEOTIFF_CSV=%CURRENT_SCRIPT_DIR%share\epsg_csv
+set PYTHONPATH=%CURRENT_SCRIPT_DIR%lib\python;%PYTHONPATH%
+set OTB_APPLICATION_PATH=%CURRENT_SCRIPT_DIR%lib\otb\applications
+set GDAL_DRIVER_PATH=disable
+:: Set numeric locale to C
+set LC_NUMERIC=C
diff --git a/Packaging/Files/otbenv.profile b/Packaging/Files/otbenv.profile
new file mode 100644
index 0000000000000000000000000000000000000000..191121e411efbe133bd2a458e1fc2e9bd705e684
--- /dev/null
+++ b/Packaging/Files/otbenv.profile
@@ -0,0 +1,75 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# The below environment variables only affect current shell
+# So if you run again from a terminal. you need to run the script again
+# see how this is sourced in monteverdi.sh and mapla.sh
+
+# unset any existing LD_LIBRARY_PATH
+unset LD_LIBRARY_PATH
+
+CMAKE_PREFIX_PATH=OUT_DIR
+export CMAKE_PREFIX_PATH
+
+
+# if OTB_USE_LOCAL_GTK is set to one,
+# we must include ./lib/gtk because gtklibs are installed there. 
+# OTB_USE_LOCAL_GTK is not set by default (use GTK system)
+#This code only affect linux system. for osx OUT_DIR/lib/gtk does not exists
+if [ "$OTB_USE_LOCAL_GTK" = "1" ]; then
+    if [ -d "OUT_DIR/lib/gtk" ]; then
+	LD_LIBRARY_PATH=OUT_DIR/lib/gtk
+	export LD_LIBRARY_PATH
+    fi
+fi
+
+# check and set OTB_APPLICATION_PATH
+if [ -z "$OTB_APPLICATION_PATH" ] || [ "$OTB_APPLICATION_PATH" = "" ]; then
+    OTB_APPLICATION_PATH=OUT_DIR/lib/otb/applications
+else
+    OTB_APPLICATION_PATH=OUT_DIR/lib/otb/applications:$OTB_APPLICATION_PATH
+fi
+
+# Add bin direcotory to system PATH
+PATH=OUT_DIR/bin:$PATH
+
+# export PYTHONPATH to import otbApplication.py
+PYTHONPATH=OUT_DIR/lib/python:$PYTHONPATH
+
+# set numeric locale to C
+LC_NUMERIC=C
+
+# set GDAL_DATA variable used by otb application
+GDAL_DATA=OUT_DIR/share/gdal
+
+export GDAL_DRIVER_PATH=disable
+
+# set GEOTIFF_CSV variable used by otb application
+GEOTIFF_CSV=OUT_DIR/share/epsg_csv
+
+# export variables
+export LC_NUMERIC
+export GDAL_DATA
+export GEOTIFF_CSV
+export OTB_APPLICATION_PATH
+export PATH
+export PYTHONPATH
+
diff --git a/SuperBuild/Packaging/Files/qt.conf b/Packaging/Files/qt.conf
similarity index 100%
rename from SuperBuild/Packaging/Files/qt.conf
rename to Packaging/Files/qt.conf
diff --git a/SuperBuild/Packaging/Files/selftester.bat b/Packaging/Files/selftester.bat
similarity index 65%
rename from SuperBuild/Packaging/Files/selftester.bat
rename to Packaging/Files/selftester.bat
index 7aabc01e5e2fa305b032818ab51627dc5f48e7a3..756b3f793d5f2138a0774bc93ffba25798890879 100755
--- a/SuperBuild/Packaging/Files/selftester.bat
+++ b/Packaging/Files/selftester.bat
@@ -1,33 +1,59 @@
 @echo off
-setlocal
+::  Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+:: 
+::  This file is part of Orfeo Toolbox
+:: 
+::      https://www.orfeo-toolbox.org/
+:: 
+::  Licensed under the Apache License, Version 2.0 (the "License");
+::  you may not use this file except in compliance with the License.
+::  You may obtain a copy of the License at
+:: 
+::      http://www.apache.org/licenses/LICENSE-2.0
+:: 
+::  Unless required by applicable law or agreed to in writing, software
+::  distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+rem set EXIT_ON_ERROR=0
+rem set TEST_VERBOSE=1
+rem cmd /k tools\selftester.bat /q > selftest_report.log 2>&1
+
+set MY_TOOLS_DIR=%~dp0
+cd %MY_TOOLS_DIR%..
+set MY_INSTALL_DIR=%cd%
+echo "MY_INSTALL_DIR=%MY_INSTALL_DIR%"
+
+:: this is set in wrapper script
+::set EXIT_ON_ERROR=0
+IF %EXIT_ON_ERROR%.==. ( set EXIT_ON_ERROR=1)
+IF %TEST_VERBOSE%.==. ( set TEST_VERBOSE=1)
 
-set CURRENT_SCRIPT_DIR=%~dp0
-set DIRNAME=%CURRENT_SCRIPT_DIR%..
-cd %DIRNAME%
+echo TEST_VERBOSE=%TEST_VERBOSE%
+echo EXIT_ON_ERROR=%EXIT_ON_ERROR%
 
 :: if "/q" is given, hide the error dialogs (hence make the script non-interactive)
 if /i not -%1-==-/q- (
   goto :skip_hide_error
 )
-echo Hide error dialogs
+
+
 call :getDontShowUI
 if %DONTSHOWUI_VALUE% equ 0 call :setDontShowUI 1
 :skip_hide_error
-
+echo Hide error dialogs
 :: Get current PID
 type NUL > pid.log
 wmic PROCESS where "Name='WMIC.exe'" get ParentProcessId >pid.log 2>&1
 for /F "TOKENS=1" %%b in ('type pid.log ^| findstr [0-9]') do set CURRENT_PID=%%b
 
 :: setup the otbenv
-call otbenv.cmd
+call otbenv.bat
 
-del selftest_report.log
-type NUL > selftest_report.log
-call :nb_report_lines
-set REF_SIZE=%nb_report_lines_out%
 :: -----------------------------------------------------------------------------------
-rem Check 1 : check binaries
+REM Check 1 : check binaries
 for /R %%i in (*.dll) do (
   call :check_binary %%i
 )
@@ -36,13 +62,6 @@ for %%i in (bin\mapla.exe,bin\monteverdi.exe,bin\otbApplicationLauncherCommandLi
 )
 call :check_binary lib\python\_otbApplication.pyd
 
-call :nb_report_lines
-if %nb_report_lines_out% gtr %REF_SIZE% (
-  echo Check 1/3 : FAIL
-) else (
-  echo Check 1/3 : PASS
-)
-set REF_SIZE=%nb_report_lines_out%
 :: -----------------------------------------------------------------------------------
 rem Check 2 : check applications and Python wrapping
 set /a app_count=0
@@ -54,30 +73,17 @@ if %app_count% leq 90 (
 )
 call :check_python_wrapping
 
-call :nb_report_lines
-if %nb_report_lines_out% gtr %REF_SIZE% (
-  echo Check 2/3 : FAIL
-) else (
-  echo Check 2/3 : PASS
-)
-set REF_SIZE=%nb_report_lines_out%
 :: -----------------------------------------------------------------------------------
 rem Check 3 : check monteverdi & mapla
 call :check_desktop_app monteverdi
 call :check_desktop_app mapla 20
 
-call :nb_report_lines
-if %nb_report_lines_out% gtr %REF_SIZE% (
-  echo Check 3/3 : FAIL
-) else (
-  echo Check 3/3 : PASS
-)
-
 if /i not -%1-==-/q- (
   goto :skip_restore_error
 )
 if %DONTSHOWUI_VALUE% equ 0 call :setDontShowUI 0
 :skip_restore_error
+setlocal
 del pid.log
 del tmp.log
 endlocal
@@ -86,13 +92,14 @@ goto :eof
 ::########################[ FUNCTIONS ]##################################
 :check_binary
 setlocal
+if %TEST_VERBOSE% gtr 1 ( echo ":check_binary %1" )
 type NUL > tmp.log
-bin\otb_loader.exe %1 > tmp.log 2>&1
+tools\otb_loader.exe %1 > tmp.log 2>&1
 call :nb_tmp_lines
 if %nb_tmp_lines_out% gtr 0 (
-  echo ERROR : otb_loader.exe %1
-  echo otb_loader.exe %1 >> selftest_report.log
-  type tmp.log >> selftest_report.log
+  echo "ERROR: otb_loader.exe %1"
+  type tmp.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
 )
 endlocal
 goto :eof
@@ -101,9 +108,10 @@ goto :eof
 setlocal
 set dll_path=%~n1
 set app=%dll_path:~7%
+if %TEST_VERBOSE% equ 1 ( echo ":check_application %app%" )
 if not exist bin\otbcli_%app%.bat (
   echo ERROR : missing cli launcher for application %app%
-  echo ERROR : missing cli launcher for application %app% >> selftest_report.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
   goto :check_gui
 )
 type NUL > tmp.log
@@ -111,13 +119,14 @@ cmd /C bin\otbcli_%app%.bat "-help" ^> tmp.log ^2^>^&^1
 call :parse_cli_output
 if %parse_cli_result% equ 0 (
   echo ERROR : error launching application otbcli_%app%
-  echo ERROR : error launching application otbcli_%app% >> selftest_report.log
-  type tmp.log >> selftest_report.log
-)
+  type results.txt 
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
+  )
+
 :check_gui
 if not exist bin\otbgui_%app%.bat (
   echo ERROR : missing gui launcher for application %app%
-  echo ERROR : missing gui launcher for application %app% >> selftest_report.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
   goto :check_application_end
 )
 if %app_count% geq 2 goto :check_application_end
@@ -130,20 +139,21 @@ if %child_pid% gtr 1 (
   set first_child=%child_pid%
 ) else (
   echo ERROR : could not launch otbgui_%app%
-  echo ERROR : could not launch otbgui_%app% >> selftest_report.log
-  type tmp.log >> selftest_report.log
+  type tmp.log 
   goto :check_application_clean
 )
 call :get_child_pid %first_child% otbApplicationLauncherQt.exe
 if not %child_pid% gtr 1 (
   echo ERROR : could not launch otbApplicationLauncherQt %app%
-  echo ERROR : could not launch otbApplicationLauncherQt %app% >> selftest_report.log
-  type tmp.log >> selftest_report.log
+  type tmp.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
 )
+  
 :check_application_clean
 if not %first_child% == 0 (
   taskkill /PID %first_child% /F /T > NUL 2>&1
 )
+  
 :check_application_end
 endlocal & set /a app_count=app_count+1
 goto :eof
@@ -161,8 +171,8 @@ if %child_pid% gtr 1 (
   taskkill /PID %child_pid% /F /T > NUL 2>&1
 ) else (
   echo ERROR : could not launch %appName%.exe
-  echo ERROR : could not launch %appName%.exe >> selftest_report.log
-  type tmp.log >> selftest_report.log
+  type tmp.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
 )
 endlocal
 goto :eof
@@ -174,8 +184,8 @@ python -c "import otbApplication" > tmp.log 2>&1
 call :nb_tmp_lines
 if %nb_tmp_lines_out% gtr 0 (
   echo ERROR : failed to run python wrapping
-  echo ERROR : failed to run python wrapping >> selftest_report.log
-  type tmp.log >> selftest_report.log
+  type tmp.log
+  if %EXIT_ON_ERROR% equ 1 ( exit 1 )
 )
 endlocal
 goto :eof
@@ -183,39 +193,36 @@ goto :eof
 :parse_cli_output
 setlocal
 set /a ret=1
-for /F %%a in ('findstr /n /r /c:"^This is the %app% application, version " tmp.log') do set output=%%a
-if not "%output%" gtr "1:" (
+findstr /n /r /c:"^This is the *.*(%app%) application, version " tmp.log  > results.txt
+if %errorlevel%==1 (
   set /a ret=0
-  goto :parse_cli_output_end
+  echo "findstr failed 1st regex in parse_cli_output"
+  goto :parse_cli_output_end  
 )
-set output=
-for /F %%a in ('findstr /n /r /c:"^Parameters:" tmp.log') do set output=%%a
-if not "%output%" gtr "3:" (
+findstr /n /r /c:"^Parameters: " tmp.log  > results.txt
+if %errorlevel%==1 (
   set /a ret=0
-  goto :parse_cli_output_end
+  echo "findstr failed 2nd regex in parse_cli_output"
+  goto :parse_cli_output_end  
 )
-set output=
-for /F %%a in ('findstr /n /r /c:"^Examples:" tmp.log') do set output=%%a
-if not "%output%" gtr "1" (
+findstr /n /r /c:"^Examples: " tmp.log  > results.txt
+if %errorlevel%==1 (
   set /a ret=0
-  goto :parse_cli_output_end
+    echo "findstr failed 3rd regex in parse_cli_output"
+  goto :parse_cli_output_end  
 )
-set output=
-for /F %%a in ('findstr /n /r /c:"FATAL" tmp.log') do set output=%%a
-if "%output%" gtr "1" (
+findstr /n /r /c:"FATAL" tmp.log  > results.txt
+if %errorlevel%==0 (
   set /a ret=0
-  goto :parse_cli_output_end
+    echo "findstr passed 4th regex in parse_cli_output"
+  goto :parse_cli_output_end  
 )
+
 :parse_cli_output_end
 endlocal & set /a parse_cli_result=%ret%
 goto :eof
 ::-----------------------------------------------------------------------
-:nb_report_lines
-setlocal
-for /F "delims=" %%i in ('find /C /V "" ^< selftest_report.log') do set output=%%i
-endlocal & set nb_report_lines_out=%output%
-goto :eof
-::-----------------------------------------------------------------------
+
 :nb_tmp_lines
 setlocal
 for /F "delims=" %%i in ('find /C /V "" ^< tmp.log') do set output=%%i
@@ -245,3 +252,4 @@ setlocal
 reg add "HKCU\Software\Microsoft\Windows\Windows Error Reporting" /v DontShowUI /t REG_DWORD /d %1 /f
 endlocal
 goto :eof
+
diff --git a/SuperBuild/Packaging/Files/selftester.sh b/Packaging/Files/selftester.sh
similarity index 70%
rename from SuperBuild/Packaging/Files/selftester.sh
rename to Packaging/Files/selftester.sh
index 6cf5f86c2c59f7dfe1714e3dc0a8f71ef2491a4d..69d42e1304a79770bca9ffc2831ab3ac2d9be221 100755
--- a/SuperBuild/Packaging/Files/selftester.sh
+++ b/Packaging/Files/selftester.sh
@@ -1,9 +1,29 @@
 #!/bin/sh
-
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
 # Setup test environment
-DIRNAME_0=$(dirname "$0")
-DIRNAME=$(readlink "$DIRNAME_0/..")
-cd "$DIRNAME" || exit
+CUR_DIR="$( cd "$( dirname "$0" )/../" && pwd )"
+echo "CUR_DIR=$CUR_DIR"
+cd "$CUR_DIR" || exit
+
+EXIT_ON_ERROR=1
 
 # define convenient functions
 # ps_children( parentPID ) : get PIDs of children processes
@@ -16,14 +36,23 @@ nb_report_lines () {
   report_lines="$(wc -l selftest_report.log)"
   echo $report_lines | cut -d ' ' -f 1
 }
+#
+
+exit_if () {
+  if [ $EXIT_ON_ERROR = 1 ]; then
+      echo "EXIT_ON_ERROR=1"
+      exit 1;
+  fi
+}
 
 # echo_and_report ( string ) : echo and print to report
 echo_and_report () {
-  echo "$1" | tee -a selftest_report.log
+    echo "$1" | tee -a selftest_report.log
+    exit_if
 }
 
 # -------------------------------------------------------------------------
-. ./otbenv.profile
+. "$CUR_DIR/otbenv.profile"
 
 rm -f selftest_report.log
 touch selftest_report.log
@@ -35,7 +64,7 @@ OTB_SO_LIBRARIES=$(find lib -name '*.so*')
 OTB_DY_LIBRARIES=$(find lib -name '*.dylib')
 OTB_EXE="bin/mapla bin/monteverdi bin/otbApplicationLauncherQt bin/otbApplicationLauncherCommandLine"
 for name in $OTB_SO_LIBRARIES $OTB_DY_LIBRARIES $OTB_EXE; do
-  F_OUTPUT=$(file "$name")
+    F_OUTPUT=$(file "$name")
   if echo "$F_OUTPUT" | grep -q 'cannot open'; then
     echo_and_report "$F_OUTPUT"
   elif echo "$F_OUTPUT" | grep -q ': broken symbolic link'; then
@@ -55,15 +84,15 @@ for name in $OTB_SO_LIBRARIES $OTB_DY_LIBRARIES $OTB_EXE; do
   elif echo "$F_OUTPUT" | grep -q ': symbolic link'; then
     :
   else
-    echo_and_report "Unkown file type : $F_OUTPUT"
+    echo_and_report "Unknown file type : $F_OUTPUT"
   fi
 done
 
 REPORT_SIZE=$(nb_report_lines)
 if [ "$REPORT_SIZE" -ne "$REF_SIZE" ]; then
-  echo "Check 1/3 : FAIL"
+  echo "Check 1/4 : FAIL"
 else
-  echo "Check 1/3 : PASS"
+  echo "Check 1/4 : PASS"
 fi
 REF_SIZE=$REPORT_SIZE
 
@@ -76,14 +105,14 @@ fi
 app_index=0
 for app in $OTB_APPS; do
   if [ ! -f "bin/otbcli_$app" ]; then
-    echo_and_report "ERROR: missing cli launcher for application $app"
+      echo_and_report "ERROR: missing cli launcher for application $app"
+      
   else
     CLI_OUTPUT=$("bin/otbcli_$app" -help 2>&1)
-    CLI_FILTER=$(echo "${CLI_OUTPUT}"| tr '\n' ' ' | grep -E "^This is the $app application, version .* Parameters: .* Examples:.*")
+    CLI_FILTER=$(echo "${CLI_OUTPUT}"| tr '\n' ' ' | grep -E "This is the*.*$app*.*application, version .* Parameters: .* Examples:.*")
     CLI_FILTER2=$(echo "$CLI_FILTER" | grep -v 'FATAL')
     if [ -z "$CLI_FILTER2" ]; then
-      echo_and_report "ERROR: bin/otbcli_$app"
-      echo_and_report "$CLI_OUTPUT"
+      echo_and_report "ERROR: bin/otbcli_$app\n$CLI_OUTPUT"
     fi
   fi
   # test the gui launcher only on 2 first applications
@@ -104,12 +133,14 @@ for app in $OTB_APPS; do
         kill -9 "$NEXT_CHILD_PID"
         wait "$NEXT_CHILD_PID" 2>/dev/null
       else
-        echo_and_report "ERROR: otbApplicationLauncherQt $app failed to launch"
+        echo "ERROR: otbApplicationLauncherQt $app failed to launch"
         tee -a selftest_report.log < tmp.log
+	exit_if
       fi
     else
-      echo_and_report "ERROR: bin/otbgui_$app failed to launch"
-      tee -a selftest_report.log < tmp.log
+	echo "ERROR: bin/otbgui_$app failed to launch"
+	tee -a selftest_report.log < tmp.log
+	exit_if
     fi
   fi
   app_index=$(( app_index + 1 ))
@@ -124,9 +155,9 @@ fi
 
 REPORT_SIZE=$(nb_report_lines)
 if [ "$REPORT_SIZE" -ne "$REF_SIZE" ]; then
-  echo "Check 2/3 : FAIL"
+  echo "Check 2/4 : FAIL"
 else
-  echo "Check 2/3 : PASS"
+  echo "Check 2/4 : PASS"
 fi
 REF_SIZE=$REPORT_SIZE
 
@@ -168,9 +199,20 @@ fi
 
 REPORT_SIZE=$(nb_report_lines)
 if [ "$REPORT_SIZE" -ne "$REF_SIZE" ]; then
-  echo "Check 3/3 : FAIL"
+  echo "Check 3/4 : FAIL"
+else
+  echo "Check 3/4 : PASS"
+fi
+
+grep_cmd=$(which grep)
+grep_out=$($grep_cmd -Rs "/usr/" "$CUR_DIR/lib/cmake/")
+grep_ret=$?
+if [ $grep_ret -ne 1 ]; then
+    echo "Check 4/4 : FAIL"
+    echo "ERROR: your cmake files contains references to /usr. Is this normal?"
+    echo_and_report "$grep_out"
 else
-  echo "Check 3/3 : PASS"
+    echo "Check 4/4 : PASS"
 fi
 
 # clean any background process
diff --git a/Packaging/Files/setup_python.sh b/Packaging/Files/setup_python.sh
new file mode 100755
index 0000000000000000000000000000000000000000..e24731a88ca3579ff40925d97cf9ffaa87dccd0a
--- /dev/null
+++ b/Packaging/Files/setup_python.sh
@@ -0,0 +1,87 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Setup python environment
+if [ ! -f "$OTB_PYTHON_EXE" ] ; then
+    OTB_PYTHON_EXE=$(which python)
+fi
+
+python_major_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[0])")
+python_minor_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[1])")
+python_patch_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[2])")
+python_version="$python_major_version.$python_minor_version.$python_patch_version"
+
+python_check_failed() {
+    printf %s\\n "*****Error occurred during installation******"
+    printf %s\\n "OTB python bindings requires python2.6 or python2.7 but current detected python version is $python_version"
+    printf %s\\n "If you have python2.6 or Python2.7 installed in your system "
+    printf %s\\n "You should set OTB_PYTHON_EXE and re-run this installation script."
+    printf %s\\n "eg: OTB_PYTHON_EXE=/path/to/python2.7 ./OTB-X.Y-Linux64.run"
+    exit 1;
+}
+if [ "$python_major_version" -gt 2 ]; then
+python_check_failed
+fi
+
+if [ "$python_minor_version" -lt 5 ]; then
+python_check_failed
+fi
+
+python_INSTSONAME=$($OTB_PYTHON_EXE -c "import sys; from distutils import sysconfig; print (sysconfig.get_config_var('INSTSONAME'));")
+
+python_lib_dirs="$LD_LIBRARY_PATH /usr/lib /usr/lib64 /usr/lib/x86_64-linux-gnu"
+if [ "$(uname)" = "Darwin" ]; then
+    python_lib_dirs="$DYLD_LIBRARY_PATH /usr/lib /Library/Frameworks /opt/local/lib /opt/local/Library/Frameworks"
+fi;
+
+found_python_lib="0"
+python_lib_file_path=""
+for list_of_dir in $python_lib_dirs
+do
+    if [ -f "$list_of_dir/$python_INSTSONAME" ]; then
+        python_lib_file_path="$list_of_dir/$python_INSTSONAME"
+        found_python_lib="1"
+        break
+    fi
+done
+
+if [ "$found_python_lib" -eq "1" ]; then
+    numpy_import_result="$($OTB_PYTHON_EXE -c 'import numpy' 2>&1)"
+    if [ ! -z "$numpy_import_result" ]; then
+	printf %s\\n "*****Error occurred during installation******"
+	printf %s\\n "Python interpreter detected is : $OTB_PYTHON_EXE ( version: $python_version )"	
+	printf %s\\n "numpy not installed with '$OTB_PYTHON_EXE'"
+	printf %s\\n "Check failed with result:"
+	printf %s\\n "$numpy_import_result"
+	exit 1;
+    fi;
+    printf %s\\n "OTB python bindings will be configured for $OTB_PYTHON_EXE ( version: $python_version )"
+    printf %s\\n "Found python library: $python_lib_file_path"
+    #ln -sf "$python_lib_file_path" "OUT_DIR/lib/$python_INSTALLED_SONAME"
+else
+    printf %s\\n "*****Error occurred during installation******"
+    printf %s\\n "Python interpreter detected is : $OTB_PYTHON_EXE ( version: $python_version )"
+    printf %s\\n "$python_INSTSONAME cannot be found in any of search directories."
+    printf %s\\n "We had searched following directories $python_lib_dirs"
+    printf %s\\n "If you don't have python-dev package installed, install it and make a symlink"
+    printf %s\\n "If you don't have python headers and so installed on a custom location, then make a symlink"
+    printf %s\\n "eg: ln -s /usr/lib/x86_64-linux-gnu/$python_INSTSONAME OUT_DIR/lib/$python_INSTSONAME"
+fi
diff --git a/Packaging/Files/start_devenv.bat b/Packaging/Files/start_devenv.bat
new file mode 100755
index 0000000000000000000000000000000000000000..f0458cf027ca2a9f6b4ac24e65495409fee4ebe6
--- /dev/null
+++ b/Packaging/Files/start_devenv.bat
@@ -0,0 +1,41 @@
+::
+:: Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+::
+:: This file is part of Orfeo Toolbox
+::
+::     https://www.orfeo-toolbox.org/
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+::     http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+::
+
+@echo on
+
+set CURRENT_SCRIPT_DIR=%~dp0
+set CURRENT_SCRIPT_DIR=%CURRENT_SCRIPT_DIR:~0,-1%
+
+
+set PATH=%CURRENT_SCRIPT_DIR%\bin;%PATH%
+set VSDEV_ENV=C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
+set OTB_VS_TEMPLATE_DIR=%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates
+
+set OTB_XDK_DIR=%CURRENT_SCRIPT_DIR:\=/%
+::dir %OTB_VS_TEMPLATE_DIR%
+if exist "%VSDEV_ENV%" (
+if not exist "%OTB_VS_TEMPLATE_DIR%" (   md "%OTB_VS_TEMPLATE_DIR%" )
+copy "%CURRENT_SCRIPT_DIR%\OTB Project.zip" "%OTB_VS_TEMPLATE_DIR%"
+START "" "%VSDEV_ENV%"
+) else (
+echo "%VSDEV_ENV% not found"
+)
+
+@cmd
diff --git a/Packaging/Files/template.app/Contents/Info.plist b/Packaging/Files/template.app/Contents/Info.plist
new file mode 100644
index 0000000000000000000000000000000000000000..5f870f8d090a22d89878bf1b9b5a272acd36756d
--- /dev/null
+++ b/Packaging/Files/template.app/Contents/Info.plist
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+  <key>CFBundleExecutable</key>
+  <string>STARTUP_FILE</string>
+  <key>CFBundleIconFile</key>
+  <string>Monteverdi.icns</string>
+  <key>CFBundleInfoDictionaryVersion</key>
+  <string>6.0</string>
+  <key>CFBundlePackageType</key>
+  <string>APPL</string>
+  <key>CFBundleLongVersionString</key>
+  <string>LONG_VERSION</string>
+  <key>CFBundleShortVersionString</key>
+  <string>SHORT_VERSION</string>
+</dict>
+</plist>
diff --git a/Packaging/Files/uninstall_otb.bat b/Packaging/Files/uninstall_otb.bat
new file mode 100644
index 0000000000000000000000000000000000000000..b437444cee283e5945f207b8995922a82ec69664
--- /dev/null
+++ b/Packaging/Files/uninstall_otb.bat
@@ -0,0 +1,39 @@
+:: 
+:: Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+::
+:: This file is part of Orfeo Toolbox
+:: 
+::    https://www.orfeo-toolbox.org/
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+::    http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+:: script to uninstall OTB
+
+setlocal
+set CUR_DIR=%~dp0
+cd %CUR_DIR%..
+set MY_INSTALL_DIR=%cd%
+del /S /Q %MY_INSTALL_DIR%\include\OTB* || exit 1
+del /S /Q %MY_INSTALL_DIR%\lib\cmake\OTB* || exit 1
+del /S /Q %MY_INSTALL_DIR%\lib\otb* || exit 1
+del /S /Q %MY_INSTALL_DIR%\lib\python\_otbApplication.* || exit 1
+del /S /Q %MY_INSTALL_DIR%\bin\otb* || exit 1
+del /S /Q %MY_INSTALL_DIR%\bin\monteverdi.exe || exit 1
+del /S /Q %MY_INSTALL_DIR%\bin\mapla.exe || exit 1
+del /S /Q %MY_INSTALL_DIR%\mapla.bat || exit 1
+del /S /Q %MY_INSTALL_DIR%\monteverdi.bat || exit 1
+del /S /Q %MY_INSTALL_DIR%\share\OTB* || exit 1
+del /S /Q "%MY_INSTALL_DIR%\OTB Project.zip" || exit 1
+endlocal
+
+
diff --git a/Packaging/Files/uninstall_otb.sh b/Packaging/Files/uninstall_otb.sh
new file mode 100755
index 0000000000000000000000000000000000000000..4f596f38ed35d397f6ecd01658ec77412bccfbf0
--- /dev/null
+++ b/Packaging/Files/uninstall_otb.sh
@@ -0,0 +1,29 @@
+#!/bin/sh
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+set -e
+rm -fr OUT_DIR/include/OTB-*
+rm -f OUT_DIR/lib/{libotb*,libOTB*}
+rm -fr OUT_DIR/lib/{otb,python/_otbApplication*}
+rm -fr OUT_DIR/share/OTB*
+rm -fv OUT_DIR/bin/{otb*,monteverdi,mapla}
+rm -fv OUT_DIR/{mapla.sh,monteverdi.sh}
+
+echo "OTB is now uninstalled from OUT_DIR"
diff --git a/SuperBuild/Packaging/PackageGlobals.cmake b/Packaging/PackageGlobals.cmake
similarity index 78%
rename from SuperBuild/Packaging/PackageGlobals.cmake
rename to Packaging/PackageGlobals.cmake
index 9b94a74c1bade4cca2bbe6f69ea0e64a038e81dd..e945e98f31646c9ee350d1e43d025d513215d0f5 100644
--- a/SuperBuild/Packaging/PackageGlobals.cmake
+++ b/Packaging/PackageGlobals.cmake
@@ -18,6 +18,30 @@
 # limitations under the License.
 #
 
+set(LOADER_REGEX_EOL "E")
+set(DEST_BIN_DIR bin)
+set(DEST_APP_DIR lib/otb/applications)
+
+set(LIB_PREFIX lib)
+set(DEST_LIB_DIR lib)
+set(EXE_EXT "")
+set(SCRIPT_EXT ".sh")
+set(LIB_EXT ".so")
+set(PYMODULE_EXT ".so")
+set(STATIC_LIB_EXT ".a")
+
+if(WIN32)
+  set(LIB_PREFIX)
+  set(DEST_LIB_DIR bin)
+  set(EXE_EXT ".exe")
+  set(LIB_EXT ".dll")
+  set(SCRIPT_EXT ".bat")
+  set(PYMODULE_EXT ".pyd")
+  set(STATIC_LIB_EXT ".lib")
+elseif(APPLE)
+  set(LIB_EXT ".dylib")
+endif()
+
 set(WINDOWS_SYSTEM_DLLS
   user32.dll
   gdi32.dll
@@ -45,28 +69,9 @@ set(WINDOWS_SYSTEM_DLLS
   python...dll
   )
 
-if(MINGW)
-  set(WINDOWS_SYSTEM_DLLS
-    ${WINDOWS_SYSTEM_DLLS}
-    msvcrt.dll
-    )
-endif()
-
-if(PKG_GENERATE_XDK)
-  set(WINDOWS_SYSTEM_DLLS
-    ${WINDOWS_SYSTEM_DLLS}
-    api-ms-win-*
-    concrt140.dll
-    ucrtbase.dll
-    msvcp140.dll
-    msvrt140.dll
-    vcomp140.dll
-    )
-endif()
-
 set(LINUX_SYSTEM_DLLS
   libm.so
-  libc.so
+  libc.so.*
   libstdc*
   libgcc_s.so
   librt.so
@@ -76,6 +81,9 @@ set(LINUX_SYSTEM_DLLS
   libgomp.so*
   ld-linux-x86-64.so*
   libX11.so*
+  libXi.so*  #GLUT
+  libXcursor.so* #GLFW
+  libXinerama.so*  #GLFW
   libXext.so*
   libXau.so*
   libXdmcp.so*
@@ -88,10 +96,12 @@ set(LINUX_SYSTEM_DLLS
   libICE.so*
   libXrandr.so*
   libpython*
-  libexpat.so.*
-  libfontconfig.so*
-  libfreetype.so*
   )
+  # libexpat.so.*
+  # libfontconfig.so*
+  # libfreetype.so*
+  # libwebp.so*
+  # )
 
 # libgcc_s.*dylib and other *.framework are dragged by QT
 set(APPLE_SYSTEM_DLLS
@@ -150,9 +160,11 @@ set(GTK_LIB_LIST_1
   libpcre.so.3
   libffi.so.6
   )
-set(GTK_LIB_LIST_2
-  libz.so.1
-  libpng12.so.0
-  )
+# set(GTK_LIB_LIST_2
+#   libz.so.1
+#   libpng12.so.0
+#   )
+
 
-set(ALLOWED_SYSTEM_DLLS ${GTK_LIB_LIST_1} ${GTK_LIB_LIST_2})
+#set(ALLOWED_SYSTEM_DLLS ${GTK_LIB_LIST_1} ${GTK_LIB_LIST_2})
+set(ALLOWED_SYSTEM_DLLS ${GTK_LIB_LIST_1}) # ${GTK_LIB_LIST_2})
diff --git a/SuperBuild/Packaging/README.md b/Packaging/README.md
similarity index 100%
rename from SuperBuild/Packaging/README.md
rename to Packaging/README.md
diff --git a/Packaging/check_cmake_variables.cmake b/Packaging/check_cmake_variables.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..a757a3b07d3c4a0c5058dee1769848aeb6b58fe1
--- /dev/null
+++ b/Packaging/check_cmake_variables.cmake
@@ -0,0 +1,57 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+macro(check_cmake_variables)
+  set(required_vars)
+  if(OTB_WRAP_PYTHON)
+    list(APPEND required_vars PYTHON_EXECUTABLE)
+  endif()
+  
+  if(LINUX)
+    list(APPEND required_vars FILE_COMMAND)
+    list(APPEND required_vars READLINK)
+    list(APPEND required_vars  PATCHELF_PROGRAM)
+  endif()
+
+  if(WIN32)
+    list(APPEND required_vars ZIP_EXECUTABLE)
+  endif()
+  foreach(req
+      ${required_vars}
+      PKG_STAGE_DIR
+      SUPERBUILD_BINARY_DIR
+      SUPERBUILD_INSTALL_DIR
+      SUPERBUILD_SOURCE_DIR
+      PACKAGE_OTB_SRC_DIR
+      OTB_TARGET_SYSTEM_ARCH
+      OTB_TARGET_SYSTEM_ARCH_IS_X64
+      LOADER_PROGRAM
+      LOADER_ARGS
+      LOADER_REGEX
+      PKG_ITK_SB_VERSION
+      PKG_OTB_VERSION_STRING
+      PACKAGE_OUTPUT_FILE
+      )
+    if(NOT DEFINED ${req} OR "${${req}}" STREQUAL "")
+      message(FATAL_ERROR "you must set ${req}")
+    endif()
+    message(STATUS "${req}=[${${req}}]")
+  endforeach(req)
+
+endmacro()
diff --git a/Packaging/cleanup_package.cmake b/Packaging/cleanup_package.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..e7bae3164be1bc63518ea67f08bbc9351c58a879
--- /dev/null
+++ b/Packaging/cleanup_package.cmake
@@ -0,0 +1,58 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+macro(cleanup_package)
+
+if(EXISTS "${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}")
+
+message(STATUS "Deleting package staging directory: ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}")
+execute_process(COMMAND 
+${CMAKE_COMMAND} -E remove_directory
+  "${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}"
+  RESULT_VARIABLE cleanup_stagedir_rv
+  OUTPUT_VARIABLE cleanup_stagedir_ov
+  ERROR_VARIABLE cleanup_stagedir_ov
+  )
+  
+  if(cleanup_stagedir_rv)
+  message(FATAL_ERROR  "Delete ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR} - FAILED\ncleanup_stagedir_ov=${cleanup_stagedir_ov}")
+  else()
+  message(STATUS "Delete ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR} - OK")  
+  endif()
+endif()
+
+if(EXISTS "${PACKAGE_OUTPUT_FILE}")
+message(STATUS "Remove PACKAGE_OUTPUT_FILE: ${PACKAGE_OUTPUT_FILE}")
+execute_process(COMMAND 
+${CMAKE_COMMAND} -E remove -f "${PACKAGE_OUTPUT_FILE}"
+  RESULT_VARIABLE cleanup_pkgfile_rv
+  OUTPUT_VARIABLE cleanup_pkgfile_ov
+  ERROR_VARIABLE cleanup_pkgfile_ov
+  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+  )
+  
+    if(cleanup_pkgfile_rv)
+  message(FATAL_ERROR  "Delete ${PACKAGE_OUTPUT_FILE} - FAILED\ncleanup_pkgfile_ov=${cleanup_pkgfile_ov}")
+  else()
+  message(STATUS "Delete ${PACKAGE_OUTPUT_FILE} - OK")  
+  endif()
+  
+endif()
+endmacro()
diff --git a/Packaging/clear_cmakecache_variables.cmake b/Packaging/clear_cmakecache_variables.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..e4418c001a9463399b759e1c09a57644bcad4750
--- /dev/null
+++ b/Packaging/clear_cmakecache_variables.cmake
@@ -0,0 +1,29 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+macro(clear_cmakecache_variables)
+unset(matched_vars CACHE)
+  get_variables_ending_with("_USED|_RESOLVED" matched_vars)
+  foreach (var_to_unset IN LISTS matched_vars)
+    if(PKG_DEBUG)
+      message("unset ${var_to_unset} from cache")
+    endif()
+    unset(${var_to_unset} CACHE)
+  endforeach()
+endmacro() #clear_cmakecache_variables
diff --git a/Packaging/configure_loader.cmake b/Packaging/configure_loader.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..74f70943120ce26bc2ab2c15ada68e4acba1e69f
--- /dev/null
+++ b/Packaging/configure_loader.cmake
@@ -0,0 +1,50 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(configure_loader loader_pgm_result loader_args_result loader_regex_result)
+set(loader_PATHS)
+if(MSVC)
+    set(loader_PATHS)
+    set(loader_names      "dumpbin")
+    set(loader_args       "/DEPENDENTS")
+    set(loader_regex      "^    ([^ ].*[Dd][Ll][Ll])${LOADER_REGEX_EOL}$")
+  elseif(APPLE)
+    set(loader_PATHS)
+    set(loader_names    otool)
+    set(loader_args      "-l" )
+    set(loader_regex ".*name.*([ ].*dylib ).*${LOADER_REGEX_EOL}$")
+  elseif("${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
+    set(loader_PATHS)
+    set(loader_names    objdump)
+    set(loader_args    "-p" )
+    set(loader_regex "^..NEEDED.*([ ].*so.*)${LOADER_REGEX_EOL}$")
+  else()
+    message(FATAL_ERROR "find_loader_and_args: Unknown platform")
+  endif()
+  
+  find_program(loader_pgm "${loader_names}" PATHS ${loader_PATHS})
+  if(NOT loader_pgm)
+    message(FATAL_ERROR "${loader_names} not found in ${loader_PATHS}.")
+  endif()
+
+  #save result in PARENT_SCOPE
+  set(${loader_args_result} ${loader_args} PARENT_SCOPE)
+  set(${loader_pgm_result} ${loader_pgm} PARENT_SCOPE)
+  set(${loader_regex_result} ${loader_regex} PARENT_SCOPE)  
+endfunction()
diff --git a/Packaging/create_package.cmake b/Packaging/create_package.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..d53e0181089311cc153da9032c5d7d0ef506e774
--- /dev/null
+++ b/Packaging/create_package.cmake
@@ -0,0 +1,45 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+macro(create_package)
+  install(CODE "
+    message(STATUS \"Creating ${PACKAGE_OUTPUT_FILE}\") 
+    if(WIN32)
+      execute_process(
+        COMMAND ${ZIP_EXECUTABLE} \"a\" \"-r\" \"-y\"
+        \"${PACKAGE_OUTPUT_FILE}\" \"${PKG_STAGE_DIR}/*\"
+        WORKING_DIRECTORY \"${CMAKE_INSTALL_PREFIX}\"
+      )
+    else()
+      execute_process(
+        COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/makeself/makeself.sh
+        \"--quiet\"
+        \"--target\"
+        \"${PKG_STAGE_DIR}\"
+        \"${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}\"
+        \"${PKG_STAGE_DIR}.run\"
+        \"${PACKAGE_LONG_NAME} ${PKG_OTB_VERSION_STRING}\"
+        \"./pkgsetup\"
+        WORKING_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}\"
+     )
+    endif()
+  ")
+
+endmacro()
+
diff --git a/Packaging/detect_using_file_command.cmake b/Packaging/detect_using_file_command.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..61a060399aebedd020bd1b44688aec0a12bbc2cc
--- /dev/null
+++ b/Packaging/detect_using_file_command.cmake
@@ -0,0 +1,111 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(detect_using_file_command input_file result_type result_dir)
+  
+  execute_process(COMMAND "${FILE_COMMAND}" "${input_file}"
+    RESULT_VARIABLE file_rv
+    OUTPUT_VARIABLE file_ov
+    ERROR_VARIABLE file_ev
+    OUTPUT_STRIP_TRAILING_WHITESPACE
+    )
+  if(NOT file_rv STREQUAL "0")
+    message(FATAL_ERROR "${FILE_COMMAND} failed: ${file_rv}\n${file_ev}\n${file_ov}")
+  endif()
+
+  get_filename_component(input_file_NAME ${input_file} NAME)
+  string(REPLACE "${input_file}" " _file_full_ " file_ov "${file_ov}")
+  string(TOLOWER "${file_ov}" file_ov_lower)
+
+  set(detected_type)
+  set(detected_dir)
+  # below executable check works for both mac osx and linux
+  if("${file_ov_lower}" MATCHES "executable")
+    set(detected_type PROGRAMS)
+    set(detected_dir bin)
+    # detect position independent executables on Linux,
+    # where "file" gives "dynamically linked (uses shared libraries)"
+  elseif("${file_ov_lower}" MATCHES "dynamically linked.*\(uses shared libs\)")
+    set(detected_type FILES)
+    set(detected_dir lib)
+    # detect position independent executables on Linux,
+    # where "file" gives "shared object ... (uses shared libraries)"
+  elseif("${file_ov_lower}" MATCHES "shared object.*\(uses shared libs\)")
+    set(detected_type FILES)
+    set(detected_dir lib)
+    # detect shared libraries on Linux,
+    # where "file" gives "ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not stripped"
+  elseif("${file_ov_lower}" MATCHES "elf.*shared object.*version")
+    set(detected_type FILES)
+    set(detected_dir lib)
+    # "file" version 5.22 does not print "(used shared libraries)"
+    # but uses "interpreter"
+  elseif("${file_ov_lower}" MATCHES "shared object.*interpreter")
+    set(detected_type FILES)
+    set(detected_dir lib)
+    # detect shared libraries on Mac OSX
+    # where "file" gives "Mach-O 64-bit x86_64 dynamically linked shared library"
+  elseif("${file_ov_lower}" MATCHES "mach-o.*dynamically linked shared library")
+    set(detected_type FILES)
+    set(detected_dir lib)
+    #below check is redundant.  detect executables on Mac OSX
+    # where "file" gives "Mach-O 64-bit x86_64 executable"
+  elseif("${file_ov_lower}" MATCHES "mach-o.*executable")
+    set(detected_type PROGRAMS)
+    set(detected_dir bin)
+    # detect shared libraries on Mac OSX
+    # where "file" gives "Mach-O 64-bit x86_64 bundle"
+  elseif("${file_ov_lower}" MATCHES "mach-o.*bundle")
+    set(detected_type FILES)
+    set(detected_dir lib)
+  elseif("${file_ov_lower}" MATCHES "mach-o.*bundle")
+    set(detected_type FILES)
+    set(detected_dir lib)
+  elseif("${file_ov_lower}" MATCHES "symbolic link")
+    #this will do a symlink check again using but that's okay!
+
+    #set type to symlink we are going to resolve it anyway
+    set(detected_type "symlink")
+
+    set(is_this_a_symbolic_link FALSE)
+    set(target_file)
+    isfile_symlink("${input_file}" is_this_a_symbolic_link target_file)    
+    if(is_this_a_symbolic_link)
+      
+      if(target_file)
+	set(libdir "lib")
+	setif_value_in_list(is_gtk_lib "${input_file_NAME}" GTK_LIB_LIST_1)
+	if(is_gtk_lib)
+	  set(libdir "lib/gtk")
+	endif()
+	file(APPEND
+	  ${CMAKE_BINARY_DIR}/make_symlinks
+	  "ln -sf \"$OUT_DIR/${libdir}/${target_file}\" \"$OUT_DIR/${libdir}/${input_file_NAME}\" \n"
+	  )
+      endif() #target_file
+    endif() #is_this_a_symbolic_link
+  else() #if("${file_ov_lower}" MATCHES ...)
+    #we are out of options at this point. throw error!
+    message(FATAL_ERROR "unknown/untracked file type found: ${input_file}")
+  endif() #if("${file_ov_lower}" MATCHES ...)
+
+  #message("detected_type=${detected_type}")
+  set(${result_type} "${detected_type}" PARENT_SCOPE)
+  set(${result_dir} "${detected_dir}" PARENT_SCOPE)
+endfunction()
diff --git a/Packaging/get_variables_ending_with.cmake b/Packaging/get_variables_ending_with.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..8998aff47eef25ab47d94a91280159d88bf719e2
--- /dev/null
+++ b/Packaging/get_variables_ending_with.cmake
@@ -0,0 +1,24 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function (get_variables_ending_with suffix result)
+  get_cmake_property(all_cmake_vars VARIABLES)
+  string (REGEX MATCHALL "(^|;)[A-Za-z0-9_\\.\\-]*(${suffix})" _matchedVars "${all_cmake_vars}")
+  set(${result} ${_matchedVars} PARENT_SCOPE)
+endfunction()
diff --git a/Packaging/howto_update_makeself b/Packaging/howto_update_makeself
new file mode 100644
index 0000000000000000000000000000000000000000..97df2547a2f72f046ce976408ea49bbd6c80d8f3
--- /dev/null
+++ b/Packaging/howto_update_makeself
@@ -0,0 +1,11 @@
+HOW TO UPDATE MAKESELF
+
+#If makEself version with your required bug fix is 2.3.1
+# cd to otb/sources/Packaging/
+
+wget https://github.com/megastep/makeself/archive/release-2.3.1.tar.gz
+tar xzf release-2.3.1.tar.gz
+mv makeself-release-2.3.1 makeself
+rm -fr release-2.3.1.tar.gz
+
+run git diff to check if everything is in place and git commit 
diff --git a/Packaging/install_cmake_files.cmake b/Packaging/install_cmake_files.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..ca63afb0f6203fa8295aece0e09dcc8a03f15939
--- /dev/null
+++ b/Packaging/install_cmake_files.cmake
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+include(patch_cmake_files.cmake)
+
+function(install_cmake_files)
+ patch_cmake_files(NAME "ITK"
+   VERSION "${PKG_ITK_SB_VERSION}"
+   MATCH_STRING  "${CMAKE_INSTALL_PREFIX}"
+   REPLACE_VAR "ITK_INSTALL_PREFIX"
+   )
+ 
+ patch_cmake_files(NAME "OTB"
+   VERSION "${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}"
+   MATCH_STRING  "${CMAKE_INSTALL_PREFIX}"
+   REPLACE_VAR "OTB_INSTALL_PREFIX"
+   )
+endfunction()
diff --git a/Packaging/install_importlibs.cmake b/Packaging/install_importlibs.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..5a68caff7cf580c8ef97b59c4e57a459e4287f3a
--- /dev/null
+++ b/Packaging/install_importlibs.cmake
@@ -0,0 +1,43 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#
+# This is more messed up that you might think.
+# On windows we cannot track dependency on .lib files like dll
+function(install_importlibs)
+  if(NOT WIN32)
+    return()
+  endif()
+  
+  #ALL .lib files are required for building
+  #eg: gdal.dll will have gdal_i.lib which is
+  #needed when you do cmake configure for projects
+  #using OTB. Hence the *.lib regex is non optional
+  #and cannot be optimized at any level.
+  #Only thing you can control is to create only those
+  #required .lib files in install directory.
+  file(GLOB import_lib_files
+    "${SUPERBUILD_INSTALL_DIR}/lib/*.lib"
+    "${SUPERBUILD_INSTALL_DIR}/bin/itk*.dll"
+    )
+  foreach( import_lib_file ${import_lib_files})
+    install_rule(${import_lib_file})
+  endforeach()
+
+endfunction()
diff --git a/Packaging/install_include_dirs.cmake b/Packaging/install_include_dirs.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..1a243ae60d6b5b4a3a8f0f762b1629b115d6ab99
--- /dev/null
+++ b/Packaging/install_include_dirs.cmake
@@ -0,0 +1,36 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_include_dirs)
+  # #install ${SUPERBUILD_INSTALL_DIR}/include directory.
+  file(GLOB ALL_IN_INCLUDE_DIR "${SUPERBUILD_INSTALL_DIR}/include/*")
+  foreach(INCLUDE_DIR_ITEM ${ALL_IN_INCLUDE_DIR})
+    get_filename_component(INCLUDE_DIR_ITEM_name ${INCLUDE_DIR_ITEM} NAME)
+    if( IS_DIRECTORY ${INCLUDE_DIR_ITEM})
+      install(CODE
+        "message(STATUS \"Installing: ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}/include/${INCLUDE_DIR_ITEM_name}/\")" )
+      install(DIRECTORY   "${INCLUDE_DIR_ITEM}"
+        DESTINATION "${PKG_STAGE_DIR}/include/"
+        MESSAGE_NEVER)
+    else()
+      install(FILES   "${INCLUDE_DIR_ITEM}"
+        DESTINATION "${PKG_STAGE_DIR}/include/" )
+    endif() #if( IS_DIRECTORY    
+  endforeach()
+endfunction()
diff --git a/Packaging/install_otbapp_wrapper_scripts.cmake b/Packaging/install_otbapp_wrapper_scripts.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..bba639a281ffe426390004917e0c366044f20a7d
--- /dev/null
+++ b/Packaging/install_otbapp_wrapper_scripts.cmake
@@ -0,0 +1,58 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_otbapp_wrapper_scripts otbapp_libfile)
+  ########### install cli and gui script for each application ###########
+  set(my_script_ext "")
+  if(WIN32)
+    set(my_script_ext ".bat")
+  endif()
+  get_filename_component(otbapp_libfile_WE ${otbapp_libfile} NAME_WE)
+  #just remove otbapp_ first. we will add otbcli_ or otbgui_ later
+  set(otbapp_name)
+  string(REPLACE "otbapp_" "" otbapp_name ${otbapp_libfile_WE})
+
+  #now define cli_script with valid name otbcli_<APPNAME><EXT>
+  set(cli_script "otbcli_${otbapp_name}${my_script_ext}")
+  if(NOT EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/${cli_script}")
+    #report error!
+    message(FATAL_ERROR "Cannot find ${cli_script} for ${otbapp_libfile}")
+  endif()
+  #install file
+  install(
+    PROGRAMS "${SUPERBUILD_INSTALL_DIR}/bin/${cli_script}"
+    DESTINATION ${PKG_STAGE_DIR}/bin
+    )
+
+  #Do the same for otbgui script but only if HAVE_QT4 is set.
+  if(NOT HAVE_QT4)
+    return()
+  endif()
+  
+  #now define gui_script_actual with valid name otbgui_<APPNAME><EXT>
+  set(gui_script "otbgui_${otbapp_name}${my_script_ext}")
+  if(NOT EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/${gui_script}")
+    #report error
+    message(FATAL_ERROR "Cannot find ${gui_script} for ${otbapp_libfile}")
+  endif()
+  #install script file
+  install(
+  PROGRAMS "${SUPERBUILD_INSTALL_DIR}/bin/${gui_script}"
+  DESTINATION ${PKG_STAGE_DIR}/bin )
+endfunction() 
diff --git a/Packaging/install_python_bindings.cmake b/Packaging/install_python_bindings.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..451894bb09aa00a844d46f985419cd3955322400
--- /dev/null
+++ b/Packaging/install_python_bindings.cmake
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_python_bindings)
+  if(HAVE_PYTHON)
+    install(DIRECTORY ${SUPERBUILD_INSTALL_DIR}/lib/otb/python
+      DESTINATION ${PKG_STAGE_DIR}/lib
+      PATTERN "*.pyc" EXCLUDE
+      )
+  endif()
+endfunction()
diff --git a/Packaging/install_qtdev_files.cmake b/Packaging/install_qtdev_files.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..a615b02d0a2b28896360888f3b7a59fca9b391f1
--- /dev/null
+++ b/Packaging/install_qtdev_files.cmake
@@ -0,0 +1,46 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_qtdev_files)
+  if(NOT HAVE_QT4)
+    return()
+  endif()
+set(QT_REQ_DIRS)
+  if(MSVC)
+    file(GLOB ALL_LIB_FILES "${SUPERBUILD_INSTALL_DIR}/lib/*.lib")
+  endif()
+  foreach(LIB_FILE ${LIB_FILES})
+    install_rule(${LIB_FILE})
+  endforeach()
+  list(APPEND QT_REQ_DIRS imports)  
+  list(APPEND QT_REQ_DIRS mkspecs)
+  list(APPEND QT_REQ_DIRS plugins)
+  list(APPEND QT_REQ_DIRS translations)
+  foreach(QT_REQ_DIR ${QT_REQ_DIRS} )
+    if(EXISTS "${SUPERBUILD_INSTALL_DIR}/${QT_REQ_DIR}")
+      install_without_message("${SUPERBUILD_INSTALL_DIR}/${QT_REQ_DIR}" "")
+    endif()
+  endforeach()
+
+  install(FILES
+    ${CMAKE_CURRENT_SOURCE_DIR}/Files/qt.conf
+    DESTINATION ${PKG_STAGE_DIR}/bin
+    )
+ 
+endfunction()
diff --git a/Packaging/install_rule.cmake b/Packaging/install_rule.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..e404a59fe6ea212d03a5055a08b3a0cc2321d0f9
--- /dev/null
+++ b/Packaging/install_rule.cmake
@@ -0,0 +1,121 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#
+# This is one big fat if-elseif ladder
+# that will detect a type and destination to use in
+# install(..
+
+function(install_rule src_file)
+
+  get_filename_component(src_file_EXT ${src_file} EXT)
+  get_filename_component(src_file_NAME ${src_file} NAME)
+  get_filename_component(src_file_NAME_WE ${src_file} NAME_WE)
+  get_filename_component(src_file_PATH ${src_file} PATH)
+
+  file(GLOB src_file_star "${src_file_PATH}/${src_file_NAME_WE}*")
+  foreach(sfile ${src_file_star})
+    get_filename_component(sfile_NAME ${sfile} NAME)
+    string(TOLOWER "${sfile_NAME}" sfile_NAME_LOWER)
+
+    get_filename_component(sfile_ABS "${sfile}" ABSOLUTE)
+    string(TOLOWER "${sfile_ABS}" sfile_ABS_LOWER)
+    set(install_type)
+    set(install_dir)
+    if ("${sfile_NAME_LOWER}" MATCHES "^(otb|mvd)([a-z0-9]+)test*.*" )
+      if(PKG_DEBUG)
+        message("SKIP INSTALL for ${sfile_NAME_LOWER}")
+      endif()
+      continue()
+    elseif ("${sfile_NAME_LOWER}" MATCHES "headertest" )
+      # special case for remote modules which has executables
+      # like MosiacHeaderTest1.exe. This ideally should be
+      # fixed in remote modules like OTBMosiacHeaderTest1.exe
+      if(PKG_DEBUG)
+	message("SKIP INSTALL for ${sfile_NAME_LOWER}")
+      endif()
+      continue()
+    elseif("${sfile_ABS_LOWER}" MATCHES "(\\.exe)$")
+      set(install_type PROGRAMS)
+      set(install_dir bin)
+    elseif("${sfile_ABS_LOWER}" MATCHES "(\\.dll)$")
+      set(install_type FILES)
+      set(install_dir bin) 
+    elseif("${sfile_ABS_LOWER}" MATCHES "(\\.lib)$")
+      set(install_type FILES)
+      set(install_dir lib)
+    elseif("${sfile_ABS_LOWER}" MATCHES "(\\.pyd)$")
+      #python bindings are installed in install_python_bindings
+      continue()
+    elseif( "${sfile_NAME_LOWER}" MATCHES "^_otbapplication")
+      # _otbApplication.so matched below; so we explicit skip it
+      # because it's already handled in install_python_bindings.cmake
+      continue()
+    elseif("${sfile_ABS_LOWER}" MATCHES "\\.lnk$")
+      #we don't install symlink on windows. issue a warning
+      set(install_type "symlink")
+      set(install_dir)
+    elseif("${sfile_ABS_LOWER}" MATCHES "(\\.a)$")
+      set(install_type FILES)
+      set(install_dir lib)
+    elseif("${sfile_ABS_LOWER}" MATCHES "\\.prl$")
+      continue()
+    elseif("${sfile_ABS_LOWER}" MATCHES "\\.la$")
+      continue()
+    else()
+      if(UNIX)
+        #the last else() loop where we run a 'file' command to find file type and directory
+        set(install_type)
+        set(install_dir)
+        #this is whole other story
+        detect_using_file_command(${sfile_ABS} install_type install_dir)
+      endif(UNIX)
+    endif()
+
+    if(install_type STREQUAL "symlink")
+      #we don't install symlink on windows. issue a warning and continue
+      if(PKG_DEBUG)
+        message("${sfile_ABS} is a symbolic link and this will be excluded from package")
+      endif()
+      continue()
+    endif()
+    
+    # This check comes outside the first if-elseif ladder
+    # because no matter what extension of file type, otbapp_* must go
+    # into lib/otb/applications
+  if("${sfile_NAME_LOWER}" MATCHES "^otbapp_")
+    install_otbapp_wrapper_scripts(${sfile_NAME})
+    set(install_dir "lib/otb/applications")
+    set(install_type PROGRAMS)
+  endif()
+  
+    if(NOT install_type OR NOT install_dir)
+      #throw fatal error and return
+      message(FATAL_ERROR "sfile_ABS=${sfile_ABS}.\ninstall_type=${install_type}\ninstall_dir=${install_dir}")
+      return()
+    endif()
+
+    install(${install_type} "${sfile}"
+      DESTINATION
+      "${PKG_STAGE_DIR}/${install_dir}"
+      )
+
+  endforeach()  
+endfunction()   
+
diff --git a/Packaging/install_share_dirs.cmake b/Packaging/install_share_dirs.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..62f18e2e50be56c808d1d594d015bfe567904358
--- /dev/null
+++ b/Packaging/install_share_dirs.cmake
@@ -0,0 +1,97 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_share_dirs)
+
+  #a convenient cmake var for storing <prefix>/bin
+  set(PKG_STAGE_BIN_DIR "${PKG_STAGE_DIR}/bin")
+
+  #<prefix>/share for gdal data files
+  set(PKG_SHARE_DEST_DIR ${PKG_STAGE_DIR}/share)
+
+  set(PKG_SHARE_SOURCE_DIR ${SUPERBUILD_INSTALL_DIR}/share)
+
+
+  ####################### install mvd i18N ############################
+  # OTB i18n directory is different from qt's i18N directory
+  #which is <prefix>/share/qt4/translations by default on linux.
+
+  # To install otb i18n directory correctly, we need to find
+  #Monteverdi_INSTALL_DATA_DIR. Value of this is a defined in  ConfigureMonteverdi.h
+  # and default value is "share/OTB-X.Y"
+  #...
+  # #define Monteverdi_INSTALL_DATA_DIR
+  #...
+  #Instead of parsing ConfigureMonteverdi.h,
+  #we simply use default and add a check for this directory!
+
+  #define Monteverdi_INSTALL_DATA_DIR "share/OTB-X.Y"
+
+  set(OTB_I18N_DIRNAME OTB-${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}/i18n)  
+  set(MVD_I18N_SOURCE_DIR ${PKG_SHARE_SOURCE_DIR}/${OTB_I18N_DIRNAME})
+  if(NOT EXISTS "${MVD_I18N_SOURCE_DIR}")
+    message(FATAL_ERROR "Error ${MVD_I18N_SOURCE_DIR} not exists")
+  endif()
+  set(MVD_I18N_DEST_DIR ${PKG_SHARE_DEST_DIR}/${OTB_I18N_DIRNAME})
+  file(GLOB MVD_APP_TS_FILES ${PACKAGE_OTB_SRC_DIR}/i18n/*.ts) # qm files
+  foreach(APP_TS_FILE ${APP_TS_FILES})
+    get_filename_component(APP_TS_FILENAME ${APP_TS_FILE} NAME_WE)
+    install(FILES ${MVD_I18N_SOURCE_DIR}/${APP_TS_FILENAME}.qm
+      DESTINATION ${MVD_I18N_DEST_DIR}
+      )
+  endforeach()
+
+  ####################### install GDAL data ############################
+  set(GDAL_DATA_DIR ${PKG_SHARE_SOURCE_DIR}/gdal)
+  #MSVC install gdal-data in in a different directory. So we don't spoil it
+  if(MSVC)
+    set(GDAL_DATA_DIR ${SUPERBUILD_INSTALL_DIR}/data)
+  endif()
+  if(NOT EXISTS "${GDAL_DATA_DIR}/epsg.wkt")
+    message(FATAL_ERROR
+      "Cannot generate package without GDAL_DATA : ${GDAL_DATA_DIR}")
+  endif()
+  install_without_message("${GDAL_DATA_DIR}" "share" )
+
+  ####################### install GeoTIFF data ########################
+  install_without_message("${PKG_SHARE_SOURCE_DIR}/epsg_csv" "share" )
+
+  ####################### install OSSIM data ##########################
+  install_without_message("${PKG_SHARE_SOURCE_DIR}/ossim" "share" )
+
+  ####################### install proj share ##########################
+  if(EXISTS ${PKG_SHARE_SOURCE_DIR}/proj)
+    install_without_message("${PKG_SHARE_SOURCE_DIR}/proj" "share" )
+  endif()
+  
+  ####################### Install copyrights ##########################
+  #install license for packages
+  install_without_message("${PKG_SHARE_SOURCE_DIR}/copyright" "share" )
+  install(FILES ${PKG_SHARE_SOURCE_DIR}/copyright/LICENSE
+    DESTINATION ${PKG_STAGE_DIR})
+
+  ####################### Install VERSION ##########################
+  set(PKG_VERSION_FILE
+    "${SUPERBUILD_INSTALL_DIR}/share/doc/${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}/VERSION")
+  if(EXISTS ${PKG_VERSION_FILE} )
+    install(FILES ${PKG_VERSION_FILE} DESTINATION ${PKG_STAGE_DIR})
+  endif()
+ 
+endfunction()
+
diff --git a/Packaging/install_vstudio_files.cmake b/Packaging/install_vstudio_files.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..8630dd8081e9d233348c6f8a14e5dfafe5d49c3d
--- /dev/null
+++ b/Packaging/install_vstudio_files.cmake
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_vstudio_files)
+if(MSVC)
+    install(FILES
+      "Files/OTB Project.zip"
+      "Files/start_devenv.bat"
+      DESTINATION "${PKG_STAGE_DIR}" )
+  endif()
+endfunction()
diff --git a/Packaging/install_without_message.cmake b/Packaging/install_without_message.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..947e8d9b66da373a2e788c934ad73bc10b037df9
--- /dev/null
+++ b/Packaging/install_without_message.cmake
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(install_without_message src_dir dst_dir_suffix)
+  set (extra_func_args ${ARGN})
+  list(LENGTH extra_func_args num_extra_args)
+  if (${num_extra_args} GREATER 0)
+    list(GET extra_func_args 0 optional_msg)
+  endif()
+
+  if( "${dst_dir_suffix}" STREQUAL "")
+    set(dst_dir "${PKG_STAGE_DIR}")
+  else()
+    set(dst_dir "${PKG_STAGE_DIR}/${dst_dir_suffix}")
+  endif()
+
+  get_filename_component(src_dir_name ${src_dir} NAME)
+  set(install_msg "message(STATUS \"Installing: ${CMAKE_INSTALL_PREFIX}/${dst_dir}/${src_dir_name} ${optional_msg}\")")
+  install(CODE "${install_msg}" )
+  install(
+    DIRECTORY   ${src_dir}
+    DESTINATION ${dst_dir}
+    MESSAGE_NEVER )
+endfunction() #install_without_message
diff --git a/Packaging/installer_files.cmake b/Packaging/installer_files.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..941f7f8cdfbf8caa17e8f52e3553a65bd25b6ab9
--- /dev/null
+++ b/Packaging/installer_files.cmake
@@ -0,0 +1,133 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+macro(installer_files)
+
+  #configure README from rst docs
+  set(RSTDOC_DIR "${PACKAGE_OTB_SRC_DIR}/Documentation/Cookbook/rst")
+  if(APPLE)
+    set(README_FILE ${RSTDOC_DIR}/Installation_Macx.txt)
+  elseif(LINUX) #not osx
+    set(README_FILE ${RSTDOC_DIR}/Installation_Linux.txt)
+  elseif(WIN32) #windows
+    set(README_FILE ${RSTDOC_DIR}/Installation_Windows.txt)
+  endif()
+  configure_file("${README_FILE}" ${CMAKE_BINARY_DIR}/README )
+  install(FILES ${CMAKE_BINARY_DIR}/README DESTINATION ${PKG_STAGE_DIR} )
+
+  
+  #configure pkgsetup for mac and linux
+  if(LINUX)
+    configure_file(
+      ${CMAKE_CURRENT_SOURCE_DIR}/Files/linux_pkgsetup.in
+      ${CMAKE_CURRENT_BINARY_DIR}/pkgsetup @ONLY
+      )
+  endif()
+
+  if(APPLE)
+    set(ORIGINAL_RPATH_TO_REPLACE ${SUPERBUILD_INSTALL_DIR}/lib)
+    configure_file(
+      ${CMAKE_CURRENT_SOURCE_DIR}/Files/macx_pkgsetup.in
+      ${CMAKE_CURRENT_BINARY_DIR}/pkgsetup @ONLY
+      )
+
+    #install icon file for .app file. Monteverdi and Mapla has same icon!
+    install(FILES
+      Files/Monteverdi.icns DESTINATION ${PKG_STAGE_DIR})
+  endif()
+
+  #start installing script and other stuff related to package
+  if(UNIX)
+    install( PROGRAMS
+      ${CMAKE_BINARY_DIR}/pkgsetup
+      ${CMAKE_BINARY_DIR}/make_symlinks
+      Files/setup_python.sh
+      Files/otbenv.profile
+      DESTINATION ${PKG_STAGE_DIR}
+      )
+  endif()
+
+  # We also need wrapper script to start mapla & monteverdi
+  #if(NOT HAVE_MVD)
+  #  message(FATAL_ERROR "not have mvd")
+  #endif()
+  if(HAVE_MVD)
+    install(PROGRAMS
+      Files/mapla${SCRIPT_EXT}
+      Files/monteverdi${SCRIPT_EXT}
+      DESTINATION ${PKG_STAGE_DIR}
+      )
+
+    #for mac osx, we have a template.app which is
+    # later processed in pkgsetup (macx_pkgsetup.in)
+    if(APPLE)
+      install(DIRECTORY Files/template.app
+	DESTINATION "${PKG_STAGE_DIR}")
+    endif()
+  endif() #HAVE_MVD
+
+  #my_file_ext is required for otbcli and otbgui files which has
+  # no extension on linux. (hence we cannot use SCRIPT_EXT
+
+  #For windows otbenv.bash and otbenv.bat is required.
+  # Former is for windows shell users and latter is for other
+  # linux emulator such as bash for windows or mobxterm
+  set(my_file_ext "")
+  if(WIN32)
+    set(my_file_ext ".bat")
+    install( PROGRAMS
+      Files/otbenv.bat
+      Files/otbenv.bash
+      DESTINATION ${PKG_STAGE_DIR}
+      )
+  endif()
+
+  #these scripts are not auto-installed in PKG_STAGE_DIR
+  #could this be move them to somewhere else?
+  install(PROGRAMS
+    "${SUPERBUILD_INSTALL_DIR}/bin/otbcli${my_file_ext}"
+    "${SUPERBUILD_INSTALL_DIR}/bin/otbgui${my_file_ext}"
+    DESTINATION ${PKG_STAGE_DIR}/bin)
+
+  install(PROGRAMS
+    Files/selftester${SCRIPT_EXT}
+    Files/uninstall_otb${SCRIPT_EXT}
+    DESTINATION ${PKG_STAGE_DIR}/tools)
+
+  # only required for linux.
+  # THIS WILL BE REMOVED ONCE INSTALLATION IS DONE
+  # USE --noexec option when running .run file to keep this file
+  # along with other installation files
+  if(LINUX)
+    install(PROGRAMS
+      "${PATCHELF_PROGRAM}"
+      DESTINATION ${PKG_STAGE_DIR})
+  endif()
+
+  install(FILES
+    Files/build_examples.cmake
+    DESTINATION ${PKG_STAGE_DIR}/tools)
+
+  
+  #add otb_loader
+  add_executable(otb_loader ${CMAKE_CURRENT_SOURCE_DIR}/Files/otb_loader.cxx)
+  target_link_libraries(otb_loader ${CMAKE_DL_LIBS})
+  install(TARGETS otb_loader DESTINATION ${PKG_STAGE_DIR}/tools)
+  add_dependencies(otb_loader PATCHELF)
+endmacro()
diff --git a/Packaging/isfile_symlink.cmake b/Packaging/isfile_symlink.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..0d3b490d6bf866d6780cc9ec69eda1535c90f588
--- /dev/null
+++ b/Packaging/isfile_symlink.cmake
@@ -0,0 +1,89 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(isfile_symlink file result_var1 result_var2)
+  #
+  # A file is not executable until proven otherwise:
+  #
+  set(${result_var1} 0 PARENT_SCOPE)
+  set(${result_var2} "" PARENT_SCOPE)
+
+  get_filename_component(file_full "${file}" ABSOLUTE)
+  string(TOLOWER "${file_full}" file_full_lower)
+
+  # If file name ends in .lnk on Windows,
+  # *assume* symlink a.k.a shortcut.
+  #
+  if(WIN32 AND NOT UNIX)
+    if("${file_full_lower}" MATCHES "\\.lnk$")
+      set(${result_var1} 1 PARENT_SCOPE)
+      #Assuming the file is linked to a file
+      #with same name without .lnk extension
+      get_filename_component(file_full_name_we "${file_full}" NAME_WE)
+      set(${result_var2} "${file_full_name_we}" PARENT_SCOPE)
+      return()
+    endif()
+
+    # A clause could be added here that uses output or return value of dumpbin
+    # to determine ${result_var}. In 99%+? practical cases, the exe name
+    # match will be sufficient...
+    #
+  endif()
+
+  #if we are not on a unix or unix-like platform,
+  #then we don't have any business after this line.
+  if(NOT UNIX)
+    return()
+  endif()
+
+  # Use the information returned from the Unix shell command "file" to
+  # determine if ${file_full} should be considered an executable file...
+  #
+  # If the file command's output contains "executable" and does *not* contain
+  # "text" then it is likely an executable suitable for prerequisite analysis
+  # via the get_prerequisites macro.
+  
+  execute_process(COMMAND "${READLINK}" "${file_full}"
+    RESULT_VARIABLE readlink_rv
+    OUTPUT_VARIABLE readlink_ov
+    ERROR_VARIABLE readlink_ev
+    OUTPUT_STRIP_TRAILING_WHITESPACE
+    )
+
+  if(PKG_DEBUG)
+    message("${READLINK} on '${file_full} has output: '${readlink_ov}'\nreadlink_ev=${readlink_ev}")
+  endif()
+  
+  if(readlink_rv STREQUAL "1")
+    set(${result_var1} 0 PARENT_SCOPE)
+    set(${result_var2} "" PARENT_SCOPE)
+    return()
+  endif()
+
+  #got a symlink!. set result_var1 to TRUE
+  set(${result_var1} 1 PARENT_SCOPE)
+
+  #Now get the resolved link to result_var2
+  set(symlinked_to)
+  string(STRIP ${readlink_ov} symlinked_to)
+  set(${result_var2} "${symlinked_to}" PARENT_SCOPE)
+
+  return()
+
+endfunction()
diff --git a/Packaging/makeself/COPYING b/Packaging/makeself/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..d159169d1050894d3ea3b98e1c965c4058208fe1
--- /dev/null
+++ b/Packaging/makeself/COPYING
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/Packaging/makeself/README.md b/Packaging/makeself/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..04b9de80bbc0a71f0d1df86bd7453f1019704c36
--- /dev/null
+++ b/Packaging/makeself/README.md
@@ -0,0 +1,220 @@
+[![AUR](https://img.shields.io/aur/license/yaourt.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html)
+[![Build Status](https://travis-ci.org/megastep/makeself.svg?branch=master)](https://travis-ci.org/megastep/makeself)
+
+# makeself - Make self-extractable archives on Unix
+
+[makeself.sh][1] is a small shell script that generates a self-extractable
+compressed tar archive from a directory. The resulting file appears as a shell script
+(many of those have a **.run** suffix), and can be launched as is. The archive
+will then uncompress itself to a temporary directory and an optional arbitrary
+command will be executed (for example an installation script). This is pretty
+similar to archives generated with WinZip Self-Extractor in the Windows world.
+Makeself archives also include checksums for integrity self-validation (CRC
+and/or MD5 checksums).
+
+The makeself.sh script itself is used only to create the archives from a
+directory of files. The resultant archive is actually a compressed (using
+gzip, bzip2, or compress) TAR archive, with a small shell script stub at the
+beginning. This small stub performs all the steps of extracting the files,
+running the embedded command, and removing the temporary files when done.
+All the user has to do to install the software contained in such an
+archive is to "run" the archive, i.e **sh nice-software.run**. I recommend
+using the ".run" (which was introduced by some Makeself archives released by
+Loki Software) or ".sh" suffix for such archives not to confuse the users,
+so that they will know they are actually shell scripts (with quite a lot of binary data
+attached to them though!).
+
+I am trying to keep the code of this script as portable as possible, i.e it is
+not relying on any bash-specific features and only calls commands that are
+installed on any functioning UNIX-compatible system. This script as well as
+the archives it generates should run on any Unix flavor, with any compatible
+Bourne shell, provided of course that the compression programs are available.
+
+As of version 2.1, Makeself has been rewritten and tested on the following
+platforms :
+
+  * Linux (all distributions)
+  * Sun Solaris (8 and above)
+  * HP-UX (tested on 11.0 and 11i on HPPA RISC)
+  * SCO OpenUnix and OpenServer
+  * IBM AIX 5.1L
+  * macOS (Darwin)
+  * SGI IRIX 6.5
+  * FreeBSD
+  * UnicOS / Cray
+  * Cygwin (Windows)
+
+If you successfully run Makeself and/or archives created with it on another
+system, then please [let me know][2]!
+
+Examples of publicly available archives made using makeself are :
+
+  * Game patches and installers for [Id Software][3] games like Quake 3 for Linux or Return To Castle Wolfenstein ;
+  * All game patches released by [Loki Software][4] for the Linux version of popular games ;
+  * The [nVidia drivers][5] for Linux
+  * The installer for the Linux version of [Google Earth][6]
+  * The [VirtualBox][7] installers for Linux
+  * The [Makeself][1] distribution itself ;-)
+  * and countless others...
+
+**Important note for Apache users:** By default, most Web servers will think that Makeself archives are regular text files and thus they may show up as text in a Web browser. The correct way to prevent this is to add a MIME type for this file format, like so (in httpd.conf) :
+
+`AddType application/x-makeself .run`
+
+**Important note for certain GNU/Linux distributions:** Archives created with Makeself prior to v2.1.2 were using an old syntax for the _head_ and _tail_ Unix commands that is being progressively obsoleted in their GNU forms. Therefore you may have problems uncompressing some of these archives. A workaround for this is to set the environment variable $_POSIX2_VERSION to enable the old syntax, i.e. :
+
+`export _POSIX2_VERSION=199209`
+
+## Usage
+
+The syntax of makeself is the following:
+
+```
+makeself.sh [args] archive_dir file_name label startup_script [script_args]
+```
+
+  * _args_ are optional options for Makeself. The available ones are :
+
+    * **--version** : Prints the version number on stdout, then exits immediately
+    * **--gzip** : Use gzip for compression (the default on platforms on which gzip is commonly available, like Linux)
+    * **--bzip2** : Use bzip2 instead of gzip for better compression. The bzip2 command must be available in the command path. It is recommended that the archive prefix be set to something like '.bz2.run', so that potential users know that they'll need bzip2 to extract it.
+    * **--pbzip2** : Use pbzip2 instead of gzip for better and faster compression on machines having multiple CPUs. The pbzip2 command must be available in the command path. It is recommended that the archive prefix be set to something like '.bz2.run', so that potential users know that they'll need bzip2 to extract it.
+    * **--xz** : Use xz instead of gzip for better compression. The xz command must be available in the command path. It is recommended that the archive prefix be set to something like '.xz.run' for the archive, so that potential users know that they'll need xz to extract it.
+    * **--lzo** : Use lzop instead of gzip for better compression. The lzop command must be available in the command path. It is recommended that the archive prefix be set to something like '.lzo.run' for the archive, so that potential users know that they'll need lzop to extract it.
+    * **--lz4** : Use lz4 instead of gzip for better compression. The lz4 command must be available in the command path. It is recommended that the archive prefix be set to something like '.lz4.run' for the archive, so that potential users know that they'll need lz4 to extract it.
+    * **--pigz** : Use pigz for compression.
+    * **--base64** : Encode the archive to ASCII in Base64 format instead of compressing (base64 command required).
+    * **--gpg-encrypt** : Encrypt the archive using `gpg -ac -z $COMPRESS_LEVEL`. This will prompt for a password to encrypt with. Assumes that potential users have `gpg` installed.
+    * **--ssl-encrypt** : Encrypt the archive using `openssl aes-256-cbc -a -salt`. This will prompt for a password to encrypt with. Assumes that the potential users have the OpenSSL tools installed.
+    * **--compress** : Use the UNIX `compress` command to compress the data. This should be the default on all platforms that don't have gzip available.
+    * **--nocomp** : Do not use any compression for the archive, which will then be an uncompressed TAR.
+    * **--complevel** : Specify the compression level for gzip, bzip2, pbzip2, xz, lzo or lz4. (defaults to 9)
+    * **--notemp** : The generated archive will not extract the files to a temporary directory, but in a new directory created in the current directory. This is better to distribute software packages that may extract and compile by themselves (i.e. launch the compilation through the embedded script).
+    * **--current** : Files will be extracted to the current directory, instead of in a subdirectory. This option implies `--notemp` above.
+    * **--follow** : Follow the symbolic links inside of the archive directory, i.e. store the files that are being pointed to instead of the links themselves.
+    * **--append** _(new in 2.1.x)_: Append data to an existing archive, instead of creating a new one. In this mode, the settings from the original archive are reused (compression type, label, embedded script), and thus don't need to be specified again on the command line.
+    * **--header** : Makeself 2.0 uses a separate file to store the header stub, called `makeself-header.sh`. By default, it is assumed that it is stored in the same location as makeself.sh. This option can be used to specify its actual location if it is stored someplace else.
+    * **--copy** : Upon extraction, the archive will first extract itself to a temporary directory. The main application of this is to allow self-contained installers stored in a Makeself archive on a CD, when the installer program will later need to unmount the CD and allow a new one to be inserted. This prevents "Filesystem busy" errors for installers that span multiple CDs.
+    * **--nox11** : Disable the automatic spawning of a new terminal in X11.
+    * **--nowait** : When executed from a new X11 terminal, disable the user prompt at the end of the script execution.
+    * **--nomd5** and **--nocrc** : Disable the creation of a MD5 / CRC checksum for the archive. This speeds up the extraction process if integrity checking is not necessary.
+    * **--lsm _file_** : Provide and LSM file to makeself, that will be embedded in the generated archive. LSM files are describing a software package in a way that is easily parseable. The LSM entry can then be later retrieved using the `--lsm` argument to the archive. An example of a LSM file is provided with Makeself.
+    * **--tar-extra opt** : Append more options to the tar command line.
+
+        For instance, in order to exclude the `.git` directory from the packaged archive directory using the GNU `tar`, one can use `makeself.sh --tar-extra "--exclude=.git" ...`
+
+    * **--keep-umask** : Keep the umask set to shell default, rather than overriding when executing self-extracting archive.
+    * **--packaging-date date** : Use provided string as the packaging date instead of the current date.
+    * **--license** : Append a license file.
+    * **--nooverwrite** : Do not extract the archive if the specified target directory already exists.
+    * **--header file** : Specify the location of the header script file (default `makeself-header.sh`)
+    * **--help-header file** : Add a header to the archive's `--help` output.
+  * _archive_dir_ is the name of the directory that contains the files to be archived
+  * _file_name_ is the name of the archive to be created
+  * _label_ is an arbitrary text string describing the package. It will be displayed while extracting the files.
+  * _startup_script_ is the command to be executed _from within_ the directory of extracted files. Thus, if you wish to execute a program contain in this directory, you must prefix your command with `./`. For example, `./program` will be fine. The _script_args_ are additionnal arguments for this command.
+
+Here is an example, assuming the user has a package image stored in a **/home/joe/mysoft**, and he wants to generate a self-extracting package named
+**mysoft.sh**, which will launch the "setup" script initially stored in /home/joe/mysoft :
+
+`makeself.sh /home/joe/mysoft mysoft.sh "Joe's Nice Software Package" ./setup
+`
+
+Here is also how I created the [makeself.run][9] archive which contains the Makeself distribution :
+
+`makeself.sh --notemp makeself makeself.run "Makeself by Stephane Peter" echo "Makeself has extracted itself" `
+
+Archives generated with Makeself can be passed the following arguments:
+
+  * _--keep_ : Prevent the files to be extracted in a temporary directory that will be removed after the embedded script's execution. The files will then be extracted in the current working directory and will stay here until you remove them.
+  * _--verbose_ : Will prompt the user before executing the embedded command
+  * _--target dir_ : Allows to extract the archive in an arbitrary place.
+  * _--nox11_ : Do not spawn a X11 terminal.
+  * _--confirm_ : Prompt the user for confirmation before running the embedded command.
+  * _--info_ : Print out general information about the archive (does not extract).
+  * _--lsm_ : Print out the LSM entry, if it is present.
+  * _--list_ : List the files in the archive.
+  * _--check_ : Check the archive for integrity using the embedded checksums. Does not extract the archive.
+  * _--nochown_ : By default, a `chown -R` command is run on the target directory after extraction, so that all files belong to the current user. This is mostly needed if you are running as root, as tar will then try to recreate the initial user ownerships. You may disable this behavior with this flag.
+  * _--tar_ : Run the tar command on the contents of the archive, using the following arguments as parameter for the command.
+  * _--noexec_ : Do not run the embedded script after extraction.
+  * _--nodiskspace_ : Do not check for available disk space before attempting to extract.
+
+Any subsequent arguments to the archive will be passed as additional arguments to the embedded command. You must explicitly use the _--_ special command-line construct before any such options to make sure that Makeself will not try to interpret them.
+
+## Maven Usage
+
+Makeself is now supported by the following maven plugin [makeself-maven-plugin](https://github.com/hazendaz/makeself-maven-plugin).  Please refer to project for usage and report any bugs in regards to maven plugin on that project.
+
+## License
+
+Makeself is covered by the [GNU General Public License][8] (GPL) version 2 and above. Archives generated by Makeself don't have to be placed under this license (although I encourage it ;-)), since the archive itself is merely data for Makeself.
+
+## Contributing
+
+I will gladly consider merging your pull requests on the [GitHub][10] repository. However, please keep the following in mind:
+
+  * One of the main purposes of Makeself is portability. Do not submit patches that will break supported platforms. The more platform-agnostic, the better.
+  * Please explain clearly what the purpose of the patch is, and how you achieved it.
+
+## Download
+
+Get the latest official distribution [here][9] (version 2.3.1).
+
+The latest development version can be grabbed from [GitHub][10]. Feel free to submit any patches there through the fork and pull request process.
+
+## Version history
+
+  * **v1.0:** Initial public release
+  * **v1.1:** The archive can be passed parameters that will be passed on to the embedded script, thanks to John C. Quillan
+  * **v1.2:** Cosmetic updates, support for bzip2 compression and non-temporary archives. Many ideas thanks to Francois Petitjean.
+  * **v1.3:** More patches from Bjarni R. Einarsson and Francois Petitjean: Support for no compression (--nocomp), script is no longer mandatory, automatic launch in an xterm, optional verbose output, and -target archive option to indicate where to extract the files.
+  * **v1.4:** Many patches from Francois Petitjean: improved UNIX compatibility, automatic integrity checking, support of LSM files to get info on the package at run time..
+  * **v1.5.x:** A lot of bugfixes, and many other patches, including automatic verification through the usage of checksums. Version 1.5.5 was the stable release for a long time, even though the Web page didn't get updated ;-). Makeself was also officially made a part of the [Loki Setup installer][11], and its source is being maintained as part of this package.
+  * **v2.0:** Complete internal rewrite of Makeself. The command-line parsing was vastly improved, the overall maintenance of the package was greatly improved by separating the stub from makeself.sh. Also Makeself was ported and tested to a variety of Unix platforms.
+  * **v2.0.1:** First public release of the new 2.0 branch. Prior versions are officially obsoleted. This release introduced the '--copy' argument that was introduced in response to a need for the [UT2K3][12] Linux installer.
+  * **v2.1.0:** Big change : Makeself can now support multiple embedded tarballs, each stored separately with their own checksums. An existing archive can be updated with the --append flag. Checksums are also better managed, and the --nochown option for archives appeared.
+  * **v2.1.1:** Fixes related to the Unix compression (compress command). Some Linux distributions made the insane choice to make it unavailable, even though gzip is capable of uncompressing these files, plus some more bugfixes in the extraction and checksum code.
+  * **v2.1.2:** Some bug fixes. Use head -n to avoid problems with POSIX conformance.
+  * **v2.1.3:** Bug fixes with the command line when spawning terminals. Added --tar, --noexec for archives. Added --nomd5 and --nocrc to avoid creating checksums in archives. The embedded script is now run through "eval". The --info output now includes the command used to create the archive. A man page was contributed by Bartosz Fenski.
+  * **v2.1.4:** Fixed --info output. Generate random directory name when extracting files to . to avoid problems. Better handling of errors with wrong permissions for the directory containing the files. Avoid some race conditions, Unset the $CDPATH variable to avoid problems if it is set. Better handling of dot files in the archive directory.
+  * **v2.1.5:** Made the md5sum detection consistent with the header code. Check for the presence of the archive directory. Added --encrypt for symmetric encryption through gpg (Eric Windisch). Added support for the digest command on Solaris 10 for MD5 checksums. Check for available disk space before extracting to the target directory (Andreas Schweitzer). Allow extraction to run asynchronously (patch by Peter Hatch). Use file descriptors internally to avoid error messages (patch by Kay Tiong Khoo).
+  * **v2.1.6:** Replaced one dot per file progress with a realtime progress percentage and a spining cursor. Added --noprogress to prevent showing the progress during the decompression. Added --target dir to allow extracting directly to a target directory. (Guy Baconniere)
+  * **v2.2.0:** First major new release in years! Includes many bugfixes and user contributions. Please look at the [project page on Github][10] for all the details.
+  * **v2.3.0:** Support for archive encryption via GPG or OpenSSL. Added LZO and LZ4 compression support. Options to set the packaging date and stop the umask from being overriden. Optionally ignore check for available disk space when extracting. New option to check for root permissions before extracting.
+  * **v2.3.1:** Various compatibility updates. Added unit tests for Travis CI in the GitHub repo. New --tar-extra, --untar-extra, --gpg-extra, --gpg-asymmetric-encrypt-sign options.
+
+## Links
+
+  * Check out the ["Loki Setup"][11] installer, used to install many Linux games and other applications, and of which I am the co-author. Since the demise of Loki, I am now the official maintainer of the project, and it is now being hosted here on GitHub.
+  * Bjarni R. Einarsson also wrote the **setup.sh** installer script, inspired by Makeself. [Check it out !][14]
+
+## Contact
+
+This script was written by [Stéphane Peter][15] (megastep at megastep.org). Any enhancements and suggestions are welcome.
+
+Contributions were included from John C. Quillan, Bjarni R. Einarsson,
+Francois Petitjean, Ryan C. Gordon, and many contributors on GitHub. If you think I forgot
+your name, don't hesitate to contact me.
+
+This project is now hosted on GitHub. Feel free to submit patches and bug reports on the [project page][10].
+
+* * *
+
+[Stephane Peter][2]
+
+   [1]: http://makeself.io/
+   [2]: mailto:megastep@megastep.org
+   [3]: http://www.idsoftware.com/
+   [4]: http://www.lokigames.com/products/myth2/updates.php3
+   [5]: http://www.nvidia.com/
+   [6]: http://earth.google.com/
+   [7]: http://www.virtualbox.org/
+   [8]: http://www.gnu.org/copyleft/gpl.html
+   [9]: https://github.com/megastep/makeself/releases/download/release-2.3.1/makeself-2.3.1.run
+   [10]: https://github.com/megastep/makeself
+   [11]: https://github.com/megastep/loki_setup/
+   [12]: http://www.unrealtournament2003.com/
+   [13]: http://www.icculus.org/
+   [14]: http://bre.klaki.net/programs/setup.sh/
+   [15]: https://stephanepeter.com/
diff --git a/Packaging/makeself/makeself-header.sh b/Packaging/makeself/makeself-header.sh
new file mode 100755
index 0000000000000000000000000000000000000000..83131a17c261c94746da9df54c754ccb4f4b10ab
--- /dev/null
+++ b/Packaging/makeself/makeself-header.sh
@@ -0,0 +1,553 @@
+cat << EOF  > "$archname"
+#!/bin/sh
+# This script was generated using Makeself $MS_VERSION
+
+ORIG_UMASK=\`umask\`
+if test "$KEEP_UMASK" = n; then
+    umask 077
+fi
+
+CRCsum="$CRCsum"
+MD5="$MD5sum"
+TMPROOT=\${TMPDIR:=/tmp}
+USER_PWD="\$PWD"; export USER_PWD
+
+label="$LABEL"
+script="$SCRIPT"
+scriptargs="$SCRIPTARGS"
+licensetxt="$LICENSE"
+helpheader='$HELPHEADER'
+targetdir="$archdirname"
+filesizes="$filesizes"
+keep="$KEEP"
+nooverwrite="$NOOVERWRITE"
+quiet="n"
+accept="n"
+nodiskspace="n"
+export_conf="$EXPORT_CONF"
+
+print_cmd_arg=""
+if type printf > /dev/null; then
+    print_cmd="printf"
+elif test -x /usr/ucb/echo; then
+    print_cmd="/usr/ucb/echo"
+else
+    print_cmd="echo"
+fi
+	
+if test -d /usr/xpg4/bin; then
+    PATH=/usr/xpg4/bin:\$PATH
+    export PATH
+fi
+
+unset CDPATH
+
+MS_Printf()
+{
+    \$print_cmd \$print_cmd_arg "\$1"
+}
+
+MS_PrintLicense()
+{
+  if test x"\$licensetxt" != x; then
+    echo "\$licensetxt"
+    if test x"\$accept" != xy; then
+      while true
+      do
+        MS_Printf "Please type y to accept, n otherwise: "
+        read yn
+        if test x"\$yn" = xn; then
+          keep=n
+          eval \$finish; exit 1
+          break;
+        elif test x"\$yn" = xy; then
+          break;
+        fi
+      done
+    fi
+  fi
+}
+
+MS_diskspace()
+{
+	(
+	df -kP "\$1" | tail -1 | awk '{ if (\$4 ~ /%/) {print \$3} else {print \$4} }'
+	)
+}
+
+MS_dd()
+{
+    blocks=\`expr \$3 / 1024\`
+    bytes=\`expr \$3 % 1024\`
+    dd if="\$1" ibs=\$2 skip=1 obs=1024 conv=sync 2> /dev/null | \\
+    { test \$blocks -gt 0 && dd ibs=1024 obs=1024 count=\$blocks ; \\
+      test \$bytes  -gt 0 && dd ibs=1 obs=1024 count=\$bytes ; } 2> /dev/null
+}
+
+MS_dd_Progress()
+{
+    if test x"\$noprogress" = xy; then
+        MS_dd \$@
+        return \$?
+    fi
+    file="\$1"
+    offset=\$2
+    length=\$3
+    pos=0
+    bsize=4194304
+    while test \$bsize -gt \$length; do
+        bsize=\`expr \$bsize / 4\`
+    done
+    blocks=\`expr \$length / \$bsize\`
+    bytes=\`expr \$length % \$bsize\`
+    (
+        dd ibs=\$offset skip=1 2>/dev/null
+        pos=\`expr \$pos \+ \$bsize\`
+        MS_Printf "     0%% " 1>&2
+        if test \$blocks -gt 0; then
+            while test \$pos -le \$length; do
+                dd bs=\$bsize count=1 2>/dev/null
+                pcent=\`expr \$length / 100\`
+                pcent=\`expr \$pos / \$pcent\`
+                if test \$pcent -lt 100; then
+                    MS_Printf "\b\b\b\b\b\b\b" 1>&2
+                    if test \$pcent -lt 10; then
+                        MS_Printf "    \$pcent%% " 1>&2
+                    else
+                        MS_Printf "   \$pcent%% " 1>&2
+                    fi
+                fi
+                pos=\`expr \$pos \+ \$bsize\`
+            done
+        fi
+        if test \$bytes -gt 0; then
+            dd bs=\$bytes count=1 2>/dev/null
+        fi
+        MS_Printf "\b\b\b\b\b\b\b" 1>&2
+        MS_Printf " 100%%  " 1>&2
+    ) < "\$file"
+}
+
+MS_Help()
+{
+    cat << EOH >&2
+\${helpheader}Makeself version $MS_VERSION
+ 1) Getting help or info about \$0 :
+  \$0 --help   Print this message
+  \$0 --info   Print embedded info : title, default target directory, embedded script ...
+  \$0 --lsm    Print embedded lsm entry (or no LSM)
+  \$0 --list   Print the list of files in the archive
+  \$0 --check  Checks integrity of the archive
+
+ 2) Running \$0 :
+  \$0 [options] [--] [additional arguments to embedded script]
+  with following options (in that order)
+  --confirm             Ask before running embedded script
+  --quiet		Do not print anything except error messages
+  --accept              Accept the license
+  --noexec              Do not run embedded script
+  --keep                Do not erase target directory after running
+			the embedded script
+  --noprogress          Do not show the progress during the decompression
+  --nox11               Do not spawn an xterm
+  --nochown             Do not give the extracted files to the current user
+  --nodiskspace         Do not check for available disk space
+  --target dir          Extract directly to a target directory
+                        directory path can be either absolute or relative
+  --tar arg1 [arg2 ...] Access the contents of the archive through the tar command
+  --                    Following arguments will be passed to the embedded script
+EOH
+}
+
+MS_Check()
+{
+    OLD_PATH="\$PATH"
+    PATH=\${GUESS_MD5_PATH:-"\$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
+	MD5_ARG=""
+    MD5_PATH=\`exec <&- 2>&-; which md5sum || command -v md5sum || type md5sum\`
+    test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which md5 || command -v md5 || type md5\`
+	test -x "\$MD5_PATH" || MD5_PATH=\`exec <&- 2>&-; which digest || command -v digest || type digest\`
+    PATH="\$OLD_PATH"
+
+    if test x"\$quiet" = xn; then
+		MS_Printf "Verifying archive integrity..."
+    fi
+    offset=\`head -n $SKIP "\$1" | wc -c | tr -d " "\`
+    verb=\$2
+    i=1
+    for s in \$filesizes
+    do
+		crc=\`echo \$CRCsum | cut -d" " -f\$i\`
+		if test -x "\$MD5_PATH"; then
+			if test x"\`basename \$MD5_PATH\`" = xdigest; then
+				MD5_ARG="-a md5"
+			fi
+			md5=\`echo \$MD5 | cut -d" " -f\$i\`
+			if test x"\$md5" = x00000000000000000000000000000000; then
+				test x"\$verb" = xy && echo " \$1 does not contain an embedded MD5 checksum." >&2
+			else
+				md5sum=\`MS_dd_Progress "\$1" \$offset \$s | eval "\$MD5_PATH \$MD5_ARG" | cut -b-32\`;
+				if test x"\$md5sum" != x"\$md5"; then
+					echo "Error in MD5 checksums: \$md5sum is different from \$md5" >&2
+					exit 2
+				else
+					test x"\$verb" = xy && MS_Printf " MD5 checksums are OK." >&2
+				fi
+				crc="0000000000"; verb=n
+			fi
+		fi
+		if test x"\$crc" = x0000000000; then
+			test x"\$verb" = xy && echo " \$1 does not contain a CRC checksum." >&2
+		else
+			sum1=\`MS_dd_Progress "\$1" \$offset \$s | CMD_ENV=xpg4 cksum | awk '{print \$1}'\`
+			if test x"\$sum1" = x"\$crc"; then
+				test x"\$verb" = xy && MS_Printf " CRC checksums are OK." >&2
+			else
+				echo "Error in checksums: \$sum1 is different from \$crc" >&2
+				exit 2;
+			fi
+		fi
+		i=\`expr \$i + 1\`
+		offset=\`expr \$offset + \$s\`
+    done
+    if test x"\$quiet" = xn; then
+		echo " All good."
+    fi
+}
+
+UnTAR()
+{
+    if test x"\$quiet" = xn; then
+		tar \$1vf - $UNTAR_EXTRA 2>&1 || { echo " ... Extraction failed." > /dev/tty; kill -15 \$$; }
+    else
+		tar \$1f - $UNTAR_EXTRA 2>&1 || { echo Extraction failed. > /dev/tty; kill -15 \$$; }
+    fi
+}
+
+finish=true
+xterm_loop=
+noprogress=$NOPROGRESS
+nox11=$NOX11
+copy=$COPY
+ownership=y
+verbose=n
+
+initargs="\$@"
+
+while true
+do
+    case "\$1" in
+    -h | --help)
+	MS_Help
+	exit 0
+	;;
+    -q | --quiet)
+	quiet=y
+	noprogress=y
+	shift
+	;;
+	--accept)
+	accept=y
+	shift
+	;;
+    --info)
+	echo Identification: "\$label"
+	echo Target directory: "\$targetdir"
+	echo Uncompressed size: $USIZE KB
+	echo Compression: $COMPRESS
+	echo Date of packaging: $DATE
+	echo Built with Makeself version $MS_VERSION on $OSTYPE
+	echo Build command was: "$MS_COMMAND"
+	if test x"\$script" != x; then
+	    echo Script run after extraction:
+	    echo "    " \$script \$scriptargs
+	fi
+	if test x"$copy" = xcopy; then
+		echo "Archive will copy itself to a temporary location"
+	fi
+	if test x"$NEED_ROOT" = xy; then
+		echo "Root permissions required for extraction"
+	fi
+	if test x"$KEEP" = xy; then
+	    echo "directory \$targetdir is permanent"
+	else
+	    echo "\$targetdir will be removed after extraction"
+	fi
+	exit 0
+	;;
+    --dumpconf)
+	echo LABEL=\"\$label\"
+	echo SCRIPT=\"\$script\"
+	echo SCRIPTARGS=\"\$scriptargs\"
+	echo archdirname=\"$archdirname\"
+	echo KEEP=$KEEP
+	echo NOOVERWRITE=$NOOVERWRITE
+	echo COMPRESS=$COMPRESS
+	echo filesizes=\"\$filesizes\"
+	echo CRCsum=\"\$CRCsum\"
+	echo MD5sum=\"\$MD5\"
+	echo OLDUSIZE=$USIZE
+	echo OLDSKIP=`expr $SKIP + 1`
+	exit 0
+	;;
+    --lsm)
+cat << EOLSM
+EOF
+eval "$LSM_CMD"
+cat << EOF  >> "$archname"
+EOLSM
+	exit 0
+	;;
+    --list)
+	echo Target directory: \$targetdir
+	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+	for s in \$filesizes
+	do
+	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | UnTAR t
+	    offset=\`expr \$offset + \$s\`
+	done
+	exit 0
+	;;
+	--tar)
+	offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+	arg1="\$2"
+    if ! shift 2; then MS_Help; exit 1; fi
+	for s in \$filesizes
+	do
+	    MS_dd "\$0" \$offset \$s | eval "$GUNZIP_CMD" | tar "\$arg1" - "\$@"
+	    offset=\`expr \$offset + \$s\`
+	done
+	exit 0
+	;;
+    --check)
+	MS_Check "\$0" y
+	exit 0
+	;;
+    --confirm)
+	verbose=y
+	shift
+	;;
+	--noexec)
+	script=""
+	shift
+	;;
+    --keep)
+	keep=y
+	shift
+	;;
+    --target)
+	keep=y
+	targetdir=\${2:-.}
+    if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --noprogress)
+	noprogress=y
+	shift
+	;;
+    --nox11)
+	nox11=y
+	shift
+	;;
+    --nochown)
+	ownership=n
+	shift
+	;;
+    --nodiskspace)
+	nodiskspace=y
+	shift
+	;;
+    --xwin)
+	if test "$NOWAIT" = n; then
+		finish="echo Press Return to close this window...; read junk"
+	fi
+	xterm_loop=1
+	shift
+	;;
+    --phase2)
+	copy=phase2
+	shift
+	;;
+    --)
+	shift
+	break ;;
+    -*)
+	echo Unrecognized flag : "\$1" >&2
+	MS_Help
+	exit 1
+	;;
+    *)
+	break ;;
+    esac
+done
+
+if test x"\$quiet" = xy -a x"\$verbose" = xy; then
+	echo Cannot be verbose and quiet at the same time. >&2
+	exit 1
+fi
+
+if test x"$NEED_ROOT" = xy -a \`id -u\` -ne 0; then
+	echo "Administrative privileges required for this archive (use su or sudo)" >&2
+	exit 1	
+fi
+
+if test x"\$copy" \!= xphase2; then
+    MS_PrintLicense
+fi
+
+case "\$copy" in
+copy)
+    tmpdir=\$TMPROOT/makeself.\$RANDOM.\`date +"%y%m%d%H%M%S"\`.\$\$
+    mkdir "\$tmpdir" || {
+	echo "Could not create temporary directory \$tmpdir" >&2
+	exit 1
+    }
+    SCRIPT_COPY="\$tmpdir/makeself"
+    echo "Copying to a temporary location..." >&2
+    cp "\$0" "\$SCRIPT_COPY"
+    chmod +x "\$SCRIPT_COPY"
+    cd "\$TMPROOT"
+    exec "\$SCRIPT_COPY" --phase2 -- \$initargs
+    ;;
+phase2)
+    finish="\$finish ; rm -rf \`dirname \$0\`"
+    ;;
+esac
+
+if test x"\$nox11" = xn; then
+    if tty -s; then                 # Do we have a terminal?
+	:
+    else
+        if test x"\$DISPLAY" != x -a x"\$xterm_loop" = x; then  # No, but do we have X?
+            if xset q > /dev/null 2>&1; then # Check for valid DISPLAY variable
+                GUESS_XTERMS="xterm gnome-terminal rxvt dtterm eterm Eterm xfce4-terminal lxterminal kvt konsole aterm terminology"
+                for a in \$GUESS_XTERMS; do
+                    if type \$a >/dev/null 2>&1; then
+                        XTERM=\$a
+                        break
+                    fi
+                done
+                chmod a+x \$0 || echo Please add execution rights on \$0
+                if test \`echo "\$0" | cut -c1\` = "/"; then # Spawn a terminal!
+                    exec \$XTERM -title "\$label" -e "\$0" --xwin "\$initargs"
+                else
+                    exec \$XTERM -title "\$label" -e "./\$0" --xwin "\$initargs"
+                fi
+            fi
+        fi
+    fi
+fi
+
+if test x"\$targetdir" = x.; then
+    tmpdir="."
+else
+    if test x"\$keep" = xy; then
+	if test x"\$nooverwrite" = xy && test -d "\$targetdir"; then
+            echo "Target directory \$targetdir already exists, aborting." >&2
+            exit 1
+	fi
+	if test x"\$quiet" = xn; then
+	    echo "Creating directory \$targetdir" >&2
+	fi
+	tmpdir="\$targetdir"
+	dashp="-p"
+    else
+	tmpdir="\$TMPROOT/selfgz\$\$\$RANDOM"
+	dashp=""
+    fi
+    mkdir \$dashp \$tmpdir || {
+	echo 'Cannot create target directory' \$tmpdir >&2
+	echo 'You should try option --target dir' >&2
+	eval \$finish
+	exit 1
+    }
+fi
+
+location="\`pwd\`"
+if test x"\$SETUP_NOCHECK" != x1; then
+    MS_Check "\$0"
+fi
+offset=\`head -n $SKIP "\$0" | wc -c | tr -d " "\`
+
+if test x"\$verbose" = xy; then
+	MS_Printf "About to extract $USIZE KB in \$tmpdir ... Proceed ? [Y/n] "
+	read yn
+	if test x"\$yn" = xn; then
+		eval \$finish; exit 1
+	fi
+fi
+
+if test x"\$quiet" = xn; then
+	MS_Printf "Uncompressing \$label"
+fi
+res=3
+if test x"\$keep" = xn; then
+    trap 'echo Signal caught, cleaning up >&2; cd \$TMPROOT; /bin/rm -rf \$tmpdir; eval \$finish; exit 15' 1 2 3 15
+fi
+
+if test x"\$nodiskspace" = xn; then
+    leftspace=\`MS_diskspace \$tmpdir\`
+    if test -n "\$leftspace"; then
+        if test "\$leftspace" -lt $USIZE; then
+            echo
+            echo "Not enough space left in "\`dirname \$tmpdir\`" (\$leftspace KB) to decompress \$0 ($USIZE KB)" >&2
+            echo "Use --nodiskspace option to skip this check and proceed anyway" >&2
+            if test x"\$keep" = xn; then
+                echo "Consider setting TMPDIR to a directory with more free space."
+            fi
+            eval \$finish; exit 1
+        fi
+    fi
+fi
+
+for s in \$filesizes
+do
+    if MS_dd_Progress "\$0" \$offset \$s | eval "$GUNZIP_CMD" | ( cd "\$tmpdir"; umask \$ORIG_UMASK ; UnTAR xp ) 1>/dev/null; then
+		if test x"\$ownership" = xy; then
+			(cd "\$tmpdir"; chown -R \`id -u\` .;  chgrp -R \`id -g\` .)
+		fi
+    else
+		echo >&2
+		echo "Unable to decompress \$0" >&2
+		eval \$finish; exit 1
+    fi
+    offset=\`expr \$offset + \$s\`
+done
+if test x"\$quiet" = xn; then
+	echo
+fi
+
+cd "\$tmpdir"
+res=0
+if test x"\$script" != x; then
+    if test x"\$export_conf" = x"y"; then
+        MS_BUNDLE="\$0"
+        MS_LABEL="\$label"
+        MS_SCRIPT="\$script"
+        MS_SCRIPTARGS="\$scriptargs"
+        MS_ARCHDIRNAME="\$archdirname"
+        MS_KEEP="\$KEEP"
+        MS_NOOVERWRITE="\$NOOVERWRITE"
+        MS_COMPRESS="\$COMPRESS"
+        export MS_BUNDLE MS_LABEL MS_SCRIPT MS_SCRIPTARGS
+        export MS_ARCHDIRNAME MS_KEEP MS_NOOVERWRITE MS_COMPRESS
+    fi
+
+    if test x"\$verbose" = x"y"; then
+		MS_Printf "OK to execute: \$script \$scriptargs \$* ? [Y/n] "
+		read yn
+		if test x"\$yn" = x -o x"\$yn" = xy -o x"\$yn" = xY; then
+			eval "\"\$script\" \$scriptargs \"\\\$@\""; res=\$?;
+		fi
+    else
+		eval "\"\$script\" \$scriptargs \"\\\$@\""; res=\$?
+    fi
+    if test "\$res" -ne 0; then
+		test x"\$verbose" = xy && echo "The program '\$script' returned an error code (\$res)" >&2
+    fi
+fi
+if test x"\$keep" = xn; then
+    cd \$TMPROOT
+    /bin/rm -rf \$tmpdir
+fi
+eval \$finish; exit \$res
+EOF
diff --git a/Packaging/makeself/makeself.1 b/Packaging/makeself/makeself.1
new file mode 100644
index 0000000000000000000000000000000000000000..abab2301b720620b1ef54db22e9434ce89f1c34a
--- /dev/null
+++ b/Packaging/makeself/makeself.1
@@ -0,0 +1,104 @@
+.TH "makeself" "1" "2.1.6"
+.SH "NAME"
+makeself \- An utility to generate self-extractable archives.
+.SH "SYNTAX"
+.LP 
+.B makeself [\fIoptions\fP] archive_dir file_name label 
+.B [\fIstartup_script\fP] [\fIargs\fP]
+.SH "DESCRIPTION"
+.LP 
+This program is a free (GPL) utility designed to create self-extractable 
+archives from a directory. 
+.br
+.SH "OPTIONS"
+.LP 
+The following options are supported.
+.LP 
+.TP 15
+.B -v, --version
+Prints out the makeself version number and exits.
+.TP
+.B -h, --help
+Print out help information.
+.TP
+.B --tar-quietly
+Suppress verbose output from the tar command
+.TP
+.B --quiet
+Do not print any messages other than errors
+.TP
+.B --gzip
+Compress using gzip (default if detected).
+.TP
+.B --bzip2
+Compress using bzip2.
+.TP
+.B --pbzip2
+Compress using pbzip2.
+.TP
+.B --xz
+Compress using xz.
+.TP
+.B --lzo
+Compress using lzop.
+.TP
+.B --lz4
+Compress using lz4.
+.TP
+.B --compress
+Compress using the UNIX 'compress' command.
+.TP
+.B --nocomp
+Do not compress the data.
+.TP
+.B --complevel lvl
+Specify the compression level for gzip,bzip2,pbzui2,xz,lzo or lz4
+.TP
+.B --notemp
+The archive will create archive_dir in the current directory and 
+uncompress in ./archive_dir.
+.TP
+.B --copy
+Upon extraction, the archive will first copy itself to a temporary directory.
+.TP
+.B --append
+Append more files to an existing makeself archive. The label and startup scripts will then be ignored.
+.TP
+.B --current
+Files will be extracted to the current directory. Both --current and --target dir imply --notemp.
+.TP
+.B --target dir
+Extract directly to a target directory. Directory path can be either absolute or relative.
+.TP
+.B --header file
+Specify location of the header script. 
+.TP
+.B --follow
+Follow the symlinks in the archive.
+.TP
+.B --noprogress
+Do not show the progress during the decompression.
+.TP
+.B --nox11
+Disable automatic spawn of an xterm if running in X11.
+.TP
+.B --nowait
+Do not wait for user input after executing embedded program from an xterm.
+.TP
+.B --nomd5
+Do not create a MD5 checksum for the archive.
+.TP
+.B --nocrc
+Do not create a CRC32 checksum for the archive.
+.TP
+.B --lsm file
+LSM file describing the package.
+.B --packaging-date date
+Use provided string as the packaging date instead of the current date.
+.PD
+.SH "AUTHORS"
+.LP 
+Makeself has been written by Stéphane Peter <megastep@megastep.org>.
+.BR 
+This man page was originally written by Bartosz Fenski <fenio@o2.pl> for the 
+Debian GNU/Linux distribution (but it may be used by others).
diff --git a/Packaging/makeself/makeself.lsm b/Packaging/makeself/makeself.lsm
new file mode 100644
index 0000000000000000000000000000000000000000..e32722ed514c4963b1109f67623ce6d0529fb889
--- /dev/null
+++ b/Packaging/makeself/makeself.lsm
@@ -0,0 +1,16 @@
+Begin3
+Title:          makeself.sh
+Version:        2.3.0
+Description:    makeself.sh is a shell script that generates a self-extractable        
+                tar.gz archive from a directory. The resulting file appears as a shell          
+                script, and can be launched as is. The archive will then uncompress
+                itself to a temporary directory and an arbitrary command will be
+                executed (for example an installation script). This is pretty similar
+                to archives generated with WinZip Self-Extractor in the Windows world.
+Keywords:       Installation archive tar winzip
+Author:         Stephane Peter (megastep@megastep.org)
+Maintained-by:  Stephane Peter (megastep@megastep.org)
+Original-site:  http://makeself.io/
+Platform:       Unix
+Copying-policy: GPL
+End
diff --git a/Packaging/makeself/makeself.sh b/Packaging/makeself/makeself.sh
new file mode 100755
index 0000000000000000000000000000000000000000..a2bb226d1ece2a46139dd6e8a1866100e10b65cb
--- /dev/null
+++ b/Packaging/makeself/makeself.sh
@@ -0,0 +1,620 @@
+#!/bin/sh
+#
+# Makeself version 2.3.x
+#  by Stephane Peter <megastep@megastep.org>
+#
+# Utility to create self-extracting tar.gz archives.
+# The resulting archive is a file holding the tar.gz archive with
+# a small Shell script stub that uncompresses the archive to a temporary
+# directory and then executes a given script from withing that directory.
+#
+# Makeself home page: http://makeself.io/
+#
+# Version 2.0 is a rewrite of version 1.0 to make the code easier to read and maintain.
+#
+# Version history :
+# - 1.0 : Initial public release
+# - 1.1 : The archive can be passed parameters that will be passed on to
+#         the embedded script, thanks to John C. Quillan
+# - 1.2 : Package distribution, bzip2 compression, more command line options,
+#         support for non-temporary archives. Ideas thanks to Francois Petitjean
+# - 1.3 : More patches from Bjarni R. Einarsson and Francois Petitjean:
+#         Support for no compression (--nocomp), script is no longer mandatory,
+#         automatic launch in an xterm, optional verbose output, and -target 
+#         archive option to indicate where to extract the files.
+# - 1.4 : Improved UNIX compatibility (Francois Petitjean)
+#         Automatic integrity checking, support of LSM files (Francois Petitjean)
+# - 1.5 : Many bugfixes. Optionally disable xterm spawning.
+# - 1.5.1 : More bugfixes, added archive options -list and -check.
+# - 1.5.2 : Cosmetic changes to inform the user of what's going on with big 
+#           archives (Quake III demo)
+# - 1.5.3 : Check for validity of the DISPLAY variable before launching an xterm.
+#           More verbosity in xterms and check for embedded command's return value.
+#           Bugfix for Debian 2.0 systems that have a different "print" command.
+# - 1.5.4 : Many bugfixes. Print out a message if the extraction failed.
+# - 1.5.5 : More bugfixes. Added support for SETUP_NOCHECK environment variable to
+#           bypass checksum verification of archives.
+# - 1.6.0 : Compute MD5 checksums with the md5sum command (patch from Ryan Gordon)
+# - 2.0   : Brand new rewrite, cleaner architecture, separated header and UNIX ports.
+# - 2.0.1 : Added --copy
+# - 2.1.0 : Allow multiple tarballs to be stored in one archive, and incremental updates.
+#           Added --nochown for archives
+#           Stopped doing redundant checksums when not necesary
+# - 2.1.1 : Work around insane behavior from certain Linux distros with no 'uncompress' command
+#           Cleaned up the code to handle error codes from compress. Simplified the extraction code.
+# - 2.1.2 : Some bug fixes. Use head -n to avoid problems.
+# - 2.1.3 : Bug fixes with command line when spawning terminals.
+#           Added --tar for archives, allowing to give arbitrary arguments to tar on the contents of the archive.
+#           Added --noexec to prevent execution of embedded scripts.
+#           Added --nomd5 and --nocrc to avoid creating checksums in archives.
+#           Added command used to create the archive in --info output.
+#           Run the embedded script through eval.
+# - 2.1.4 : Fixed --info output.
+#           Generate random directory name when extracting files to . to avoid problems. (Jason Trent)
+#           Better handling of errors with wrong permissions for the directory containing the files. (Jason Trent)
+#           Avoid some race conditions (Ludwig Nussel)
+#           Unset the $CDPATH variable to avoid problems if it is set. (Debian)
+#           Better handling of dot files in the archive directory.
+# - 2.1.5 : Made the md5sum detection consistent with the header code.
+#           Check for the presence of the archive directory
+#           Added --encrypt for symmetric encryption through gpg (Eric Windisch)
+#           Added support for the digest command on Solaris 10 for MD5 checksums
+#           Check for available disk space before extracting to the target directory (Andreas Schweitzer)
+#           Allow extraction to run asynchronously (patch by Peter Hatch)
+#           Use file descriptors internally to avoid error messages (patch by Kay Tiong Khoo)
+# - 2.1.6 : Replaced one dot per file progress with a realtime progress percentage and a spining cursor (Guy Baconniere)
+#           Added --noprogress to prevent showing the progress during the decompression (Guy Baconniere)
+#           Added --target dir to allow extracting directly to a target directory (Guy Baconniere)
+# - 2.2.0 : Many bugfixes, updates and contributions from users. Check out the project page on Github for the details.
+# - 2.3.0 : Option to specify packaging date to enable byte-for-byte reproducibility. (Marc Pawlowsky)
+#
+# (C) 1998-2017 by Stephane Peter <megastep@megastep.org>
+#
+# This software is released under the terms of the GNU GPL version 2 and above
+# Please read the license at http://www.gnu.org/copyleft/gpl.html
+#
+
+MS_VERSION=2.3.1
+MS_COMMAND="$0"
+unset CDPATH
+
+for f in "${1+"$@"}"; do
+    MS_COMMAND="$MS_COMMAND \\\\
+    \\\"$f\\\""
+done
+
+# For Solaris systems
+if test -d /usr/xpg4/bin; then
+    PATH=/usr/xpg4/bin:$PATH
+    export PATH
+fi
+
+# Procedures
+
+MS_Usage()
+{
+    echo "Usage: $0 [params] archive_dir file_name label startup_script [args]"
+    echo "params can be one or more of the following :"
+    echo "    --version | -v     : Print out Makeself version number and exit"
+    echo "    --help | -h        : Print out this help message"
+    echo "    --tar-quietly      : Suppress verbose output from the tar command"
+    echo "    --quiet | -q       : Do not print any messages other than errors."
+    echo "    --gzip             : Compress using gzip (default if detected)"
+    echo "    --pigz             : Compress with pigz"
+    echo "    --bzip2            : Compress using bzip2 instead of gzip"
+    echo "    --pbzip2           : Compress using pbzip2 instead of gzip"
+    echo "    --xz               : Compress using xz instead of gzip"
+    echo "    --lzo              : Compress using lzop instead of gzip"
+    echo "    --lz4              : Compress using lz4 instead of gzip"
+    echo "    --compress         : Compress using the UNIX 'compress' command"
+    echo "    --complevel lvl    : Compression level for gzip pigz xz lzo lz4 bzip2 and pbzip2 (default 9)"
+    echo "    --base64           : Instead of compressing, encode the data using base64"
+    echo "    --gpg-encrypt      : Instead of compressing, encrypt the data using GPG"
+    echo "    --gpg-asymmetric-encrypt-sign"
+    echo "                       : Instead of compressing, asymmetrically encrypt and sign the data using GPG"
+    echo "    --gpg-extra opt    : Append more options to the gpg command line"
+    echo "    --ssl-encrypt      : Instead of compressing, encrypt the data using OpenSSL"
+    echo "    --nocomp           : Do not compress the data"
+    echo "    --notemp           : The archive will create archive_dir in the"
+    echo "                         current directory and uncompress in ./archive_dir"
+    echo "    --needroot         : Check that the root user is extracting the archive before proceeding"
+    echo "    --copy             : Upon extraction, the archive will first copy itself to"
+    echo "                         a temporary directory"
+    echo "    --append           : Append more files to an existing Makeself archive"
+    echo "                         The label and startup scripts will then be ignored"
+    echo "    --target dir       : Extract directly to a target directory"
+    echo "                         directory path can be either absolute or relative"
+    echo "    --nooverwrite      : Do not extract the archive if the specified target directory exists"
+    echo "    --current          : Files will be extracted to the current directory"
+    echo "                         Both --current and --target imply --notemp"
+    echo "    --tar-extra opt    : Append more options to the tar command line"
+    echo "    --untar-extra opt  : Append more options to the during the extraction of the tar archive"
+    echo "    --nomd5            : Don't calculate an MD5 for archive"
+    echo "    --nocrc            : Don't calculate a CRC for archive"
+    echo "    --header file      : Specify location of the header script"
+    echo "    --follow           : Follow the symlinks in the archive"
+    echo "    --noprogress       : Do not show the progress during the decompression"
+    echo "    --nox11            : Disable automatic spawn of a xterm"
+    echo "    --nowait           : Do not wait for user input after executing embedded"
+    echo "                         program from an xterm"
+    echo "    --lsm file         : LSM file describing the package"
+    echo "    --license file     : Append a license file"
+    echo "    --help-header file : Add a header to the archive's --help output"
+    echo "    --packaging-date date"
+    echo "                       : Use provided string as the packaging date"
+    echo "                         instead of the current date."
+    echo
+    echo "    --keep-umask       : Keep the umask set to shell default, rather than overriding when executing self-extracting archive."
+    echo "    --export-conf      : Export configuration variables to startup_script"
+    echo
+    echo "Do not forget to give a fully qualified startup script name"
+    echo "(i.e. with a ./ prefix if inside the archive)."
+    exit 1
+}
+
+# Default settings
+if type gzip 2>&1 > /dev/null; then
+    COMPRESS=gzip
+else
+    COMPRESS=Unix
+fi
+COMPRESS_LEVEL=9
+KEEP=n
+CURRENT=n
+NOX11=n
+NOWAIT=n
+APPEND=n
+TAR_QUIETLY=n
+KEEP_UMASK=n
+QUIET=n
+NOPROGRESS=n
+COPY=none
+NEED_ROOT=n
+TAR_ARGS=cvf
+TAR_EXTRA=""
+GPG_EXTRA=""
+DU_ARGS=-ks
+HEADER=`dirname "$0"`/makeself-header.sh
+TARGETDIR=""
+NOOVERWRITE=n
+DATE=`LC_ALL=C date`
+EXPORT_CONF=n
+
+# LSM file stuff
+LSM_CMD="echo No LSM. >> \"\$archname\""
+
+while true
+do
+    case "$1" in
+    --version | -v)
+	echo Makeself version $MS_VERSION
+	exit 0
+	;;
+    --pbzip2)
+	COMPRESS=pbzip2
+	shift
+	;;
+    --bzip2)
+	COMPRESS=bzip2
+	shift
+	;;
+    --gzip)
+	COMPRESS=gzip
+	shift
+	;;
+    --pigz)
+    	COMPRESS=pigz
+    	shift
+    	;;
+    --xz)
+	COMPRESS=xz
+	shift
+	;;
+    --lzo)
+	COMPRESS=lzo
+	shift
+	;;
+    --lz4)
+	COMPRESS=lz4
+	shift
+	;;
+    --compress)
+	COMPRESS=Unix
+	shift
+	;;
+    --base64)
+	COMPRESS=base64
+	shift
+	;;
+    --gpg-encrypt)
+	COMPRESS=gpg
+	shift
+	;;
+    --gpg-asymmetric-encrypt-sign)
+  COMPRESS=gpg-asymmetric
+  shift
+  ;;
+    --gpg-extra)
+  GPG_EXTRA="$2"
+  if ! shift 2; then MS_Help; exit 1; fi
+  ;;
+    --ssl-encrypt)
+  COMPRESS=openssl
+  shift
+  ;;
+    --nocomp)
+	COMPRESS=none
+	shift
+	;;
+    --complevel)
+	COMPRESS_LEVEL="$2"
+	if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --notemp)
+	KEEP=y
+	shift
+	;;
+    --copy)
+	COPY=copy
+	shift
+	;;
+    --current)
+	CURRENT=y
+	KEEP=y
+	shift
+	;;
+    --tar-extra)
+	TAR_EXTRA="$2"
+        if ! shift 2; then MS_Help; exit 1; fi
+        ;;
+    --untar-extra)
+        UNTAR_EXTRA="$2"
+        if ! shift 2; then MS_Help; exit 1; fi
+        ;;
+    --target)
+	TARGETDIR="$2"
+	KEEP=y
+        if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --nooverwrite)
+        NOOVERWRITE=y
+	shift
+        ;;
+    --needroot)
+	NEED_ROOT=y
+	shift
+	;;
+    --header)
+	HEADER="$2"
+        if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --license)
+        LICENSE=`cat $2`
+        if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --follow)
+	TAR_ARGS=cvhf
+	DU_ARGS=-ksL
+	shift
+	;;
+    --noprogress)
+	NOPROGRESS=y
+	shift
+	;;
+    --nox11)
+	NOX11=y
+	shift
+	;;
+    --nowait)
+	NOWAIT=y
+	shift
+	;;
+    --nomd5)
+	NOMD5=y
+	shift
+	;;
+    --nocrc)
+	NOCRC=y
+	shift
+	;;
+    --append)
+	APPEND=y
+	shift
+	;;
+    --lsm)
+	LSM_CMD="cat \"$2\" >> \"\$archname\""
+    if ! shift 2; then MS_Help; exit 1; fi
+	;;
+    --packaging-date)
+	DATE="$2"
+	if ! shift 2; then MS_Help; exit 1; fi
+        ;;
+    --help-header)
+	HELPHEADER=`sed -e "s/'/'\\\\\''/g" $2`
+    if ! shift 2; then MS_Help; exit 1; fi
+	[ -n "$HELPHEADER" ] && HELPHEADER="$HELPHEADER
+"
+    ;;
+    --tar-quietly)
+	TAR_QUIETLY=y
+	shift
+	;;
+	--keep-umask)
+	KEEP_UMASK=y
+	shift
+	;;
+    --export-conf)
+    EXPORT_CONF=y
+    shift
+    ;;
+    -q | --quiet)
+	QUIET=y
+	shift
+	;;
+    -h | --help)
+	MS_Usage
+	;;
+    -*)
+	echo Unrecognized flag : "$1"
+	MS_Usage
+	;;
+    *)
+	break
+	;;
+    esac
+done
+
+if test $# -lt 1; then
+	MS_Usage
+else
+	if test -d "$1"; then
+		archdir="$1"
+	else
+		echo "Directory $1 does not exist." >&2
+		exit 1
+	fi
+fi
+archname="$2"
+
+if test "$QUIET" = "y" || test "$TAR_QUIETLY" = "y"; then
+    if test "$TAR_ARGS" = "cvf"; then
+	TAR_ARGS="cf"
+    elif test "$TAR_ARGS" = "cvhf";then
+	TAR_ARGS="chf"
+    fi
+fi
+
+if test "$APPEND" = y; then
+    if test $# -lt 2; then
+	MS_Usage
+    fi
+
+    # Gather the info from the original archive
+    OLDENV=`sh "$archname" --dumpconf`
+    if test $? -ne 0; then
+	echo "Unable to update archive: $archname" >&2
+	exit 1
+    else
+	eval "$OLDENV"
+    fi
+else
+    if test "$KEEP" = n -a $# = 3; then
+	echo "ERROR: Making a temporary archive with no embedded command does not make sense!" >&2
+	echo >&2
+	MS_Usage
+    fi
+    # We don't want to create an absolute directory unless a target directory is defined
+    if test "$CURRENT" = y; then
+	archdirname="."
+    elif test x$TARGETDIR != x; then
+	archdirname="$TARGETDIR"
+    else
+	archdirname=`basename "$1"`
+    fi
+
+    if test $# -lt 3; then
+	MS_Usage
+    fi
+
+    LABEL="$3"
+    SCRIPT="$4"
+    test "x$SCRIPT" = x || shift 1
+    shift 3
+    SCRIPTARGS="$*"
+fi
+
+if test "$KEEP" = n -a "$CURRENT" = y; then
+    echo "ERROR: It is A VERY DANGEROUS IDEA to try to combine --notemp and --current." >&2
+    exit 1
+fi
+
+case $COMPRESS in
+gzip)
+    GZIP_CMD="gzip -c$COMPRESS_LEVEL"
+    GUNZIP_CMD="gzip -cd"
+    ;;
+pigz) 
+    GZIP_CMD="pigz -$COMPRESS_LEVEL"
+    GUNZIP_CMD="gzip -cd"
+    ;;
+pbzip2)
+    GZIP_CMD="pbzip2 -c$COMPRESS_LEVEL"
+    GUNZIP_CMD="bzip2 -d"
+    ;;
+bzip2)
+    GZIP_CMD="bzip2 -$COMPRESS_LEVEL"
+    GUNZIP_CMD="bzip2 -d"
+    ;;
+xz)
+    GZIP_CMD="xz -c$COMPRESS_LEVEL"
+    GUNZIP_CMD="xz -d"
+    ;;
+lzo)
+    GZIP_CMD="lzop -c$COMPRESS_LEVEL"
+    GUNZIP_CMD="lzop -d"
+    ;;
+lz4)
+    GZIP_CMD="lz4 -c$COMPRESS_LEVEL"
+    GUNZIP_CMD="lz4 -d"
+    ;;
+base64)
+    GZIP_CMD="base64"
+    GUNZIP_CMD="base64 -d -i"
+    ;;
+gpg)
+    GZIP_CMD="gpg $GPG_EXTRA -ac -z$COMPRESS_LEVEL"
+    GUNZIP_CMD="gpg -d"
+    ;;
+gpg-asymmetric)
+    GZIP_CMD="gpg $GPG_EXTRA -z$COMPRESS_LEVEL -es"
+    GUNZIP_CMD="gpg --yes -d"
+    ;;
+openssl)
+    GZIP_CMD="openssl aes-256-cbc -a -salt"
+    GUNZIP_CMD="openssl aes-256-cbc -d -a"
+    ;;
+Unix)
+    GZIP_CMD="compress -cf"
+    GUNZIP_CMD="exec 2>&-; uncompress -c || test \\\$? -eq 2 || gzip -cd"
+    ;;
+none)
+    GZIP_CMD="cat"
+    GUNZIP_CMD="cat"
+    ;;
+esac
+
+tmpfile="${TMPDIR:=/tmp}/mkself$$"
+
+if test -f "$HEADER"; then
+	oldarchname="$archname"
+	archname="$tmpfile"
+	# Generate a fake header to count its lines
+	SKIP=0
+    . "$HEADER"
+    SKIP=`cat "$tmpfile" |wc -l`
+	# Get rid of any spaces
+	SKIP=`expr $SKIP`
+	rm -f "$tmpfile"
+    if test "$QUIET" = "n";then
+    	echo Header is $SKIP lines long >&2
+    fi
+
+	archname="$oldarchname"
+else
+    echo "Unable to open header file: $HEADER" >&2
+    exit 1
+fi
+
+if test "$QUIET" = "n";then 
+    echo
+fi
+
+if test "$APPEND" = n; then
+    if test -f "$archname"; then
+		echo "WARNING: Overwriting existing file: $archname" >&2
+    fi
+fi
+
+USIZE=`du $DU_ARGS "$archdir" | awk '{print $1}'`
+
+if test "." = "$archdirname"; then
+	if test "$KEEP" = n; then
+		archdirname="makeself-$$-`date +%Y%m%d%H%M%S`"
+	fi
+fi
+
+test -d "$archdir" || { echo "Error: $archdir does not exist."; rm -f "$tmpfile"; exit 1; }
+if test "$QUIET" = "n";then
+   echo About to compress $USIZE KB of data...
+   echo Adding files to archive named \"$archname\"...
+fi
+exec 3<> "$tmpfile"
+( cd "$archdir" && ( tar $TAR_EXTRA -$TAR_ARGS - . | eval "$GZIP_CMD" >&3 ) ) || \
+    { echo Aborting: archive directory not found or temporary file: "$tmpfile" could not be created.; exec 3>&-; rm -f "$tmpfile"; exit 1; }
+exec 3>&- # try to close the archive
+
+fsize=`cat "$tmpfile" | wc -c | tr -d " "`
+
+# Compute the checksums
+
+md5sum=00000000000000000000000000000000
+crcsum=0000000000
+
+if test "$NOCRC" = y; then
+	if test "$QUIET" = "n";then
+		echo "skipping crc at user request"
+	fi
+else
+	crcsum=`cat "$tmpfile" | CMD_ENV=xpg4 cksum | sed -e 's/ /Z/' -e 's/	/Z/' | cut -dZ -f1`
+	if test "$QUIET" = "n";then
+		echo "CRC: $crcsum"
+	fi
+fi
+
+if test "$NOMD5" = y; then
+	if test "$QUIET" = "n";then
+		echo "skipping md5sum at user request"
+	fi
+else
+	# Try to locate a MD5 binary
+	OLD_PATH=$PATH
+	PATH=${GUESS_MD5_PATH:-"$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
+	MD5_ARG=""
+	MD5_PATH=`exec <&- 2>&-; which md5sum || command -v md5sum || type md5sum`
+	test -x "$MD5_PATH" || MD5_PATH=`exec <&- 2>&-; which md5 || command -v md5 || type md5`
+	test -x "$MD5_PATH" || MD5_PATH=`exec <&- 2>&-; which digest || command -v digest || type digest`
+	PATH=$OLD_PATH
+	if test -x "$MD5_PATH"; then
+		if test `basename ${MD5_PATH}`x = digestx; then
+			MD5_ARG="-a md5"
+		fi
+		md5sum=`cat "$tmpfile" | eval "$MD5_PATH $MD5_ARG" | cut -b-32`;
+		if test "$QUIET" = "n";then
+			echo "MD5: $md5sum"
+		fi
+	else
+		if test "$QUIET" = "n";then
+			echo "MD5: none, MD5 command not found"
+		fi
+	fi
+fi
+
+if test "$APPEND" = y; then
+    mv "$archname" "$archname".bak || exit
+
+    # Prepare entry for new archive
+    filesizes="$filesizes $fsize"
+    CRCsum="$CRCsum $crcsum"
+    MD5sum="$MD5sum $md5sum"
+    USIZE=`expr $USIZE + $OLDUSIZE`
+    # Generate the header
+    . "$HEADER"
+    # Append the original data
+    tail -n +$OLDSKIP "$archname".bak >> "$archname"
+    # Append the new data
+    cat "$tmpfile" >> "$archname"
+
+    chmod +x "$archname"
+    rm -f "$archname".bak
+    if test "$QUIET" = "n";then
+    	echo Self-extractable archive \"$archname\" successfully updated.
+    fi
+else
+    filesizes="$fsize"
+    CRCsum="$crcsum"
+    MD5sum="$md5sum"
+
+    # Generate the header
+    . "$HEADER"
+
+    # Append the compressed tar data after the stub
+    if test "$QUIET" = "n";then
+    	echo
+    fi
+    cat "$tmpfile" >> "$archname"
+    chmod +x "$archname"
+    if test "$QUIET" = "n";then
+    	echo Self-extractable archive \"$archname\" successfully created.
+    fi
+fi
+rm -f "$tmpfile"
diff --git a/Packaging/otb_update_makeself b/Packaging/otb_update_makeself
new file mode 100644
index 0000000000000000000000000000000000000000..82405385262f3b28e652661732172ee1002455e3
--- /dev/null
+++ b/Packaging/otb_update_makeself
@@ -0,0 +1,11 @@
+HOWTO UPDATE MAKESELF
+
+#If makEself version with your required bug fix is 2.3.1
+# cd to otb/sources/Packaging/
+
+wget https://github.com/megastep/makeself/archive/release-2.3.1.tar.gz
+tar xzf release-2.3.1.tar.gz
+mv makeself-release-2.3.1 makeself
+rm -fr release-2.3.1.tar.gz
+
+run git diff to check if everything is in place and git commit 
diff --git a/Packaging/patch_cmake_files.cmake b/Packaging/patch_cmake_files.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..49ee420898e2aa1f3ecd402bc4d5c66fba27ee87
--- /dev/null
+++ b/Packaging/patch_cmake_files.cmake
@@ -0,0 +1,63 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(patch_cmake_files)
+  cmake_parse_arguments(PATCH  "" "NAME;VERSION;MATCH_STRING;REPLACE_VAR" "" ${ARGN} )
+
+  set(PATCH_DIR_NAME ${PATCH_NAME}-${PATCH_VERSION})
+  set(PATCH_DIR "${SUPERBUILD_INSTALL_DIR}/lib/cmake/${PATCH_DIR_NAME}")
+  set(PATCH_STAGE_DIR ${CMAKE_CURRENT_BINARY_DIR}/patched/${PATCH_DIR_NAME})
+
+  ##message("COPY ${PATCH_DIR} to ${PATCH_STAGE_DIR} for patching")
+
+  execute_process(
+    COMMAND ${CMAKE_COMMAND} -E make_directory "${PATCH_STAGE_DIR}"
+    COMMAND ${CMAKE_COMMAND} -E copy_directory "${PATCH_DIR}" "${PATCH_STAGE_DIR}"
+    )
+
+  set(DIR_LIST "${PATCH_STAGE_DIR}|${PATCH_STAGE_DIR}/Modules")
+
+  execute_process(COMMAND ${CMAKE_COMMAND}
+    -DP_DIRS=${DIR_LIST}
+    -DP_MATCH=${PATCH_MATCH_STRING}
+    -DP_REPLACE=${PATCH_REPLACE_VAR}
+    -P ${CMAKE_CURRENT_SOURCE_DIR}/post_install.cmake
+    RESULT_VARIABLE patch_${PATCH_NAME}_cmake_rv
+    )
+
+  if(patch_${PATCH_NAME}_cmake_rv)
+    message(FATAL_ERROR "    execute_process() failed.")
+  endif()
+
+  install_without_message("${PATCH_STAGE_DIR}" "lib/cmake")
+
+  # file( GLOB otb_opengl
+  #   "${SUPERBUILD_INSTALL_DIR}/lib/cmake/OTB*/Modules/OTBOpenGL.cmake" )
+  # if(EXISTS ${otb_opengl})
+  #   file(STRINGS "${otb_opengl}" otb_opengl_cmake)
+  #   set(otb_opengl_cmake_NEW)
+  #   foreach(line ${otb_opengl_cmake})
+  #     if( NOT line MATCHES "/usr")
+  # 	list(APPEND otb_opengl_cmake_NEW "${line}\n")
+  #     endif()
+  #   endforeach()
+  # endif()
+  # file(WRITE "${otb_opengl}" ${otb_opengl_cmake_NEW})
+  
+endfunction()
diff --git a/SuperBuild/CMake/post_install.cmake b/Packaging/post_install.cmake
similarity index 60%
rename from SuperBuild/CMake/post_install.cmake
rename to Packaging/post_install.cmake
index 55cff6c48b480593f6fb4a412f96ece2626e5246..29c937e02fcafbfbf7799a00502f3aa1fedf412a 100644
--- a/SuperBuild/CMake/post_install.cmake
+++ b/Packaging/post_install.cmake
@@ -29,18 +29,18 @@ string(REPLACE "|" ";" P_DIRS ${P_DIRS})
 
 
 foreach( p_dir ${P_DIRS} )
-set(file_list)
-file( GLOB file_list "${p_dir}/*.cmake" )
-list(SORT file_list)
-foreach( cmake_file ${file_list} )
-
-  file(STRINGS "${cmake_file}" MATCH_FOUND REGEX "${P_MATCH}")
-  if(MATCH_FOUND)
-    message("Replacing '${P_MATCH}' with '${P_REPLACE}' in ${cmake_file}")
-    file(STRINGS "${cmake_file}" cmake_file_CONTENTS NEWLINE_CONSUME)
-    string(REPLACE "${P_MATCH}" "$${}{${P_REPLACE}}" cmake_file_CONTENTS ${cmake_file_CONTENTS})
-    file(WRITE "${cmake_file}"  "# This file is modified by OTB after installation.
+  set(file_list)
+  file( GLOB file_list "${p_dir}/*.cmake" )
+  list(SORT file_list)
+  foreach( cmake_file ${file_list} )
+    file(STRINGS "${cmake_file}" MATCH_FOUND REGEX "${P_MATCH}")
+    if(MATCH_FOUND)
+      message(STATUS "Patching: ${cmake_file}")
+      #message("Patch: Replace '${P_MATCH}' with '${P_REPLACE}' in ${cmake_file}")
+      file(STRINGS "${cmake_file}" cmake_file_CONTENTS NEWLINE_CONSUME)
+      string(REPLACE "${P_MATCH}" "$${}{${P_REPLACE}}" cmake_file_CONTENTS ${cmake_file_CONTENTS})
+      file(WRITE "${cmake_file}"  "# This file is modified by OTB after installation.
       \n${cmake_file_CONTENTS}")
-  endif()
-endforeach() # foreach( cmake_file
+    endif()
+  endforeach() # foreach( cmake_file
 endforeach() # foreach( p_dir
diff --git a/Packaging/prepare_file_list.cmake b/Packaging/prepare_file_list.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..4d83bc601da079a89f57d98bda00e54a00b08501
--- /dev/null
+++ b/Packaging/prepare_file_list.cmake
@@ -0,0 +1,99 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(prepare_file_list file_list_result)
+
+  set(file_list)
+  set(otbapp_launcher "otbApplicationLauncherCommandLine${EXE_EXT}")
+  #This must exist in any OTB Installation. minimal or full
+  if(NOT EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/${otbapp_launcher}")
+    message(
+      FATAL_ERROR
+      "${SUPERBUILD_INSTALL_DIR}/bin/${otbapp_launcher} not found.")
+    return()
+  endif()
+
+  set(file_list "${otbapp_launcher}")
+
+  if(HAVE_QT4)
+    list(APPEND file_list "otbApplicationLauncherQt${EXE_EXT}")
+  endif()
+
+  if(HAVE_MVD)
+    list(APPEND file_list "monteverdi${EXE_EXT}")
+    list(APPEND file_list "mapla${EXE_EXT}")
+  endif()
+  
+  if(HAVE_PYTHON)
+    list(APPEND file_list "_otbApplication${PYMODULE_EXT}")
+  endif()
+  
+  foreach(exe_file "iceViewer" "otbTestDriver" "SharkVersion")
+    if(EXISTS "${SUPERBUILD_INSTALL_DIR}/bin/${exe_file}${EXE_EXT}")
+      list(APPEND file_list "${exe_file}${EXE_EXT}")
+    else()
+      message(STATUS "${exe_file}${EXE_EXT} not found in ${SUPERBUILD_INSTALL_DIR}/bin. (skipping)")
+    endif()
+  endforeach()
+
+  #Qt stuff
+  if(HAVE_QT4)
+    list(APPEND file_list "lrelease${EXE_EXT}")
+    list(APPEND file_list "moc${EXE_EXT}")
+    list(APPEND file_list "qmake${EXE_EXT}")
+    list(APPEND file_list "rcc${EXE_EXT}")
+    list(APPEND file_list "uic${EXE_EXT}")
+    list(APPEND file_list "proj${EXE_EXT}")
+    list(APPEND file_list "cs2cs${EXE_EXT}")
+  endif()
+  
+  file(GLOB otb_test_exe_list 
+    "${SUPERBUILD_INSTALL_DIR}/bin/gdal*${EXE_EXT}"
+    "${OTB_BINARY_DIR}/bin/*[T|t]est*${EXE_EXT}"
+    )
+
+  #special items to be removed!. hackety-hack
+  list(REMOVE_ITEM otb_test_exe_list
+    "${SUPERBUILD_INSTALL_DIR}/bin/gdal-config"
+    )
+  list(REMOVE_ITEM otb_test_exe_list
+    "${OTB_BINARY_DIR}/bin/otbcli_TestApplication")
+  
+  list(REMOVE_ITEM otb_test_exe_list
+    "${OTB_BINARY_DIR}/bin/otbgui_TestApplication")
+  
+  foreach(otb_test_exe   ${otb_test_exe_list})
+    get_filename_component(otb_test_exe_name ${otb_test_exe} NAME)
+    list(APPEND file_list ${otb_test_exe_name})
+  endforeach()
+  
+  # special case for msvc: ucrtbase.dll must be explicitly vetted.
+  # for proj.dll, see Mantis-1424
+  if(MSVC)
+    list(APPEND file_list "ucrtbase.dll")
+    list(APPEND file_list "proj.dll")
+  endif()  
+
+  set(otb_applications_dir "${SUPERBUILD_INSTALL_DIR}/lib/otb/applications")
+  file(GLOB OTB_APPS_LIST "${otb_applications_dir}/otbapp_*${LIB_EXT}") # /lib/otb
+  list(APPEND  file_list ${OTB_APPS_LIST})
+
+
+  set(${file_list_result} ${file_list} PARENT_SCOPE)
+endfunction()
diff --git a/Packaging/prepare_search_dirs.cmake b/Packaging/prepare_search_dirs.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..8f246edd9b072a59ccc4095fccb4718250c1c1bb
--- /dev/null
+++ b/Packaging/prepare_search_dirs.cmake
@@ -0,0 +1,59 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(prepare_search_dirs search_dirs_result)
+  
+  set(search_dirs)
+  
+  if(MSVC)
+    if(NOT DEFINED ENV{UniversalCRTSdkDir})
+      message(FATAL_ERROR "UniversalCRTSdkDir variable not set. Cannot continue")
+    endif()
+    if(NOT DEFINED ENV{VCINSTALLDIR})
+      message(FATAL_ERROR  "VCINSTALLDIR variable not set. Cannot continue.")
+    endif()
+  endif()
+  
+  if(MSVC)    
+    file(TO_CMAKE_PATH "$ENV{UniversalCRTSdkDir}" UCRT_SDK_DIR)
+    list(APPEND search_dirs "${UCRT_SDK_DIR}/Redist/ucrt/DLLs/${OTB_TARGET_SYSTEM_ARCH}") #ucrt dlls
+  
+  #additional msvc redist dll from VCINSTALLDIR
+  file(TO_CMAKE_PATH "$ENV{VCINSTALLDIR}" PKG_VCINSTALLDIR)
+  list(APPEND search_dirs 
+    "${PKG_VCINSTALLDIR}/redist/${OTB_TARGET_SYSTEM_ARCH}/Microsoft.VC140.CRT"
+    "${PKG_VCINSTALLDIR}/redist/${OTB_TARGET_SYSTEM_ARCH}/Microsoft.VC140.OPENMP"
+    )
+endif()
+
+#superbuild .so /.dylib
+list(APPEND search_dirs "${SUPERBUILD_INSTALL_DIR}/lib")
+#all executables gdalinfo etc..
+list(APPEND search_dirs "${SUPERBUILD_INSTALL_DIR}/bin") 
+#common for all platforms.
+list(APPEND search_dirs "${SUPERBUILD_INSTALL_DIR}/lib/otb/applications")
+
+#_otbApplication.so
+list(APPEND search_dirs "${SUPERBUILD_INSTALL_DIR}/lib/otb/python")
+
+#for otbtest executables. 
+list(APPEND search_dirs ${OTB_BINARY_DIR}/bin)
+
+set(${search_dirs_result} ${search_dirs} PARENT_SCOPE)
+endfunction()
diff --git a/Packaging/process_file_recurse.cmake b/Packaging/process_file_recurse.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..b83616ad864c070e3d3b390b809d20dca00303df
--- /dev/null
+++ b/Packaging/process_file_recurse.cmake
@@ -0,0 +1,141 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(process_file_recurse input_file)
+  set(input_file_full_path)
+  search_library(${input_file} PKG_SEARCHDIRS input_file_full_path)
+  if(NOT input_file_full_path)
+    if(LINUX)
+      setif_value_in_list(is_gtk_lib "${input_file}" ALLOWED_SYSTEM_DLLS)
+      if(is_gtk_lib)
+	search_library(${input_file} PKG_GTK_SEARCHDIRS input_file_full_path)
+	if( NOT input_file_full_path)
+	  message(FATAL_ERROR "${input_file} not found. searched in ${PKG_GTK_SEARCHDIRS}")
+	endif()
+      endif()
+      if( NOT input_file_full_path)
+	message(FATAL_ERROR "${input_file} not found. searched in ${PKG_SEARCHDIRS}")
+	endif()
+    endif(LINUX)
+
+  endif() #if(NOT input_file_full_path)
+
+  if(NOT PKG_DEBUG)
+    message("Processing ${input_file_full_path}")
+  endif()
+  
+  # Install the file with install_rule().
+  # This function has specific "rules" to decide wheather and where to install file  
+  install_rule(${input_file_full_path})
+  
+  set(raw_items)
+
+  execute_process(
+    COMMAND ${LOADER_PROGRAM} ${LOADER_ARGS} "${input_file_full_path}"
+    RESULT_VARIABLE loader_rv
+    OUTPUT_VARIABLE loader_ov
+    ERROR_VARIABLE loader_ev
+    )
+  
+  if(loader_rv)
+    message(FATAL_ERROR "loader_ev=${loader_ev}\n PACKAGE-OTB: result_variable is '${loader_rv}'")
+  endif()
+
+  string(REPLACE ";" "\\;" candidates "${loader_ov}")
+  string(REPLACE "\n" "${LOADER_REGEX_EOL};" candidates "${candidates}")
+  
+  get_filename_component(bn_name ${input_file_full_path} NAME)
+  set(${bn_name}_USED TRUE CACHE INTERNAL "")
+
+  if(PKG_DEBUG)
+    message("Processing ${input_file} started. Set ${bn_name}_USED=${${bn_name}_USED}")
+  endif()
+
+  foreach(candidate ${candidates})
+    if(NOT candidate)
+      continue()
+    endif()
+
+    if(NOT "${candidate}" MATCHES "${LOADER_REGEX}")
+      continue()
+    endif()
+
+    string(REGEX REPLACE "${LOADER_REGEX}" "\\1" raw_item "${candidate}")
+
+    if(NOT raw_item)
+      continue()
+    endif()  
+
+    string(STRIP ${raw_item} raw_item)
+    set(is_system FALSE)
+    setif_value_in_list(is_system "${raw_item}" SYSTEM_DLLS)
+    if(APPLE AND NOT is_system)
+      if("${raw_item}" MATCHES "@rpath")
+        string(REGEX REPLACE "@rpath." "" raw_item "${raw_item}")
+      else()
+        message(FATAL_ERROR "'${raw_item}' does not have @rpath")
+      endif()
+    endif()
+
+    if(PKG_DEBUG AND ${raw_item}_RESOLVED)
+      message("${raw_item} is already resolved [${raw_item}_RESOLVED=${${raw_item}_RESOLVED}]")
+    endif()
+
+    if(PKG_DEBUG)
+      message("raw_item='${raw_item}'\tis_system='${is_system}'")
+    endif()
+    if(is_system OR ${raw_item}_RESOLVED OR ${raw_item}_USED)
+      continue()
+    endif()
+    
+    list(APPEND raw_items ${raw_item})
+    
+  endforeach()
+
+  if(PKG_DEBUG)
+    string(REPLACE ";" "\n" raw_items_pretty_print "${raw_items}")
+    # message(FATAL_ERROR "raw_items=${raw_items_pretty_print}")
+  endif(PKG_DEBUG)
+
+  if(raw_items)
+    list(REVERSE raw_items)
+    foreach(item ${raw_items})      
+      search_library(${item} PKG_SEARCHDIRS item_full_path)
+      set(is_a_symlink FALSE)
+      set(item_target_file)
+      isfile_symlink("${item_full_path}" is_a_symlink item_target_file)
+      if(is_a_symlink)
+        set(${item}_RESOLVED TRUE CACHE INTERNAL "")
+        set(item ${item_target_file})
+      endif()
+      if(PKG_DEBUG)
+        message("${bn_name} depends on '${item}'. So we now process '${item}'") # [ ${item}_USED=${${item}_USED} ${item}_RESOLVED=${${item}_RESOLVED}]")
+      endif()
+      process_file_recurse(${item})
+    endforeach()
+  endif()
+
+  set(${bn_name}_RESOLVED TRUE CACHE INTERNAL "")
+   if(PKG_DEBUG)
+     message("All dependencies of ${bn_name} are processed. Install file and set ${bn_name}_RESOLVED=${${bn_name}_RESOLVED}")
+   endif()
+
+   #install_rule(${input_file_full_path})
+
+endfunction() #function(process_file_recurse infile)
diff --git a/Packaging/search_library.cmake b/Packaging/search_library.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..500bbb9acf1585cdff4bcfd54c8d29ba35095c10
--- /dev/null
+++ b/Packaging/search_library.cmake
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(search_library input_file pkg_searchdirs result)
+  set(${result} "" PARENT_SCOPE)
+  foreach(pkg_searchdir ${${pkg_searchdirs}})
+
+    if(EXISTS ${pkg_searchdir}/${input_file} )
+      if(PKG_DEBUG)
+        message("Found '${pkg_searchdir}/${input_file}' (return)")
+      endif()
+      set(${result} "${pkg_searchdir}/${input_file}" PARENT_SCOPE)
+      return()
+    endif()
+
+    #check for file with lowercase
+    string(TOLOWER "${input_file}" input_file_lower )
+    if(EXISTS ${pkg_searchdir}/${input_file_lower})
+      set(${result} "${pkg_searchdir}/${input_file_lower}"  PARENT_SCOPE)
+      return()
+    endif()
+  endforeach()
+endfunction()
diff --git a/Packaging/setif_value_in_list.cmake b/Packaging/setif_value_in_list.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..7ae6820de3ae6c49c9d87d95818dac9145546a38
--- /dev/null
+++ b/Packaging/setif_value_in_list.cmake
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+function(setif_value_in_list matched VALUE list)
+  set(${matched} FALSE  PARENT_SCOPE)
+  string(TOLOWER ${VALUE} value)
+  foreach (PATTERN ${${list}})
+    string(TOLOWER ${PATTERN} pattern)
+    if("${value}" MATCHES "${pattern}")
+      set(${matched} TRUE PARENT_SCOPE)
+      #we found a match. return from loop.
+      return()
+    endif()
+  endforeach()
+  #message("'${value}' not found in ${list}")
+endfunction()
diff --git a/Packaging/testing.cmake b/Packaging/testing.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..c7dce464d1cc6c4e7afc46d35cfddea42dd4f8fa
--- /dev/null
+++ b/Packaging/testing.cmake
@@ -0,0 +1,85 @@
+#
+# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
+#
+# This file is part of Orfeo Toolbox
+#
+#     https://www.orfeo-toolbox.org/
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# add_test(NAME <name> COMMAND <command> [<arg>...]
+#          [CONFIGURATIONS <config>...]
+#          [WORKING_DIRECTORY <dir>])
+
+set(testing_dir ${CMAKE_BINARY_DIR}/tests)
+if(EXISTS "${testing_dir}")
+  execute_process(COMMAND ${CMAKE_COMMAND} -E remove_directory ${testing_dir})
+  execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory   ${testing_dir})
+else()
+  execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory   ${testing_dir})
+endif()
+
+set(install_package_ARGS)
+set(selftester_ARGS)
+set(pkg_extracted_dir "${testing_dir}/${PKG_STAGE_DIR}")
+if(WIN32)
+  set(install_package_ARGS "x;${PACKAGE_OUTPUT_FILE}")
+  set(install_package_CMD "${ZIP_EXECUTABLE}")
+  #selftester
+  set(selftester_CMD ${pkg_extracted_dir}/tools/selftester.bat)
+  set(selftester_ARGS "/q")
+  #uninstall OTB
+  set(uninstall_otb_CMD ${pkg_extracted_dir}/tools/uninstall_otb.bat)
+else()
+  set(install_package_ARGS "--noprogress;--nox11;--target;${pkg_extracted_dir}")
+  set(install_package_CMD "${PACKAGE_OUTPUT_FILE}")
+  #selftester
+  set(selftester_CMD ${pkg_extracted_dir}/tools/selftester.sh)
+  set(selftester_ARGS)
+  #uninstall OTB
+  set(uninstall_otb_CMD ${pkg_extracted_dir}/tools/uninstall_otb.sh)
+endif()
+add_test(
+  NAME Tu_install_package
+  COMMAND ${install_package_CMD} ${install_package_ARGS}
+  WORKING_DIRECTORY ${testing_dir}
+  )
+
+add_test(
+  NAME Tu_selftester
+  COMMAND ${selftester_CMD} ${selftester_ARGS}
+  WORKING_DIRECTORY ${pkg_extracted_dir}
+  )
+
+add_test(
+  NAME Tu_build_examples
+  COMMAND ${CMAKE_COMMAND}
+  -DSRC_DIR=${CMAKE_SOURCE_DIR}/../Examples
+  -P ${pkg_extracted_dir}/tools/build_examples.cmake
+  WORKING_DIRECTORY ${testing_dir}
+  )
+
+add_test(
+  NAME Tu_uninstall_otb
+  COMMAND ${uninstall_otb_CMD}
+  WORKING_DIRECTORY ${testing_dir}
+  )
+
+#configure test dependencies..
+set_tests_properties ( Tu_selftester PROPERTIES DEPENDS Tu_install_package)
+set_tests_properties ( Tu_build_examples PROPERTIES DEPENDS Tu_selftester)
+set_tests_properties ( Tu_uninstall_otb PROPERTIES DEPENDS Tu_build_examples)
+
+#if(UNIX)
+  #TODO: add test with shellcheck for script files
+#endif()
diff --git a/SuperBuild/CMake/External_boost.cmake b/SuperBuild/CMake/External_boost.cmake
index 8dc75b7a2d4a8e1943dfb19b78a3df7d22bd0851..baff81fc2a466ddd4d98c2d2c7af842de5d76bce 100644
--- a/SuperBuild/CMake/External_boost.cmake
+++ b/SuperBuild/CMake/External_boost.cmake
@@ -71,7 +71,7 @@ set(BOOST_BUILD_COMMAND ${CMAKE_COMMAND}
 #NOTE: update _SB_Boost_INCLUDE_DIR below when you change version number
 ExternalProject_Add(BOOST
   PREFIX BOOST
-  URL "http://download.sourceforge.net/project/boost/boost/1.60.0/boost_1_60_0.tar.bz2"
+  URL "http://downloads.sourceforge.net/project/boost/boost/1.60.0/boost_1_60_0.tar.bz2"
   URL_MD5 65a840e1a0b13a558ff19eeb2c4f0cbe
   BINARY_DIR ${BOOST_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -79,6 +79,7 @@ ExternalProject_Add(BOOST
   CONFIGURE_COMMAND ${BOOST_CONFIGURE_COMMAND}
   BUILD_COMMAND ${BOOST_BUILD_COMMAND}
   INSTALL_COMMAND ""
+  LOG_DOWNLOAD 1
   LOG_CONFIGURE 1
   LOG_BUILD 1
   LOG_INSTALL 1  
diff --git a/SuperBuild/CMake/External_curl.cmake b/SuperBuild/CMake/External_curl.cmake
index fc6fe75d08b1005ea14b66e9e34df5f5398c4c0d..8728bdeb7e8a02c4af70125d157e3cd492862015 100644
--- a/SuperBuild/CMake/External_curl.cmake
+++ b/SuperBuild/CMake/External_curl.cmake
@@ -24,64 +24,41 @@ SETUP_SUPERBUILD(CURL)
 
 # declare dependencies
 ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(CURL ZLIB)
-
 if(NOT APPLE)
-  ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(OPENSSL)
+  ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(CURL OPENSSL)
 endif()
 
-if(MSVC)
-  if(NOT BUILD_SHARED_LIBS)
-    message(FATAL_ERROR "static build or curl not supported")
-    return()
-  endif()
-
-  if(OTB_TARGET_SYSTEM_ARCH_IS_X64)
-    set(CURL_INSTALL_DIR_PREFIX "libcurl-vc-x64")
-  else()
-    set(CURL_INSTALL_DIR_PREFIX "libcurl-vc-x86")
-  endif()
-
-  set(CURL_INSTALL_DIR_PREFIX "${CURL_INSTALL_DIR_PREFIX}-release-dll-zlib-dll-ipv6-sspi-winssl")
-
-  ExternalProject_Add(CURL
+ExternalProject_Add(CURL
   PREFIX CURL
   URL "http://curl.haxx.se/download/curl-7.40.0.tar.gz"
   URL_MD5 58943642ea0ed050ab0431ea1caf3a6f
-  SOURCE_DIR ${CURL_SB_SRC}
-  BINARY_DIR ${CURL_SB_SRC}/winbuild
+  BINARY_DIR ${CURL_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
+  CMAKE_CACHE_ARGS
+  ${SB_CMAKE_CACHE_ARGS}
+  -DBUILD_CURL_TESTS:BOOL=OFF
+  -DBUILD_CURL_EXE:BOOL=ON
+  -DCMAKE_USE_OPENSSL:BOOL=OFF
+  -DCMAKE_USE_LIBSSH2:BOOL=OFF
+  -DCURL_DISABLE_LDAP:BOOL=ON
+  -DCMAKE_USE_OPENLDAP:BOOL=OFF
+  -DENABLE_MANUAL:BOOL=OFF
+  -DENABLE_IPV6:BOOL=OFF
+  ${CURL_SB_CONFIG}
   DEPENDS ${CURL_DEPENDENCIES}
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND nmake /f ${CURL_SB_SRC}/winbuild/Makefile.vc mode=dll WITH_ZLIB=dll WITH_DEVEL=${SB_INSTALL_PREFIX}
-  INSTALL_COMMAND ${CMAKE_COMMAND} -E copy_directory
-  ${CURL_SB_SRC}/builds/${CURL_INSTALL_DIR_PREFIX}/ ${SB_INSTALL_PREFIX}
+  CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
-else(UNIX)
+SUPERBUILD_PATCH_SOURCE(CURL)
 
-  ExternalProject_Add(CURL
-    PREFIX CURL
-    URL "http://curl.haxx.se/download/curl-7.40.0.tar.gz"
-    URL_MD5 58943642ea0ed050ab0431ea1caf3a6f
-    BINARY_DIR ${CURL_SB_BUILD_DIR}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    CMAKE_CACHE_ARGS
-    ${SB_CMAKE_CACHE_ARGS}
-    -DBUILD_CURL_TESTS:BOOL=OFF
-    -DBUILD_CURL_EXE:BOOL=ON
-    -DCMAKE_USE_OPENSSL:BOOL=${SB_ENABLE_OPENSSL_CURL}
-    -DCMAKE_USE_LIBSSH2:BOOL=OFF
-    -DCURL_DISABLE_LDAP:BOOL=ON
-    -DCMAKE_USE_OPENLDAP:BOOL=OFF
-    ${CURL_SB_CONFIG}
-    DEPENDS ${CURL_DEPENDENCIES}
-    CMAKE_COMMAND ${SB_CMAKE_COMMAND}
-    LOG_CONFIGURE 1
-    LOG_BUILD 1
-    LOG_INSTALL 1
-    )
+set(_SB_CURL_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
+if(WIN32)
+  set(_SB_CURL_LIBRARY "${SB_INSTALL_PREFIX}/lib/libcurl_imp.lib")
+elseif(UNIX)
+  set(_SB_CURL_LIBRARY ${SB_INSTALL_PREFIX}/lib/libcurl${CMAKE_SHARED_LIBRARY_SUFFIX})
 endif()
-
-SUPERBUILD_UPDATE_CMAKE_VARIABLES(CURL TRUE)
diff --git a/SuperBuild/CMake/External_expat.cmake b/SuperBuild/CMake/External_expat.cmake
index 2991992a9875afa5735d9a4478288065691c6e14..d59f4391faf8a06f7d8b84d786afef692244a44e 100644
--- a/SuperBuild/CMake/External_expat.cmake
+++ b/SuperBuild/CMake/External_expat.cmake
@@ -24,7 +24,7 @@ SETUP_SUPERBUILD(EXPAT)
 
 ExternalProject_Add(EXPAT
   PREFIX EXPAT
-  URL "http://sourceforge.net/projects/expat/files/expat/2.1.0/expat-2.1.0.tar.gz/download"
+  URL "http://downloads.sourceforge.net/project/expat/expat/2.1.0/expat-2.1.0.tar.gz"
   URL_MD5 dd7dab7a5fea97d2a6a43f511449b7cd
   BINARY_DIR ${EXPAT_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -35,6 +35,10 @@ ExternalProject_Add(EXPAT
   -DBUILD_tests:BOOL=OFF
   -DBUILD_tools:BOOL=OFF
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_UPDATE_CMAKE_VARIABLES(EXPAT FALSE)
diff --git a/SuperBuild/CMake/External_fftw.cmake b/SuperBuild/CMake/External_fftw.cmake
index a6969ab7b225836c475f196d01de19c51383522c..e500caa48039476663f99d2ae0982b547a161ec3 100644
--- a/SuperBuild/CMake/External_fftw.cmake
+++ b/SuperBuild/CMake/External_fftw.cmake
@@ -54,6 +54,8 @@ ExternalProject_Add(FFTWF
   --disable-fortran
   --disable-dependency-tracking
   DEPENDS ${FFTW_DEPENDENCIES}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
   LOG_BUILD 1
   LOG_INSTALL 1
   )
@@ -80,8 +82,10 @@ ExternalProject_Add(FFTWD
   --disable-fortran
   --disable-dependency-tracking
   DEPENDS FFTWF
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
   LOG_BUILD 1
-  LOG_INSTALL 1  
+  LOG_INSTALL 1
   )
 
 
diff --git a/SuperBuild/CMake/External_freetype.cmake b/SuperBuild/CMake/External_freetype.cmake
index 014e35f0ccbc44730f248d9d3f26e9c4a8cb0c48..1af53391eb1546030311305916d1e902696222fa 100644
--- a/SuperBuild/CMake/External_freetype.cmake
+++ b/SuperBuild/CMake/External_freetype.cmake
@@ -39,6 +39,10 @@ ExternalProject_Add(FREETYPE
   ${SB_CMAKE_CACHE_ARGS}
   ${FREETYPE_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_FREETYPE_INCLUDE_DIRS ${SB_INSTALL_PREFIX}/include/freetype2)
diff --git a/SuperBuild/CMake/External_gdal.cmake b/SuperBuild/CMake/External_gdal.cmake
index aa87dc9f44e755b5e1824c90f9a2b01f682c4e45..fd7ed1836132c30fe132e67c14c3add1ca92f11e 100644
--- a/SuperBuild/CMake/External_gdal.cmake
+++ b/SuperBuild/CMake/External_gdal.cmake
@@ -65,7 +65,6 @@ if(UNIX)
     ${SB_CONFIGURE_ARGS}
     --with-cfitsio=no
     --with-dods-root=no
-    --with-dwgdirect=no
     --with-ecw=no
     --with-epsilon=no
     --with-fme=no
@@ -100,6 +99,8 @@ if(UNIX)
     --with-xerces=no
     --with-xml2=no
     --with-pg=no
+    --with-webp=no
+    --with-threads=yes
     ${GDAL_SB_CONFIG}
     ${GDAL_SB_EXTRA_OPTIONS}
     )
@@ -107,8 +108,6 @@ if(UNIX)
   #set(GDAL_INSTALL_COMMAND ${CMAKE_MAKE_PROGRAM} install)
 
 else(MSVC)
-  STRING(REGEX REPLACE "/$" "" CMAKE_WIN_INSTALL_PREFIX ${SB_INSTALL_PREFIX})
-  STRING(REGEX REPLACE "/" "\\\\" CMAKE_WIN_INSTALL_PREFIX ${CMAKE_WIN_INSTALL_PREFIX})
   configure_file(
     ${CMAKE_SOURCE_DIR}/patches/GDAL/nmake_gdal_extra.opt.in
     ${CMAKE_BINARY_DIR}/nmake_gdal_extra.opt)
@@ -133,8 +132,8 @@ endif()
 
 ExternalProject_Add(GDAL
   PREFIX GDAL
-  URL "http://download.osgeo.org/gdal/2.1.0/gdal-2.1.0.tar.gz"
-  URL_MD5 0fc165cd947c54b132204233dfb243f1
+  URL "http://download.osgeo.org/gdal/2.2.1/gdal-2.2.1.tar.gz"
+  URL_MD5 785acf2b0cbf9d56d37c9044d0ee2505
   SOURCE_DIR ${GDAL_SB_SRC}
   BINARY_DIR ${GDAL_SB_SRC}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -143,6 +142,7 @@ ExternalProject_Add(GDAL
   CONFIGURE_COMMAND ${GDAL_CONFIGURE_COMMAND}
   BUILD_COMMAND ${GDAL_BUILD_COMMAND}
   INSTALL_COMMAND ${GDAL_INSTALL_COMMAND}
+  LOG_DOWNLOAD 1
   LOG_CONFIGURE 1
   LOG_BUILD 1
   LOG_INSTALL 1
diff --git a/SuperBuild/CMake/External_geos.cmake b/SuperBuild/CMake/External_geos.cmake
index f129a04379cd304f097e5425df52b29a0c73e913..921aa4d667cf4ba7f621cb8965ca47af08742c61 100644
--- a/SuperBuild/CMake/External_geos.cmake
+++ b/SuperBuild/CMake/External_geos.cmake
@@ -22,23 +22,10 @@ INCLUDE_ONCE_MACRO(GEOS)
 
 SETUP_SUPERBUILD(GEOS)
 
-if(MSVC)
-  set(GEOS_PATCH_COMMAND ${CMAKE_COMMAND} -E copy
-	  ${CMAKE_SOURCE_DIR}/patches/GEOS/CMakeLists.txt
-	  ${CMAKE_SOURCE_DIR}/patches/GEOS/nmake.opt
-	  ${GEOS_SB_SRC})
-  set(GEOS_CMAKE_COMMAND ${SB_CMAKE_COMMAND} -DGEOS_SB_SRC=${GEOS_SB_SRC})
-
-else()
-  set(GEOS_PATCH_COMMAND)
-  set(GEOS_CMAKE_COMMAND ${SB_CMAKE_COMMAND})
-
-endif()
-
 ExternalProject_Add(GEOS
    PREFIX GEOS
-   URL "http://download.osgeo.org/geos/geos-3.5.0.tar.bz2"
-   URL_MD5 136842690be7f504fba46b3c539438dd
+   URL "http://download.osgeo.org/geos/geos-3.6.1.tar.bz2"
+   URL_MD5 c97e338b3bc81f9848656e9d693ca6cc
    SOURCE_DIR ${GEOS_SB_SRC}
    BINARY_DIR ${GEOS_SB_SRC}
    INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -46,17 +33,23 @@ ExternalProject_Add(GEOS
    CMAKE_CACHE_ARGS
    ${SB_CMAKE_CACHE_ARGS}
    -DGEOS_ENABLE_TESTS:BOOL=OFF
-   PATCH_COMMAND ${GEOS_PATCH_COMMAND}
+   -DGEOS_ENABLE_MACOSX_FRAMEWORK:BOOL=OFF
+   -DGEOS_BUILD_STATIC:BOOL=${BUILD_STATIC_LIBS}
+   -DGEOS_BUILD_SHARED:BOOL=${BUILD_SHARED_LIBS}
    CMAKE_COMMAND ${GEOS_CMAKE_COMMAND}
+   LOG_DOWNLOAD 1
+   LOG_CONFIGURE 1
+   LOG_BUILD 1
+   LOG_INSTALL 1
    )
 
-if(NOT MSVC)
-  SUPERBUILD_PATCH_SOURCE(GEOS)
-endif()
+# Patch still needed with version 3.6.1 to avoid error during CMake configuration
+# See https://trac.osgeo.org/geos/ticket/753
+SUPERBUILD_PATCH_SOURCE(GEOS)
 
 set(_SB_GEOS_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 if(WIN32)
-  set(_SB_GEOS_LIBRARY ${SB_INSTALL_PREFIX}/lib/geos_i.lib )
+  set(_SB_GEOS_LIBRARY ${SB_INSTALL_PREFIX}/lib/geos.lib )
 elseif(UNIX)
   set(_SB_GEOS_LIBRARY ${SB_INSTALL_PREFIX}/lib/libgeos${CMAKE_SHARED_LIBRARY_SUFFIX})
-endif()
\ No newline at end of file
+endif()
diff --git a/SuperBuild/CMake/External_geotiff.cmake b/SuperBuild/CMake/External_geotiff.cmake
index 99babdd855a58186668364bbea4be881fb3ff479..cc557b761129c10cca2209856cb1684a592a526f 100644
--- a/SuperBuild/CMake/External_geotiff.cmake
+++ b/SuperBuild/CMake/External_geotiff.cmake
@@ -35,59 +35,28 @@ ADD_SUPERBUILD_CMAKE_VAR(GEOTIFF ZLIB_LIBRARY)
 ADD_SUPERBUILD_CMAKE_VAR(GEOTIFF JPEG_INCLUDE_DIR)
 ADD_SUPERBUILD_CMAKE_VAR(GEOTIFF JPEG_LIBRARY)
 
-#RK: we are forced to use autoconf on osx due to cmake's find_* functions
-#Do we need to use the same of Linux ?
-if(UNIX)
-  set(GEOTIFF_SB_CONFIG)
-  ADD_SUPERBUILD_CONFIGURE_VAR(GEOTIFF PROJ_ROOT     --with-proj)
-  ADD_SUPERBUILD_CONFIGURE_VAR(GEOTIFF TIFF_ROOT     --with-libtiff)
-  ADD_SUPERBUILD_CONFIGURE_VAR(GEOTIFF JPEG_ROOT     --with-jpeg)
-  ADD_SUPERBUILD_CONFIGURE_VAR(GEOTIFF ZLIB_ROOT     --with-libz)
+ExternalProject_Add(GEOTIFF
+  PREFIX GEOTIFF
+  URL "http://download.osgeo.org/geotiff/libgeotiff/libgeotiff-1.4.2.tar.gz"
+  URL_MD5 96ab80e0d4eff7820579957245d844f8
+  SOURCE_DIR ${GEOTIFF_SB_SRC}
+  BINARY_DIR ${GEOTIFF_SB_BUILD_DIR}
+  INSTALL_DIR ${SB_INSTALL_PREFIX}
+  DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
+  DEPENDS ${GEOTIFF_DEPENDENCIES}
+  CMAKE_CACHE_ARGS
+  ${SB_CMAKE_CACHE_ARGS}
+  -DBUILD_TESTING:BOOL=OFF
+  -DPROJ4_OSGEO4W_HOME:PATH=${SB_INSTALL_PREFIX}
+  ${GEOTIFF_SB_CONFIG}
+  CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
+  )
 
-  ExternalProject_Add(GEOTIFF
-    PREFIX GEOTIFF
-    URL "http://download.osgeo.org/geotiff/libgeotiff/libgeotiff-1.4.1.tar.gz"
-    URL_MD5 48bdf817e6e7a37671cc1f41b01e10fc
-    SOURCE_DIR ${GEOTIFF_SB_SRC}
-    BINARY_DIR ${GEOTIFF_SB_SRC}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    DEPENDS ${GEOTIFF_DEPENDENCIES}
-    CONFIGURE_COMMAND
-    ${SB_ENV_CONFIGURE_CMD}
-    ${GEOTIFF_SB_SRC}/configure
-    ${SB_CONFIGURE_ARGS}
-    ${GEOTIFF_SB_CONFIG}
-    LOG_BUILD 1
-    LOG_INSTALL 1
-    )
-
-  # [LOG_CONFIGURE 1]           # Wrap configure in script to log output
-  # [LOG_BUILD 1]               # Wrap build in script to log output
-  # [LOG_TEST 1]                # Wrap test in script to log output
-  # [LOG_INSTALL 1]             # Wrap install in script to log output
-  SUPERBUILD_PATCH_SOURCE(GEOTIFF)
-
-else()
-
-  ExternalProject_Add(GEOTIFF
-    PREFIX GEOTIFF
-    URL "http://download.osgeo.org/geotiff/libgeotiff/libgeotiff-1.4.1.tar.gz"
-    URL_MD5 48bdf817e6e7a37671cc1f41b01e10fc
-    SOURCE_DIR ${GEOTIFF_SB_SRC}
-    BINARY_DIR ${GEOTIFF_SB_BUILD_DIR}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    DEPENDS ${GEOTIFF_DEPENDENCIES}
-    CMAKE_CACHE_ARGS
-    ${SB_CMAKE_CACHE_ARGS}
-    -DBUILD_TESTING:BOOL=OFF
-    -DPROJ4_OSGEO4W_HOME:PATH=${SB_INSTALL_PREFIX}
-    ${GEOTIFF_SB_CONFIG}
-    CMAKE_COMMAND ${SB_CMAKE_COMMAND}
-    )
-
-endif()
+SUPERBUILD_PATCH_SOURCE(GEOTIFF)
 
 set(_SB_GEOTIFF_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 if(WIN32)
diff --git a/SuperBuild/CMake/External_glew.cmake b/SuperBuild/CMake/External_glew.cmake
index 769ba0b808c3b8e83539e3dce0c3bb90501aad56..3f370e28e0642d584cfbdecfb881fa28d71a07e4 100644
--- a/SuperBuild/CMake/External_glew.cmake
+++ b/SuperBuild/CMake/External_glew.cmake
@@ -24,13 +24,17 @@ SETUP_SUPERBUILD(GLEW)
 
 ExternalProject_Add(GLEW
   PREFIX GLEW
-  URL "https://sourceforge.net/projects/glew/files/glew/1.13.0/glew-1.13.0.tgz/download"
+  URL "https://downloads.sourceforge.net/project/glew/glew/1.13.0/glew-1.13.0.tgz"
   URL_MD5 7cbada3166d2aadfc4169c4283701066
   SOURCE_DIR ${GLEW_SB_SRC}
   BINARY_DIR ${GLEW_SB_BUILD_DIR}
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
   CONFIGURE_COMMAND ${SB_CMAKE_COMMAND} ${SB_CMAKE_CACHE_ARGS} -DBUILD_UTILS:BOOL=OFF ${GLEW_SB_SRC}/build/cmake/
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_PATCH_SOURCE(GLEW)
diff --git a/SuperBuild/CMake/External_glfw.cmake b/SuperBuild/CMake/External_glfw.cmake
index ed7285bd7cfff094d8754c1feb65e8bf09e0b29b..62e2ee046d0dbd1f1b83c6adb2ef13a834d4a9e0 100644
--- a/SuperBuild/CMake/External_glfw.cmake
+++ b/SuperBuild/CMake/External_glfw.cmake
@@ -35,4 +35,10 @@ ExternalProject_Add(GLFW
   -DGLFW_BUILD_DOCS:BOOL=OFF
   -DGLFW_BUILD_TESTS:BOOL=OFF
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
+
+SUPERBUILD_PATCH_SOURCE(GLFW)
diff --git a/SuperBuild/CMake/External_glut.cmake b/SuperBuild/CMake/External_glut.cmake
index 3299afd9b35d353890c6775ffffe88ccf198757a..8894a4931c3619b58bb01125b85494ecf2fbb37c 100644
--- a/SuperBuild/CMake/External_glut.cmake
+++ b/SuperBuild/CMake/External_glut.cmake
@@ -53,6 +53,10 @@ ExternalProject_Add(GLUT
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   PATCH_COMMAND ${GLUT_PATCH_COMMAND}
   CONFIGURE_COMMAND ${GLUT_CONFIGURE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_GLUT_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
diff --git a/SuperBuild/CMake/External_itk.cmake b/SuperBuild/CMake/External_itk.cmake
index d46abbc7f9e55233b27047cca25a64244af3daa5..d0337bb39acc561ec6ae2080ed8264de35412f46 100644
--- a/SuperBuild/CMake/External_itk.cmake
+++ b/SuperBuild/CMake/External_itk.cmake
@@ -126,11 +126,8 @@ if (WIN32)
   list(APPEND ITK_SB_CONFIG
     -DUSE_FFTWF:BOOL=OFF
     -DUSE_FFTWD:BOOL=OFF
+    -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS:BOOL=ON
     )
-  if(MSVC AND BUILD_SHARED_LIBS)
-    list(APPEND ITK_SB_CONFIG
-      -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS:BOOL=TRUE)
-  endif()
 else()
   list(APPEND ITK_SB_CONFIG
     -DUSE_FFTWF:BOOL=ON
@@ -140,33 +137,22 @@ else()
   ADD_SUPERBUILD_CMAKE_VAR(ITK FFTW_INCLUDE_PATH)
 endif()
 
-# forward compilation flags
-set(ITK_SB_COMPILATION_FLAGS
-  -DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}
-  -DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS}
-  -DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS}
-  -DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS}
-  -DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS}
-  -DCMAKE_STATIC_LINKER_FLAGS:STRING=${CMAKE_STATIC_LINKER_FLAGS}
-  )
-
 #variables are later used in packaging
 set(SB_ITK_VERSION_MAJOR "4")
-set(SB_ITK_VERSION_MINOR "10")
+set(SB_ITK_VERSION_MINOR "12")
 
 set(_SB_ITK_DIR ${SB_INSTALL_PREFIX}/lib/cmake/ITK-${SB_ITK_VERSION_MAJOR}.${SB_ITK_VERSION_MINOR})
 
 ExternalProject_Add(ITK
   PREFIX ITK
-  URL "http://downloads.sourceforge.net/project/itk/itk/4.10/InsightToolkit-4.10.0.tar.gz"
-  URL_MD5 8c67ba296da3835fb67bb29d98dcff3e
+  URL "https://sourceforge.net/projects/itk/files/itk/4.12/InsightToolkit-4.12.0.tar.gz"
+  URL_MD5 561a403f93c88c64085b5623e8e61f79
   SOURCE_DIR ${ITK_SB_SRC}
   BINARY_DIR ${ITK_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   CMAKE_CACHE_ARGS
   ${SB_CMAKE_CACHE_ARGS}
-  ${ITK_SB_COMPILATION_FLAGS}
   -DITK_BUILD_DEFAULT_MODULES:BOOL=OFF
   ${ITK_MODULES_CMAKE_CACHE}
   -DITKGroup_Core:BOOL=OFF
@@ -180,6 +166,10 @@ ExternalProject_Add(ITK
   ${ITK_SB_CONFIG}
   DEPENDS ${ITK_DEPENDENCIES}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_PATCH_SOURCE(ITK)
diff --git a/SuperBuild/CMake/External_jpeg.cmake b/SuperBuild/CMake/External_jpeg.cmake
index 0a4fca1b69d3debed537887ce4d71ecf7da60679..38e1460e508505e880d72656f47142ce118d3ee2 100644
--- a/SuperBuild/CMake/External_jpeg.cmake
+++ b/SuperBuild/CMake/External_jpeg.cmake
@@ -45,13 +45,17 @@ endif()
 
 ExternalProject_Add(JPEG
   PREFIX JPEG
-  URL "http://sourceforge.net/projects/libjpeg-turbo/files/1.4.1/libjpeg-turbo-1.4.1.tar.gz"
+  URL "http://downloads.sourceforge.net/project/libjpeg-turbo/1.4.1/libjpeg-turbo-1.4.1.tar.gz"
   URL_MD5 b1f6b84859a16b8ebdcda951fa07c3f2
   SOURCE_DIR ${JPEG_SB_SRC}
   BINARY_DIR ${JPEG_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   CONFIGURE_COMMAND ${JPEG_CONFIGURE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_PATCH_SOURCE(JPEG)
diff --git a/SuperBuild/CMake/External_libkml.cmake b/SuperBuild/CMake/External_libkml.cmake
index 4d412687de14f6a74ef470cc02d0431713f6773b..e330ab05f7f5809a07ebf78dd7f0a980dde81522 100644
--- a/SuperBuild/CMake/External_libkml.cmake
+++ b/SuperBuild/CMake/External_libkml.cmake
@@ -44,7 +44,10 @@ ExternalProject_Add(LIBKML
   CMAKE_CACHE_ARGS ${SB_CMAKE_CACHE_ARGS}
   ${LIBKML_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
-  LOG_BUILD 1  
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_LIBKML_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
diff --git a/SuperBuild/CMake/External_libsvm.cmake b/SuperBuild/CMake/External_libsvm.cmake
index 4a903c3e59c2d3bfe2ef7adc802051f34d19f33e..435c6d280c5faeb2bf5d2152cc3381c16a9f783b 100644
--- a/SuperBuild/CMake/External_libsvm.cmake
+++ b/SuperBuild/CMake/External_libsvm.cmake
@@ -35,6 +35,10 @@ ExternalProject_Add(LIBSVM
   PATCH_COMMAND ${CMAKE_COMMAND} -E copy
   ${CMAKE_SOURCE_DIR}/patches/LIBSVM/CMakeLists.txt
   ${LIBSVM_SB_SRC}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_LIBSVM_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
diff --git a/SuperBuild/CMake/External_muparser.cmake b/SuperBuild/CMake/External_muparser.cmake
index 20bb3ca23b068de7b6fb6ca0af2b4f991a9ac19f..669cd29da28b2979529ca4b5da69608c66ac2aae 100644
--- a/SuperBuild/CMake/External_muparser.cmake
+++ b/SuperBuild/CMake/External_muparser.cmake
@@ -35,6 +35,10 @@ ExternalProject_Add(MUPARSER
   PATCH_COMMAND ${CMAKE_COMMAND} -E copy
   ${CMAKE_SOURCE_DIR}/patches/MUPARSER/CMakeLists.txt
   ${MUPARSER_SB_SRC}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
-SUPERBUILD_UPDATE_CMAKE_VARIABLES(MUPARSER FALSE)
\ No newline at end of file
+SUPERBUILD_UPDATE_CMAKE_VARIABLES(MUPARSER FALSE)
diff --git a/SuperBuild/CMake/External_muparserx.cmake b/SuperBuild/CMake/External_muparserx.cmake
index a946a0da64a7e44fcc6f45e329015fa9272bf91d..8ab61cc0bded8540f42049b166b2fca5b6ddc2ee 100644
--- a/SuperBuild/CMake/External_muparserx.cmake
+++ b/SuperBuild/CMake/External_muparserx.cmake
@@ -22,12 +22,11 @@ INCLUDE_ONCE_MACRO(MUPARSERX)
 
 SETUP_SUPERBUILD(MUPARSERX)
 
-#Don't build muparserx examples
-set(MUPARSERX_FLAGS)
-list(APPEND MUPARSERX_FLAGS -DBUILD_EXAMPLES:BOOL=OFF)
-
+set(MUPARSERX_SB_CONFIG)
 if(MSVC AND BUILD_SHARED_LIBS)
- list(APPEND MUPARSERX_FLAGS -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS:BOOL=ON)
+  list(APPEND
+    MUPARSERX_SB_CONFIG
+    -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS:BOOL=TRUE)
 endif()
 
 ExternalProject_Add(MUPARSERX
@@ -39,9 +38,14 @@ ExternalProject_Add(MUPARSERX
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   CMAKE_CACHE_ARGS
   ${SB_CMAKE_CACHE_ARGS}
-  ${MUPARSERX_FLAGS}
+  -DBUILD_EXAMPLES:BOOL=OFF
+  ${MUPARSERX_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
   DEPENDS ${MUPARSERX_DEPENDENCIES}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 #Patch mpParserMessageProvider.cpp. This patch is integrated upstream but not yet released (last release is 4.0.7)
diff --git a/SuperBuild/CMake/External_mvd.cmake b/SuperBuild/CMake/External_mvd.cmake
deleted file mode 100644
index b3bf91b18f2b96a49e94fc8d1186f6fe75ab3abe..0000000000000000000000000000000000000000
--- a/SuperBuild/CMake/External_mvd.cmake
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-if( __EXTERNAL_MVD__)
-  return()
-else()
-  set(__EXTERNAL_MVD__ 1)
-endif()
-
-SETUP_SUPERBUILD(MVD)
-
-set(MONTEVERDI_GIT_TAG "develop" CACHE STRING "branch name of monteverdi to build. Default is 'develop'")
-
-# declare dependencies
-ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(MVD OTB QWT QT4)
-
-set(MVD_SB_CONFIG)
-ADD_SUPERBUILD_CMAKE_VAR(MVD OTB_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(MVD QWT_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(MVD QWT_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(MVD QT_QMAKE_EXECUTABLE)
-
-#TODO: control build testing via cmake variable properly
-
-ExternalProject_Add(MVD
-  PREFIX MVD
-  GIT_REPOSITORY "https://git@git.orfeo-toolbox.org/git/monteverdi2.git"
-  GIT_TAG "${MONTEVERDI_GIT_TAG}"
-  SOURCE_DIR ${MVD_SB_SRC}
-  BINARY_DIR ${MVD_SB_BUILD_DIR}
-  INSTALL_DIR ${CMAKE_INSTALL_PREFIX}
-  DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-  DEPENDS ${MVD_DEPENDENCIES}
-  CMAKE_CACHE_ARGS ${SB_CMAKE_CACHE_ARGS}
-  -DMonteverdi_INSTALL_LIB_DIR:STRING=lib
-  -DOTB_DATA_ROOT:STRING=${OTB_DATA_ROOT}
-  ${MVD_SB_CONFIG}
-  CMAKE_COMMAND ${SB_CMAKE_COMMAND}
-)
diff --git a/SuperBuild/CMake/External_opencv.cmake b/SuperBuild/CMake/External_opencv.cmake
index 854d09de427b0a9c86456694c46f98b3ca55e8f4..675777f3e8ef080192d0bfdd6741b40ed8332237 100644
--- a/SuperBuild/CMake/External_opencv.cmake
+++ b/SuperBuild/CMake/External_opencv.cmake
@@ -100,6 +100,10 @@ ExternalProject_Add(OPENCV
   ${OPENCV_SB_CONFIG}
   DEPENDS ${OPENCV_DEPENDENCIES}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 
diff --git a/SuperBuild/CMake/External_openjpeg.cmake b/SuperBuild/CMake/External_openjpeg.cmake
index cabb84509f4821470b7c09da4b8ce7cd52057ca4..09de9cb472905cfb0473061051b6447d217ec556 100644
--- a/SuperBuild/CMake/External_openjpeg.cmake
+++ b/SuperBuild/CMake/External_openjpeg.cmake
@@ -56,9 +56,13 @@ ExternalProject_Add(OPENJPEG
   ${OPENJPEG_SB_CONFIG}
   DEPENDS ${OPENJPEG_DEPENDENCIES}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_UPDATE_CMAKE_VARIABLES(OPENJPEG FALSE)
 
-#Apply patches to openjpeg (for now Even Roualt optim)
+#Apply patches to openjpeg (for now Even Rouault optimizations)
 SUPERBUILD_PATCH_SOURCE(OPENJPEG "-ut")
diff --git a/SuperBuild/CMake/External_openssl.cmake b/SuperBuild/CMake/External_openssl.cmake
index e398c44a89274d9ba61ea0adcdb424608f0d1cd3..80dbcccca0c781b33783ea50c2dafbfc9616c8dc 100644
--- a/SuperBuild/CMake/External_openssl.cmake
+++ b/SuperBuild/CMake/External_openssl.cmake
@@ -25,32 +25,43 @@ SETUP_SUPERBUILD(OPENSSL)
 ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(OPENSSL ZLIB)
 
 if(WIN32)
+  find_program(PERL_COMMAND NAMES perl perl.exe)
+  if(NOT PERL_COMMAND)
+    message(FATAL_ERROR "PERL_COMMAND not set. it is needed to configure openssl!")
+    return()
+  endif()
+
   set(OPENSSL_BUILD_ARCH "linux-x32")
   set(OPENSSL_BUILD_ARCH "VC-WIN32")
+  set(OPENSSL_CONFIGURE_CMD "${OPENSSL_SB_SRC}/ms/do_ms.bat")
   if(CMAKE_SIZEOF_VOID_P EQUAL 8)
     set(OPENSSL_BUILD_ARCH "linux-x86_64")
     set(OPENSSL_BUILD_ARCH "VC-WIN64A")
+    set(OPENSSL_CONFIGURE_CMD "${OPENSSL_SB_SRC}/ms/do_win64a.bat")
   endif()
 endif()
 
 if(MSVC)
-  STRING(REGEX REPLACE "/$" "" CMAKE_WIN_INSTALL_PREFIX ${SB_INSTALL_PREFIX})
-  STRING(REGEX REPLACE "/" "\\\\" CMAKE_WIN_INSTALL_PREFIX ${CMAKE_WIN_INSTALL_PREFIX})
   ExternalProject_Add(OPENSSL
     PREFIX OPENSSL
     URL "https://github.com/openssl/openssl/archive/OpenSSL_1_0_1p.tar.gz"
     URL_MD5 6bc1f9a9d9d474aceceb377e758e48ec
     DEPENDS ${OPENSSL_DEPENDENCIES}
-    BINARY_DIR ${OPENSSL_SB_BUILD_DIR}
+    BINARY_DIR ${OPENSSL_SB_SRC}
     INSTALL_DIR ${SB_INSTALL_PREFIX}
     DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    PATCH_COMMAND  ${CMAKE_COMMAND} -E copy_directory ${OPENSSL_SB_SRC} ${OPENSSL_SB_BUILD_DIR}
-    CONFIGURE_COMMAND
-    ${SB_ENV_CONFIGURE_CMD}
-    ${CMAKE_COMMAND} -E chdir ${OPENSSL_SB_BUILD_DIR}
-    perl Configure ${OPENSSL_BUILD_ARCH} no-asm  --prefix=${CMAKE_WIN_INSTALL_PREFIX} --openssldir=${CMAKE_WIN_INSTALL_PREFIX}
-    BUILD_COMMAND ms/do_ms.bat
-    INSTALL_COMMAND nmake -f ms/ntdll.mak install
+    PATCH_COMMAND ${PERL_COMMAND} ${OPENSSL_SB_SRC}/Configure
+    ${OPENSSL_BUILD_ARCH}
+    no-asm
+    "--prefix=${SB_INSTALL_PREFIX_NATIVE}"
+    "--openssldir=${SB_INSTALL_PREFIX_NATIVE}"
+    CONFIGURE_COMMAND ${OPENSSL_CONFIGURE_CMD}
+    BUILD_COMMAND nmake -f "${OPENSSL_SB_SRC}/ms/ntdll.mak"
+    INSTALL_COMMAND nmake -f "${OPENSSL_SB_SRC}/ms/ntdll.mak" install
+    LOG_DOWNLOAD 1
+    LOG_CONFIGURE 1
+    LOG_BUILD 1
+    LOG_INSTALL 1
     )
 
 else(UNIX)
@@ -59,16 +70,25 @@ else(UNIX)
     DEPENDS ${OPENSSL_DEPENDENCIES}
     URL "https://github.com/openssl/openssl/archive/OpenSSL_1_0_1p.tar.gz"
     URL_MD5 6bc1f9a9d9d474aceceb377e758e48ec
-    BINARY_DIR ${OPENSSL_SB_BUILD_DIR}
+    BINARY_DIR ${OPENSSL_SB_SRC}
     INSTALL_DIR ${SB_INSTALL_PREFIX}
     DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    PATCH_COMMAND  ${CMAKE_COMMAND} -E copy_directory ${OPENSSL_SB_SRC} ${OPENSSL_SB_BUILD_DIR}
     CONFIGURE_COMMAND
     ${SB_ENV_CONFIGURE_CMD}
-    ${CMAKE_COMMAND} -E chdir ${OPENSSL_SB_BUILD_DIR} ./config ${OPENSSL_BUILD_ARCH}
-    --prefix=${SB_INSTALL_PREFIX} shared zlib zlib-dynamic -I${SB_INSTALL_PREFIX}/include -L${SB_INSTALL_PREFIX}/lib
+    ${OPENSSL_SB_SRC}/config ${OPENSSL_BUILD_ARCH}
+    "--prefix=${SB_INSTALL_PREFIX}"
+    shared
+    zlib
+    zlib-dynamic
+    "-I${SB_INSTALL_PREFIX}/include"
+    "-L${SB_INSTALL_PREFIX}/lib"
     BUILD_COMMAND $(MAKE)
-    INSTALL_COMMAND $(MAKE) install)
+    INSTALL_COMMAND $(MAKE) install
+    LOG_DOWNLOAD 1
+    LOG_CONFIGURE 1
+    LOG_BUILD 1
+    LOG_INSTALL 1
+    )
 
   ExternalProject_Add_Step(OPENSSL remove_static
     COMMAND ${CMAKE_COMMAND} -E remove
@@ -82,7 +102,7 @@ endif()
 
 set(_SB_OPENSSL_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 if(WIN32)
-  set(_SB_OPENSSL_LIBRARY ${SB_INSTALL_PREFIX}/lib/libcurl.lib)
+  set(_SB_OPENSSL_LIBRARY "${SB_INSTALL_PREFIX}/lib/ssleay32.lib;${SB_INSTALL_PREFIX}/lib/libeay32.lib")
 elseif(UNIX)
   set(_SB_OPENSSL_LIBRARY ${SB_INSTALL_PREFIX}/lib/libssl${CMAKE_SHARED_LIBRARY_SUFFIX})
 endif()
diff --git a/SuperBuild/CMake/External_openthreads.cmake b/SuperBuild/CMake/External_openthreads.cmake
index bf783fd625a753991e6311078a2c392ad5328ff4..43661aa81cbdc81d382f5cec078dca61c860f691 100644
--- a/SuperBuild/CMake/External_openthreads.cmake
+++ b/SuperBuild/CMake/External_openthreads.cmake
@@ -37,6 +37,10 @@ ExternalProject_Add(OPENTHREADS
   PATCH_COMMAND ${CMAKE_COMMAND} -E copy
   ${CMAKE_SOURCE_DIR}/patches/OPENTHREADS/CMakeLists.txt
   ${OPENTHREADS_SB_SRC}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_OPENTHREADS_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
diff --git a/SuperBuild/CMake/External_ossim.cmake b/SuperBuild/CMake/External_ossim.cmake
index 8347a3cb854486d43b833a8105138e557f2c360d..04d89d5f3ba6c207b726d4c9cfc4351d06b275b3 100644
--- a/SuperBuild/CMake/External_ossim.cmake
+++ b/SuperBuild/CMake/External_ossim.cmake
@@ -67,6 +67,10 @@ ExternalProject_Add(OSSIM
   ${OSSIM_SB_CONFIG}
   DEPENDS ${OSSIM_DEPENDENCIES}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 ExternalProject_Add_Step(OSSIM patch_no_cmakelists
diff --git a/SuperBuild/CMake/External_otb.cmake b/SuperBuild/CMake/External_otb.cmake
index b4a7107a176fd1222f949d61632e5a1d38aab8a7..465683a9b48222947d20f7fdf5354dc4d8f6c0ce 100644
--- a/SuperBuild/CMake/External_otb.cmake
+++ b/SuperBuild/CMake/External_otb.cmake
@@ -35,15 +35,15 @@ if(OTB_USE_CURL)
 endif()
 
 if(OTB_USE_LIBKML)
-    ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(OTB LIBKML)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_INCLUDE_DIR)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_BASE_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_CONVENIENCE_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_DOM_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_ENGINE_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_REGIONATOR_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_XSD_LIBRARY)
-    ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_MINIZIP_LIBRARY)
+  ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(OTB LIBKML)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_INCLUDE_DIR)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_BASE_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_CONVENIENCE_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_DOM_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_ENGINE_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_REGIONATOR_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_XSD_LIBRARY)
+  ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_MINIZIP_LIBRARY)
 endif()
 
 if(OTB_USE_OPENCV)
@@ -128,46 +128,16 @@ ADD_SUPERBUILD_CMAKE_VAR(OTB TINYXML_LIBRARY)
 ADD_SUPERBUILD_CMAKE_VAR(OTB Boost_INCLUDE_DIR)
 ADD_SUPERBUILD_CMAKE_VAR(OTB Boost_LIBRARY_DIR)
 
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_BASE_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_CONVENIENCE_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_DOM_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_ENGINE_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_REGIONATOR_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_XSD_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBKML_MINIZIP_LIBRARY)
 
-ADD_SUPERBUILD_CMAKE_VAR(OTB OpenCV_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(OTB Shark_DIR)
-
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBSVM_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(OTB LIBSVM_LIBRARY)
-
-if(OTB_USE_CURL)
-ADD_SUPERBUILD_CMAKE_VAR(OTB CURL_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(OTB CURL_LIBRARY)
+set(OTB_MODULES_CONFIG)
+if(WITH_REMOTE_MODULES)
+  foreach(remote_module SertitObject Mosaic otbGRM)
+    list(APPEND OTB_MODULES_CONFIG -DModule_${remote_module}:BOOL=ON)
+  endforeach()
+else()
+  set(OTB_MODULES_CONFIG)
 endif()
 
-if(MSVC)
-  ADD_SUPERBUILD_CMAKE_VAR(OTB JPEG_LIBRARY)
-endif()
-  
-# forward compilation flags
-set(OTB_SB_C_FLAGS "${SB_PRIOR_INCLUDE_FLAGS} ${CMAKE_C_FLAGS} ")
-set(OTB_SB_CXX_FLAGS "${SB_PRIOR_INCLUDE_FLAGS} ${CMAKE_CXX_FLAGS}")
-
-if(MSVC)
-  set(OTB_SB_CXX_FLAGS "${OTB_SB_CXX_FLAGS} /EHsc /DNOMINMAX")
-endif()
-
-set(OTB_SB_COMPILATION_FLAGS
-  -DCMAKE_C_FLAGS:STRING=${OTB_SB_C_FLAGS}
-  -DCMAKE_CXX_FLAGS:STRING=${OTB_SB_CXX_FLAGS}
-  -DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS}
-  -DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS}
-  -DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS}
-  -DCMAKE_STATIC_LINKER_FLAGS:STRING=${CMAKE_STATIC_LINKER_FLAGS}
-  )
 
 add_custom_command(OUTPUT otb_depends_done.txt
   COMMAND cmake -E touch otb_depends_done.txt
@@ -192,7 +162,7 @@ ExternalProject_Add(OTB
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   CMAKE_CACHE_ARGS
   ${SB_CMAKE_CACHE_ARGS}
-  ${OTB_SB_COMPILATION_FLAGS}
+  ${OTB_MODULES_CONFIG}
   -DBUILD_TESTING:BOOL=${BUILD_TESTING}
   -DBUILD_EXAMPLES:BOOL=${BUILD_EXAMPLES}
   -DOTB_DATA_ROOT:STRING=${OTB_DATA_ROOT}
@@ -214,10 +184,9 @@ ExternalProject_Add(OTB
   -DOTB_USE_GLFW:BOOL=${OTB_USE_GLFW}
   -DOTB_USE_GLUT:BOOL=${OTB_USE_GLUT}
   -DOTB_USE_QWT:BOOL=${OTB_USE_QWT}
+  -DOTB_USE_OPENMP:BOOL=${OTB_USE_OPENMP}
   -DOTB_WRAP_PYTHON:BOOL=${OTB_WRAP_PYTHON}
   -DOTB_WRAP_JAVA:BOOL=${OTB_WRAP_JAVA}
-  -DGENERATE_PACKAGE:BOOL=OFF
-  -DGENERATE_XDK:BOOL=OFF  
   ${OTB_ADDITIONAL_CACHE}
   CMAKE_ARGS ${OTB_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
diff --git a/SuperBuild/CMake/External_pcre.cmake b/SuperBuild/CMake/External_pcre.cmake
index 717f09f576d2fe2f638a154c33019bc8c300fdd8..aefa89e5b535315fef74cee9bff3ed2d0bbb18ba 100644
--- a/SuperBuild/CMake/External_pcre.cmake
+++ b/SuperBuild/CMake/External_pcre.cmake
@@ -25,7 +25,7 @@ if(MSVC)
 else()
   ExternalProject_Add(PCRE
     PREFIX PCRE
-    URL "http://sourceforge.net/projects/pcre/files/pcre/8.36/pcre-8.36.tar.gz/download"
+    URL "http://downloads.sourceforge.net/project/pcre/pcre/8.36/pcre-8.36.tar.gz"
     URL_MD5 ff7b4bb14e355f04885cf18ff4125c98
     BINARY_DIR ${PCRE_SB_BUILD_DIR}
     INSTALL_DIR ${SB_INSTALL_PREFIX}
diff --git a/SuperBuild/CMake/External_pkgtools.cmake b/SuperBuild/CMake/External_pkgtools.cmake
deleted file mode 100644
index 0d137545280063561a6091367bb5a0e99bd222c8..0000000000000000000000000000000000000000
--- a/SuperBuild/CMake/External_pkgtools.cmake
+++ /dev/null
@@ -1,89 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-set(PKGTOOLS_SB_PREFIX_DIR "${CMAKE_BINARY_DIR}/PACKAGE-TOOLS")
-
-set(PATCHELF_SOURCE_DIR  "${PKGTOOLS_SB_PREFIX_DIR}/src/patchelf")
-# PATCHELF_BINARY_DIR is same as PATCHELF_SOURCE_DIR
-set(PATCHELF_INSTALL_DIR "${PKGTOOLS_SB_PREFIX_DIR}/install/patchelf")
-set(PATCHELF_STAMP_DIR   "${PKGTOOLS_SB_PREFIX_DIR}/stamp/patchelf")
-set(PATCHELF_TMP_DIR     "${PKGTOOLS_SB_PREFIX_DIR}/tmp/patchelf")
-
-#This variable is referenced in CreateCMakeProjects.cmake
-set(PATCHELF_PROGRAM "${PATCHELF_SOURCE_DIR}/src/patchelf")
-
-
-set(MAKESELF_SOURCE_DIR  "${PKGTOOLS_SB_PREFIX_DIR}/src/makeself")
-# MAKESELF_SOURCE_DIR is same as MAKESELF_BINARY_DIR and MAKESELF_INSTALL_DIR
-set(MAKESELF_STAMP_DIR   "${PKGTOOLS_SB_PREFIX_DIR}/stamp/makeself")
-set(MAKESELF_TMP_DIR     "${PKGTOOLS_SB_PREFIX_DIR}/tmp/makeself")
-
-#This variable is referenced in CreateCMakeProjects.cmake
-set(MAKESELF_SCRIPT "${MAKESELF_SOURCE_DIR}/makeself.sh")
-
-if( __EXTERNAL_PACKAGE_TOOLS__)
-  return()
-else()
-  set(__EXTERNAL_PACKAGE_TOOLS__ 1)
-endif()
-
-if(WIN32)
-  add_custom_target(PACKAGE-TOOLS)
-  return()
-endif()
-
-include(ExternalProject)
-
-
-if(APPLE)
-  add_custom_target(PATCHELF)
-else()
-  ExternalProject_Add(PATCHELF
-    PREFIX "${PKGTOOLS_SB_PREFIX_DIR}"
-    URL                 "http://nixos.org/releases/patchelf/patchelf-0.9/patchelf-0.9.tar.bz2"
-    URL_MD5             d02687629c7e1698a486a93a0d607947
-    DOWNLOAD_DIR        "${DOWNLOAD_LOCATION}"
-    SOURCE_DIR          "${PATCHELF_SOURCE_DIR}"
-    BINARY_DIR          "${PATCHELF_SOURCE_DIR}"
-    INSTALL_DIR         "${PATCHELF_INSTALL_DIR}"
-    STAMP_DIR           "${PATCHELF_STAMP_DIR}"
-    TMP_DIR             "${PATCHELF_TMP_DIR}"
-    CONFIGURE_COMMAND "./configure" "--prefix" "${PATCHELF_INSTALL_DIR}"
-    INSTALL_COMMAND ""
-    )
-endif()
-
-ExternalProject_Add(MAKESELF
-  PREFIX            "${PKGTOOLS_SB_PREFIX_DIR}"
-  URL               "https://www.orfeo-toolbox.org/packages/makeself-2.2.0.tar.gz"
-  URL_MD5           3c61df934b0c61ddcd7bd63b391e951d
-  DOWNLOAD_DIR      "${DOWNLOAD_LOCATION}"
-  SOURCE_DIR        "${MAKESELF_SOURCE_DIR}"
-  BINARY_DIR        "${MAKESELF_SOURCE_DIR}"
-  INSTALL_DIR       "${MAKESELF_SOURCE_DIR}"
-  STAMP_DIR         "${MAKESELF_STAMP_DIR}"
-  TMP_DIR           "${MAKESELF_TMP_DIR}"
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND ""
-  INSTALL_COMMAND ""
-  DEPENDS PATCHELF
-  )
-
-add_custom_target(PACKAGE-TOOLS DEPENDS MAKESELF)
diff --git a/SuperBuild/CMake/External_png.cmake b/SuperBuild/CMake/External_png.cmake
index 1d2d16148dddfef8363f12a002785ca364d96b57..cd149a67b88e1741c912623d7f8f28957a228850 100644
--- a/SuperBuild/CMake/External_png.cmake
+++ b/SuperBuild/CMake/External_png.cmake
@@ -30,7 +30,7 @@ ADD_SUPERBUILD_CMAKE_VAR(PNG ZLIB_LIBRARY)
 
 ExternalProject_Add(PNG
   PREFIX PNG
-  URL "http://sourceforge.net/projects/libpng/files/libpng16/older-releases/1.6.16/lpng1616.zip/download"
+  URL "http://downloads.sourceforge.net/project/libpng/libpng16/older-releases/1.6.16/lpng1616.zip"
   URL_MD5 c90c9587c9a5c735327fb3f6900f6b03
   BINARY_DIR ${PNG_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -48,6 +48,10 @@ ExternalProject_Add(PNG
   -DSKIP_INSTALL_EXECUTABLES:BOOL=OFF
   ${PNG_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 set(_SB_PNG_PNG_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 
diff --git a/SuperBuild/CMake/External_proj.cmake b/SuperBuild/CMake/External_proj.cmake
index 2949915c9fc42904d863752944473f78c3393494..a4fc838c7e44757776948edbda6dbeb2358fe40a 100644
--- a/SuperBuild/CMake/External_proj.cmake
+++ b/SuperBuild/CMake/External_proj.cmake
@@ -22,51 +22,32 @@ INCLUDE_ONCE_MACRO(PROJ)
 
 SETUP_SUPERBUILD(PROJ)
 
-if(MSVC)
-  ExternalProject_Add(PROJ
-    PREFIX PROJ
-    URL "http://download.osgeo.org/proj/proj-4.8.0.tar.gz"
-    URL_MD5 d815838c92a29179298c126effbb1537
-    SOURCE_DIR ${PROJ_SB_SRC}
-    BINARY_DIR ${PROJ_SB_SRC}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    CONFIGURE_COMMAND ""
-    BUILD_COMMAND nmake /f ${PROJ_SB_SRC}/makefile.vc
-    INSTALL_COMMAND nmake /f ${PROJ_SB_SRC}/makefile.vc install-all INSTDIR=${SB_INSTALL_PREFIX_NATIVE}
-    )
-
-else()
-
-  if(APPLE)
-    set(PROJ_SB_ENV_CONFIGURE_CMD ${SB_ENV_CONFIGURE_CMD} LDFLAGS=-headerpad_max_install_names)
-  else()
-    set(PROJ_SB_ENV_CONFIGURE_CMD ${SB_ENV_CONFIGURE_CMD})
-  endif()
-
-  ExternalProject_Add(PROJ
-    PREFIX PROJ
-    URL "http://download.osgeo.org/proj/proj-4.8.0.tar.gz"
-    URL_MD5 d815838c92a29179298c126effbb1537
-    BINARY_DIR ${PROJ_SB_SRC}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    CONFIGURE_COMMAND
-    ${SB_ENV_CONFIGURE_CMD}
-    ${PROJ_SB_SRC}/configure
-    --prefix=${SB_INSTALL_PREFIX}
-    --enable-static=no
-    BUILD_COMMAND $(MAKE)
-    INSTALL_COMMAND $(MAKE) install
-    )
-
-endif()
+ExternalProject_Add(PROJ
+  PREFIX PROJ
+  URL "http://download.osgeo.org/proj/proj-4.9.3.tar.gz"
+  URL_MD5 d598336ca834742735137c5674b214a1
+  BINARY_DIR ${PROJ_SB_SRC}
+  INSTALL_DIR ${SB_INSTALL_PREFIX}
+  DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
+  CMAKE_CACHE_ARGS
+  ${SB_CMAKE_CACHE_ARGS}
+  -DBUILD_LIBPROJ_SHARED:BOOL=TRUE
+  -DVERSIONED_OUTPUT:BOOL=FALSE
+  -DBUILD_FRAMEWORKS_AND_BUNDLE:BOOL=FALSE
+  -DPROJ_LIB_SUBDIR:STRING=lib
+  -DPROJ_INCLUDE_SUBDIR:STRING=include
+  CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
+  )
 
 SUPERBUILD_PATCH_SOURCE(PROJ)
 
 set(_SB_PROJ_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 if(WIN32)
-  set(_SB_PROJ_LIBRARY ${SB_INSTALL_PREFIX}/lib/proj_i.lib)
+  set(_SB_PROJ_LIBRARY ${SB_INSTALL_PREFIX}/lib/proj.lib)
 elseif(UNIX)
   set(_SB_PROJ_LIBRARY ${SB_INSTALL_PREFIX}/lib/libproj${CMAKE_SHARED_LIBRARY_SUFFIX})
 endif()
diff --git a/SuperBuild/CMake/External_qt4.cmake b/SuperBuild/CMake/External_qt4.cmake
index 8866464eba0bcdb6de152c762c2ae2a327cd247e..c460c649d5442b758ea2c211d52c2711cca0977b 100644
--- a/SuperBuild/CMake/External_qt4.cmake
+++ b/SuperBuild/CMake/External_qt4.cmake
@@ -33,14 +33,10 @@ SETUP_SUPERBUILD(QT4)
 
 set(QT4_SB_ENABLE_GTK OFF CACHE INTERNAL "Enable GTK+ style with qt using -gtkstlye. Default is OFF")
 
-if(NOT DEFINED git_protocol)
-  set(git_protocol "git")
-endif()
-
 #NOTE: make sure your superbuild install directory does not contain any
 #Qt files from previous install of superbuild QT.
 # declare dependencies
-ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(QT4 ZLIB PNG JPEG SQLITE FREETYPE)
+ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(QT4 ZLIB PNG JPEG FREETYPE)
 
 #use system libs always for Qt4 as we build them from source or have already in system
 set(QT4_SB_CONFIG)
@@ -55,10 +51,9 @@ if(UNIX)
   else() #Linux
     if(QT4_SB_ENABLE_GTK)
       message(WARNING "QT4_SB_ENABLE_GTK support is experimental")
-
       set(QT4_SB_CONFIG "${QT4_SB_CONFIG} -sm -xrender -xrandr -gtkstyle")
     else()
-      set(QT4_SB_CONFIG "${QT4_SB_CONFIG} -no-gtkstyle")
+      set(QT4_SB_CONFIG "${QT4_SB_CONFIG} -no-gtkstyle -no-glib -no-fontconfig")
     endif()
   endif()
   #common for all unix
@@ -105,10 +100,12 @@ add_custom_target(QT4-uninstall
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/include/QtSvg"
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/include/QtTest"
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/include/QtXml"
+  COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/include/Qt"
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/mkspecs"
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/plugins"
   COMMAND ${CMAKE_COMMAND} -E remove_directory "${SB_INSTALL_PREFIX}/translations"
   COMMAND ${CMAKE_COMMAND} -E remove -f "${SB_INSTALL_PREFIX}/lib/libQt*"
+  COMMAND ${CMAKE_COMMAND} -E remove -f "${SB_INSTALL_PREFIX}/lib/pkgconfig/Qt*"
   COMMAND ${CMAKE_COMMAND} -E remove -f "${SB_INSTALL_PREFIX}/bin/qmake${QT4_BIN_EXT}"
   COMMAND ${CMAKE_COMMAND} -E remove -f "${SB_INSTALL_PREFIX}/bin/lrelease${QT4_BIN_EXT}"
   COMMAND ${CMAKE_COMMAND} -E remove -f "${SB_INSTALL_PREFIX}/bin/moc${QT4_BIN_EXT}"
@@ -130,25 +127,12 @@ add_custom_target(QT4-uninstall
     DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
     CONFIGURE_COMMAND ${QT4_CONFIGURE_COMMAND}
     DEPENDS ${QT4_DEPENDENCIES}
+    LOG_DOWNLOAD 1
     LOG_CONFIGURE 1    
     LOG_BUILD 1
     LOG_INSTALL 1    
     )
 
-
- if(MSVC)
-   #Q: why this copy here?.
-   #RK: Because QT4 sucks with qmake -query.
-   ExternalProject_Add_Step(QT4 patches
-     COMMAND ${CMAKE_COMMAND} -E copy_directory
-     ${QT4_SB_SRC}/mkspecs ${SB_INSTALL_PREFIX}/mkspecs
-     COMMAND ${CMAKE_COMMAND} -E copy
-     ${CMAKE_SOURCE_DIR}/patches/QT4/qjpeghandler.pri
-     ${QT4_SB_SRC}/src/gui/image/
-     DEPENDEES patch update
-     DEPENDERS configure )
-endif()
-
 SUPERBUILD_PATCH_SOURCE(QT4)
 
 set(_SB_QT_QMAKE_EXECUTABLE ${SB_INSTALL_PREFIX}/bin/qmake)
diff --git a/SuperBuild/CMake/External_shark.cmake b/SuperBuild/CMake/External_shark.cmake
index f6a41acb569536fff64b9a3cedd68b18e37979dc..ce8486db084935352b4266fc384f40be3604a29c 100644
--- a/SuperBuild/CMake/External_shark.cmake
+++ b/SuperBuild/CMake/External_shark.cmake
@@ -44,8 +44,15 @@ ExternalProject_Add(SHARK
   -DBUILD_TESTING:BOOL=OFF
   -DENABLE_HDF5:BOOL=OFF
   -DENABLE_CBLAS:BOOL=OFF
+  -DENABLE_OPENMP:BOOL=${OTB_USE_OPENMP}
   ${SHARK_SB_CONFIG}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
+SUPERBUILD_PATCH_SOURCE(SHARK)
+
 set(_SB_Shark_DIR ${SB_INSTALL_PREFIX}/lib/cmake/Shark)
diff --git a/SuperBuild/CMake/External_sqlite.cmake b/SuperBuild/CMake/External_sqlite.cmake
index 8a87e03d0e28bc4e89af98a3d21d9a50ce7bb80b..32d845fc3d434ae9b90b459500e55d854333a1d3 100644
--- a/SuperBuild/CMake/External_sqlite.cmake
+++ b/SuperBuild/CMake/External_sqlite.cmake
@@ -33,6 +33,10 @@ ExternalProject_Add(SQLITE
   PATCH_COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/patches/SQLITE ${SQLITE_SB_SRC}
   CMAKE_CACHE_ARGS ${SB_CMAKE_CACHE_ARGS}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 set(_SB_SQLITE_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
diff --git a/SuperBuild/CMake/External_swig.cmake b/SuperBuild/CMake/External_swig.cmake
index 84c28823c7a64cc2ef82d2618ddfc5a153fe76d4..a21bac8410d123d711560da0ebffc5f0f50a58f8 100644
--- a/SuperBuild/CMake/External_swig.cmake
+++ b/SuperBuild/CMake/External_swig.cmake
@@ -43,7 +43,7 @@ if(MSVC)
   # Use pre-built swig executable (no linking is required, no install done)
   ExternalProject_Add(SWIG
     PREFIX SWIG
-    URL "http://sourceforge.net/projects/swig/files/swigwin/swigwin-3.0.7/swigwin-3.0.7.zip/download"
+    URL "http://downloads.sourceforge.net/project/swig/swigwin/swigwin-3.0.7/swigwin-3.0.7.zip"
     URL_MD5 d8b5a9ce49c819cc1bfc1e797b85ba7a
     INSTALL_DIR ${SB_INSTALL_PREFIX}
     DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
@@ -62,7 +62,7 @@ else()
 
   ExternalProject_Add(SWIG
     PREFIX SWIG
-    URL "http://sourceforge.net/projects/swig/files/swig/swig-3.0.7/swig-3.0.7.tar.gz/download"
+    URL "http://downloads.sourceforge.net/project/swig/swig/swig-3.0.7/swig-3.0.7.tar.gz"
     URL_MD5 7fff46c84b8c630ede5b0f0827e3d90a
     BINARY_DIR ${SWIG_SB_BUILD_DIR}
     INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -76,6 +76,10 @@ else()
     BUILD_COMMAND $(MAKE)
     INSTALL_COMMAND $(MAKE) install
     DEPENDS ${SWIG_DEPENDENCIES}
+    LOG_DOWNLOAD 1
+    LOG_CONFIGURE 1
+    LOG_BUILD 1
+    LOG_INSTALL 1
     )
 
   ExternalProject_Add_Step(SWIG copy_source
diff --git a/SuperBuild/CMake/External_tiff.cmake b/SuperBuild/CMake/External_tiff.cmake
index 296312b853baa1f2c8b98abff11e4a6e3c940d7f..d1d48880f29a7333d72e993f9abadf2c1e00d51c 100644
--- a/SuperBuild/CMake/External_tiff.cmake
+++ b/SuperBuild/CMake/External_tiff.cmake
@@ -25,77 +25,52 @@ SETUP_SUPERBUILD(TIFF)
 # declare dependencies
 ADDTO_DEPENDENCIES_IF_NOT_SYSTEM(TIFF ZLIB JPEG)
 
-ADD_SUPERBUILD_CMAKE_VAR(TIFF ZLIB_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(TIFF ZLIB_LIBRARY)
-ADD_SUPERBUILD_CMAKE_VAR(TIFF JPEG_INCLUDE_DIR)
-ADD_SUPERBUILD_CMAKE_VAR(TIFF JPEG_LIBRARY)
-
 if(MSVC)
-  STRING(REGEX REPLACE "/$" "" CMAKE_WIN_INSTALL_PREFIX ${SB_INSTALL_PREFIX})
-  STRING(REGEX REPLACE "/" "\\\\" CMAKE_WIN_INSTALL_PREFIX ${CMAKE_WIN_INSTALL_PREFIX})
-  configure_file(${CMAKE_SOURCE_DIR}/patches/TIFF/nmake.opt ${CMAKE_BINARY_DIR}/nmake_libtiff_extra.opt)
-  ExternalProject_Add(TIFF_build
-    PREFIX TIFF
-    URL "http://download.osgeo.org/libtiff/tiff-4.0.6.tar.gz"
-    URL_MD5 d1d2e940dea0b5ad435f21f03d96dd72
-    SOURCE_DIR ${TIFF_SB_SRC}
-    BINARY_DIR ${TIFF_SB_SRC}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    DEPENDS ${TIFF_DEPENDENCIES}
-    PATCH_COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/nmake_libtiff_extra.opt ${TIFF_SB_SRC}/nmake.opt
-    CONFIGURE_COMMAND ""
-    BUILD_COMMAND nmake /f ${TIFF_SB_SRC}/Makefile.vc
-    INSTALL_COMMAND ${CMAKE_COMMAND} -E copy  ${CMAKE_SOURCE_DIR}/patches/TIFF/CMakeLists.txt
-    ${CMAKE_BINARY_DIR}/TIFF/_install
-    )
-
-  ExternalProject_Add(TIFF
-    PREFIX TIFF/_install
-    DOWNLOAD_COMMAND ""
-    SOURCE_DIR TIFF/_install
-    BINARY_DIR ${TIFF_SB_BUILD_DIR}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    CMAKE_CACHE_ARGS
-    -DCMAKE_INSTALL_PREFIX:STRING=${SB_INSTALL_PREFIX}
-    -DCMAKE_BUILD_TYPE:STRING=Release
-    -DTIFF_BUILD_DIR:STRING=${TIFF_SB_SRC}/libtiff
-    DEPENDS TIFF_build
-    CMAKE_COMMAND
-    )
-
-else()
-  ExternalProject_Add(TIFF
-    PREFIX TIFF
-    URL "http://download.osgeo.org/libtiff/tiff-4.0.6.tar.gz"
-    URL_MD5 d1d2e940dea0b5ad435f21f03d96dd72
-    SOURCE_DIR ${TIFF_SB_SRC}
-    BINARY_DIR ${TIFF_SB_BUILD_DIR}
-    INSTALL_DIR ${SB_INSTALL_PREFIX}
-    DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
-    DEPENDS ${TIFF_DEPENDENCIES}
-    CMAKE_CACHE_ARGS
-    ${SB_CMAKE_CACHE_ARGS}
-    -DCMAKE_INSTALL_LIBDIR:PATH=lib
-    -DCMAKE_INSTALL_BINDIR:PATH=bin
-    -DBUILD_TESTING:BOOL=OFF
-    -Djpeg:BOOL=TRUE
-    -Dlzma:BOOL=FALSE
-    -Djbig:BOOL=FALSE
-    -Dzlib:BOOL=TRUE
-    -DWITH_OPENGL:BOOL=FALSE
-    -Dpixarlog:BOOL=TRUE
-    ${TIFF_SB_CONFIG}
-    CMAKE_COMMAND ${SB_CMAKE_COMMAND}
-    )
+  set(TIFF_C_FLAGS "/D_CRT_SECURE_NO_WARNINGS /DWIN32")
 endif()
 
+ExternalProject_Add(TIFF
+  PREFIX TIFF
+  URL "http://download.osgeo.org/libtiff/tiff-4.0.8.tar.gz"
+  URL_MD5 2a7d1c1318416ddf36d5f6fa4600069b
+  SOURCE_DIR ${TIFF_SB_SRC}
+  BINARY_DIR ${TIFF_SB_BUILD_DIR}
+  INSTALL_DIR ${SB_INSTALL_PREFIX}
+  DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
+  DEPENDS ${TIFF_DEPENDENCIES}
+  CMAKE_CACHE_ARGS
+  ${SB_CMAKE_CACHE_ARGS}
+  -DCMAKE_C_FLAGS:STRING=${TIFF_C_FLAGS}
+  -DCMAKE_INSTALL_LIBDIR:PATH=lib
+  -DCMAKE_INSTALL_BINDIR:PATH=bin
+  -DCMAKE_WINDOWS_EXPORT_ALL_SYMBOLS:BOOL=TRUE
+  -DBUILD_TESTING:BOOL=FALSE
+  -Djpeg:BOOL=TRUE
+  -Dlzma:BOOL=FALSE
+  -Djbig:BOOL=FALSE
+  -Dzlib:BOOL=TRUE
+  -DWITH_OPENGL:BOOL=FALSE
+  -Dpixarlog:BOOL=TRUE
+  -Dcxx:BOOL=FALSE
+  -Dwith_opengl:BOOL=FALSE
+  -Dwith_tools:BOOL=FALSE
+  -Dwith_test:BOOL=FALSE
+  -Dwith_contrib:BOOL=FALSE
+  -Dwith_docs:BOOL=FALSE
+  ${TIFF_SB_CONFIG}
+  CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
+  )
+    
 SUPERBUILD_PATCH_SOURCE(TIFF)
 
+#do we really need these variables? 
 set(_SB_TIFF_INCLUDE_DIR ${SB_INSTALL_PREFIX}/include)
 if(WIN32)
-  set(_SB_TIFF_LIBRARY ${SB_INSTALL_PREFIX}/lib/libtiff_i.lib)
+  set(_SB_TIFF_LIBRARY ${SB_INSTALL_PREFIX}/lib/tiff.lib)
 elseif(UNIX)
   set(_SB_TIFF_LIBRARY ${SB_INSTALL_PREFIX}/lib/libtiff${CMAKE_SHARED_LIBRARY_SUFFIX})
 endif()
diff --git a/SuperBuild/CMake/External_tinyxml.cmake b/SuperBuild/CMake/External_tinyxml.cmake
index d79b14ea6646d7c178dbcb20bf21c34e22a79f96..8952e1ea83147829c4cd3a1a491111ff9ccb0941 100644
--- a/SuperBuild/CMake/External_tinyxml.cmake
+++ b/SuperBuild/CMake/External_tinyxml.cmake
@@ -24,7 +24,7 @@ SETUP_SUPERBUILD(TINYXML)
 
 ExternalProject_Add(TINYXML
   PREFIX TINYXML
-  URL "http://sourceforge.net/projects/tinyxml/files/tinyxml/2.6.2/tinyxml_2_6_2.tar.gz/download"
+  URL "http://downloads.sourceforge.net/project/tinyxml/tinyxml/2.6.2/tinyxml_2_6_2.tar.gz"
   URL_MD5 c1b864c96804a10526540c664ade67f0
   BINARY_DIR ${TINYXML_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
@@ -35,6 +35,10 @@ ExternalProject_Add(TINYXML
   ${TINYXML_SB_SRC}
   CMAKE_CACHE_ARGS ${SB_CMAKE_CACHE_ARGS}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
 SUPERBUILD_UPDATE_CMAKE_VARIABLES(TINYXML FALSE)
diff --git a/SuperBuild/CMake/External_zlib.cmake b/SuperBuild/CMake/External_zlib.cmake
index d19fe414172a5d15b5c9dcdacf12c7cfe708092c..6948e1f54244176e582864c1f958a139ea559402 100644
--- a/SuperBuild/CMake/External_zlib.cmake
+++ b/SuperBuild/CMake/External_zlib.cmake
@@ -26,21 +26,27 @@ SETUP_SUPERBUILD(ZLIB)
 # Try official release 1.2.8
 ExternalProject_Add(ZLIB
   PREFIX ZLIB
-  URL "http://sourceforge.net/projects/libpng/files/zlib/1.2.8/zlib-1.2.8.tar.gz/download"
+  URL "http://downloads.sourceforge.net/project/libpng/zlib/1.2.8/zlib-1.2.8.tar.gz"
   URL_MD5 44d667c142d7cda120332623eab69f40
   BINARY_DIR ${ZLIB_SB_BUILD_DIR}
   INSTALL_DIR ${SB_INSTALL_PREFIX}
   DOWNLOAD_DIR ${DOWNLOAD_LOCATION}
   CMAKE_CACHE_ARGS ${SB_CMAKE_CACHE_ARGS}
   CMAKE_COMMAND ${SB_CMAKE_COMMAND}
+  LOG_DOWNLOAD 1
+  LOG_CONFIGURE 1
+  LOG_BUILD 1
+  LOG_INSTALL 1
   )
 
+#patch zlib cmake to disable static build on request
 if(UNIX)
   ExternalProject_Add_Step(ZLIB remove_static
     COMMAND ${CMAKE_COMMAND} -E remove ${SB_INSTALL_PREFIX}/lib/libz.a
     DEPENDEES install)
 endif()
 
+#check who uses zdll.lib and remove this hack
 if(MSVC)
   ExternalProject_Add_Step(ZLIB msvc_copy_hell
     COMMAND ${CMAKE_COMMAND} -E copy ${ZLIB_SB_BUILD_DIR}/zlib.lib ${SB_INSTALL_PREFIX}/lib/zdll.lib
diff --git a/SuperBuild/CMake/SuperBuild_Macro.cmake b/SuperBuild/CMake/SuperBuild_Macro.cmake
index 85cc6e2a3be6dab17601bb20360aeaf3bffc294a..4e572e4dbd11096d62b959d205fca6faec710af7 100644
--- a/SuperBuild/CMake/SuperBuild_Macro.cmake
+++ b/SuperBuild/CMake/SuperBuild_Macro.cmake
@@ -151,7 +151,7 @@ macro(SUPERBUILD_PATCH_SOURCE project)
   endif()
 
   if(DOT_DIFF_FILES)
-    message(STATUS "  Custom patches required for ${project}")
+    message(STATUS "Custom patches required for ${project}")
     ExternalProject_Add_Step(${project} ${project}_custom_patch
       COMMAND
       ${CMAKE_COMMAND}
diff --git a/SuperBuild/CMake/patch.cmake b/SuperBuild/CMake/patch.cmake
index 651aec69583dd741b3130e5cfcae04df6bd5c1b4..db91ef224f2324afcde0c8f070644ae34ccd18f6 100644
--- a/SuperBuild/CMake/patch.cmake
+++ b/SuperBuild/CMake/patch.cmake
@@ -54,7 +54,8 @@ foreach(dot_diff_file ${DOT_DIFF_FILES})
   endif()
 
   if(PATCHING_FAILED)
-    message(FATAL_ERROR "${PATCH_PROGRAM} returned non-zero exit status \n ${patch_ov} \n")
+    message(FATAL_ERROR
+      "${PATCH_PROGRAM} ${PATCH_ARGS} -p1 -i ${dot_diff_file} failed\n error: ${patch_ov} \n")
   else()
     message("${patch_ov}")
   endif()
diff --git a/SuperBuild/CMakeLists.txt b/SuperBuild/CMakeLists.txt
index b9d6d22904a83e70402c2b03bec8da053158ca7d..ee0ee6ac9c29a0d3f5a45dc22571ae3799a4154f 100644
--- a/SuperBuild/CMakeLists.txt
+++ b/SuperBuild/CMakeLists.txt
@@ -18,7 +18,7 @@
 # limitations under the License.
 #
 
-cmake_minimum_required(VERSION 3.1.0)
+cmake_minimum_required(VERSION 3.3.0)
 
 project(OTB-SuperBuild)
 
@@ -41,8 +41,15 @@ include(ExternalProject)
 
 include(OTBCheckTargetSystemArch)
 
-option(BUILD_SHARED_LIBS "Build OTB with shared libraries." ON)
+set(LINUX FALSE)
+if( "${CMAKE_SYSTEM_NAME}"  MATCHES "Linux")
+  set(LINUX TRUE)
+endif()
 
+option(BUILD_SHARED_LIBS "Build OTB with shared libraries." ON)
+option(BUILD_STATIC_LIBS "Build with static libraries." OFF)
+option(WITH_REMOTE_MODULES "Build with specific list of remote modules." OFF)
+option(OTB_USE_OPENMP "use openmp" OFF)
 set(OTB_ADDITIONAL_CACHE "" CACHE STRING "Additional cmake option for OTB -DVAR:TYPE=VALUE ...")
 
 if(APPLE)
@@ -73,11 +80,11 @@ option(BUILD_TESTING "Build the testing tree." OFF)
 include(CTest)
 include(SuperBuild_Macro)
 
-# Setup location where source tar-balls are downloaded
-#set (install_location "${CMAKE_CURRENT_BINARY_DIR}/install")
-set (DOWNLOAD_LOCATION "${CMAKE_CURRENT_BINARY_DIR}/Downloads"
-     CACHE PATH "Location where source tar-balls are (to be) downloaded.")
-mark_as_advanced(DOWNLOAD_LOCATION)
+# Configure location where source tar-balls are downloaded
+find_path(DOWNLOAD_LOCATION
+  NAMES OTBSuperBuild.readme
+  HINTS $ENV{DOWNLOAD_LOCATION} "${CMAKE_CURRENT_BINARY_DIR}/Downloads"
+  )
 
 # General options
 option(OTB_DATA_USE_LARGEINPUT "Use Large inputs images test." OFF)
@@ -90,7 +97,6 @@ if(OTB_DATA_USE_LARGEINPUT)
   mark_as_advanced(OTB_DATA_LARGEINPUT_ROOT)
 endif()
 
-
 option(BUILD_EXAMPLES " Build the OTB Examples directory" OFF)
 
 option(USE_DEFAULT_INSTALL_PREFIX "Install superbuild to default prefix /usr/local for unix" OFF)
@@ -146,16 +152,7 @@ if(NOT CMAKE_BUILD_TYPE)
 endif()
 
 if(MSVC)
-  set(BUILD_SHARED_LIBS OFF)
-  if(CMAKE_MAJOR_VERSION GREATER 2 AND CMAKE_MINOR_VERSION GREATER 2)
-    set(BUILD_SHARED_LIBS ON)
-  else()
-    message(WARNING "BUILD_SHARED_LIBS is set to OFF with CMake < 3.3")
-  endif()
-endif()
-
-if(MSVC)
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /Ox /FC /D_CRT_SECURE_NO_DEPRECATE /D_CRT_NONSTDC_NO_DEPRECATE")
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /D_CRT_SECURE_NO_DEPRECATE /D_CRT_NONSTDC_NO_DEPRECATE")
   if(MSVC_VERSION GREATER 1310)
     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
   endif()
@@ -186,6 +183,24 @@ if(UNIX)
   list(APPEND SB_CMAKE_CACHE_ARGS "-DCMAKE_INSTALL_RPATH:PATH=${CMAKE_INSTALL_RPATH}")
 endif()
 
+foreach(cmake_var
+    CMAKE_C_FLAGS
+    CMAKE_CXX_FLAGS
+    CMAKE_EXE_LINKER_FLAGS
+    CMAKE_SHARED_LINKER_FLAGS
+    CMAKE_MODULE_LINKER_FLAGS
+    CMAKE_STATIC_LINKER_FLAGS
+    )
+  if(${cmake_var})
+    list(APPEND SB_CMAKE_CACHE_ARGS "-D${cmake_var}:STRING=${${cmake_var}}")
+    list(APPEND SB_CMAKE_CACHE_ARGS "-D${cmake_var}:STRING=${${cmake_var}}")
+  endif()
+endforeach()
+
+if(CMAKE_VERBOSE_MAKEFILE)
+  list(APPEND SB_CMAKE_CACHE_ARGS "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON")
+endif()
+
 set(SB_CMAKE_ARGS "-G${CMAKE_GENERATOR}")
 
 set(SB_CONFIGURE_ARGS)
@@ -224,6 +239,25 @@ else()
   #windows
   set(SB_CMAKE_COMMAND ${CMAKE_COMMAND} ${SB_CMAKE_ARGS})
 endif()
+
+if(CMAKE_C_FLAGS)
+  list(APPEND SB_ENV_CONFIGURE_CMD "CFLAGS=${CMAKE_C_FLAGS}")
+endif()
+if(CMAKE_CXX_FLAGS)
+  list(APPEND SB_ENV_CONFIGURE_CMD "CXXFLAGS=${CMAKE_CXX_FLAGS}")
+endif()
+if(CMAKE_EXE_LINKER_FLAGS)
+  list(APPEND SB_ENV_CONFIGURE_CMD "LDFLAGS=${CMAKE_EXE_LINKER_FLAGS}")
+endif()
+if(CMAKE_SHARED_LINKER_FLAGS)
+  list(APPEND SB_ENV_CONFIGURE_CMD "LDFLAGS=${CMAKE_SHARED_LINKER_FLAGS}")
+endif()
+if(CMAKE_MODULE_LINKER_FLAGS)
+  list(APPEND SB_ENV_CONFIGURE_CMD "LDFLAGS=${CMAKE_MODULE_LINKER_FLAGS}")
+endif()
+
+list(REMOVE_DUPLICATES SB_ENV_CONFIGURE_CMD)
+
 message(STATUS "Environment setup for CMake (SB_CMAKE_COMMAND) : ${SB_CMAKE_COMMAND}")
 
 set(FROM_SYSTEM_LIST)
@@ -249,6 +283,7 @@ option(USE_SYSTEM_GDAL "Use a system build of GDAL" OFF)
 option(USE_SYSTEM_FFTW "Use a system build of FFTW" OFF)
 option(USE_SYSTEM_ITK "Use a system build of ITK" OFF)
 option(USE_SYSTEM_OPENTHREADS  "Use a system build of OpenThreads" OFF)
+option(USE_SYSTEM_OSSIM  "Use a system build of OSSIM" OFF)
 option(USE_SYSTEM_MUPARSER  "Use a system build of muParser" OFF)
 option(USE_SYSTEM_MUPARSERX "Use a system build of  muParserX" OFF)
 option(USE_SYSTEM_TINYXML  "Use a system build of TinyXML" OFF)
@@ -281,30 +316,33 @@ option(OTB_USE_MUPARSERX "Enable module muparserX in OTB" ON)
 option(OTB_USE_OPENCV "Enable module OpenCV in OTB" ON)
 option(OTB_USE_QT4 "Enable module QT4 in OTB" ON)
 option(OTB_USE_SIFTFAST "Enable module Siftfast in OTB" ON)
-option(OTB_USE_OPENGL "Enable module OpenGL in OTB" OFF)
-option(OTB_USE_GLEW "Enable module GLEW in OTB" OFF)
-option(OTB_USE_GLFW "Enable module GLFW in OTB" OFF)
-option(OTB_USE_GLUT "Enable module GLUT in OTB" OFF)
-option(OTB_USE_SHARK "Enable module Shark in OTB" OFF)
-option(OTB_USE_QWT "Enable module QWT in OTB" OFF)
+option(OTB_USE_OPENGL "Enable module OpenGL in OTB" ON)
+option(OTB_USE_GLEW "Enable module GLEW in OTB" ON)
 
-#Problem: below cmake setting will fail!
-#-DOTB_USE_OPENGL=ON -DOTB_USE_GLEW=ON -DOTB_USE_QWT=ON
-#This is because ENABLE_MONTEVERDI is OFF by default
-# This brings a lot of twisted logic. so taking out this option
+#Cannot activate GLUT on OSX. See manits issue #1194")
+# do not activate GLFW by default on osx. see failing test 
+# https://dash.orfeo-toolbox.org/testDetails.php?test=59844554&build=287120
+if(APPLE)
+  option(OTB_USE_GLUT "Enable module GLUT in OTB" OFF)
+  option(OTB_USE_GLFW "Enable module GLFW in OTB" OFF)
+else()
+  option(OTB_USE_GLUT "Enable module GLUT in OTB" ON)
+  option(OTB_USE_GLFW "Enable module GLFW in OTB" ON)
+endif()
 
+option(OTB_USE_SHARK "Enable module Shark in OTB" ON)
+option(OTB_USE_QWT "Enable module QWT in OTB" ON)
 
 # set OTB_DATA_ROOT to run test
-find_path(OTB_DATA_ROOT README-OTB-Data PATHS $ENV{OTB_DATA_ROOT} ${OTB-SuperBuild_SOURCE_DIR}/../../OTB-Data)
-
+find_path(OTB_DATA_ROOT README-OTB-Data
+  PATHS
+  $ENV{OTB_DATA_ROOT}
+  ${OTB-SuperBuild_SOURCE_DIR}/../../OTB-Data)
 
 # SWIG Wrapping
-option(OTB_WRAP_PYTHON "Enable python wrappers for OTB applications (requires SWIG)" OFF)
+option(OTB_WRAP_PYTHON "Enable python wrappers for OTB applications (requires SWIG)" ON)
 option(OTB_WRAP_JAVA "Enable java wrappers for OTB applications (requires SWIG)" OFF)
 
-option(GENERATE_PACKAGE "Generate a portable .run package of OTB (only Unix)." OFF)
-option(GENERATE_XDK "Generate an XDK. This files provides all headers and libraries to build and or develop OTB (only Unix)." OFF)
-
 configure_file(${CMAKE_SOURCE_DIR}/CMake/CTestCustom.cmake.in
   ${CMAKE_BINARY_DIR}/CTestCustom.cmake @ONLY)
 
@@ -330,28 +368,25 @@ endforeach()
 
 include(External_otb)
 
-
-if(UNIX OR MSVC)
-  add_subdirectory(Packaging)
-endif()
-
 if(FROM_SYSTEM_LIST)
   list(SORT FROM_SYSTEM_LIST)
   foreach( item ${FROM_SYSTEM_LIST})
-    message(STATUS "  Using system version of ${item}")
+    message(STATUS "Using system version of ${item}")
   endforeach()
 endif()
 
 if(FROM_SUPERBUILD_LIST)
   list(SORT FROM_SUPERBUILD_LIST)
   foreach( item ${FROM_SUPERBUILD_LIST})
-    message(STATUS "  Using SuperBuild version of ${item}")
+    message(STATUS "Using SuperBuild version of ${item}")
   endforeach()
 endif()
 
 message(STATUS "OTB_TARGET_SYSTEM_ARCH=${OTB_TARGET_SYSTEM_ARCH}")
 message(STATUS "OTB_TARGET_SYSTEM_ARCH_IS_X64=${OTB_TARGET_SYSTEM_ARCH_IS_X64}")
+
 if(DOWNLOAD_LOCATION)
+  message(STATUS "DOWNLOAD_LOCATION=${DOWNLOAD_LOCATION}")
   message(STATUS "Source archives for dependencies will be taken from '${DOWNLOAD_LOCATION}'")
 else()
   message(STATUS "DOWNLOAD_LOCATION is not set. We will download all source archives during build!")
diff --git a/SuperBuild/Packaging/CMakeLists.txt b/SuperBuild/Packaging/CMakeLists.txt
deleted file mode 100644
index 9c58a5bbc40ff7fc62b18338d6d197ac5a6fab2e..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/CMakeLists.txt
+++ /dev/null
@@ -1,219 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# cpack has a built-in target called 'package'. In our case we create two standalone installers with
-# and uses a custom target named packages.
-
-# stop generation of msvc packages for windows. 04-apr-2016. point OTB.
-
-##### check if standalone project ######
-set(OUT_OF_SOURCE_BUILD FALSE)
-if(NOT PROJECT_NAME)
-  cmake_minimum_required(VERSION 2.6)
-  include(CMakeParseArguments)
-  project(OTBPackaging)
-
-  option(GENERATE_PACKAGE "Generate OTB package" ON)
-  option(GENERATE_XDK "Generate XDK for OTB development" OFF)
-  
-  set(OUT_OF_SOURCE_BUILD TRUE)
-  
-  if(BUILD_TESTING)
-    include(CTest)
-  endif()
-  
-  if(NOT PACKAGE_OTB_SRC_DIR)
-    get_filename_component(PACKAGE_OTB_SRC_DIR ${OTBPackaging_SOURCE_DIR} PATH)
-    get_filename_component(PACKAGE_OTB_SRC_DIR ${PACKAGE_OTB_SRC_DIR} PATH)
-  endif()
-  
-  option(OTB_WRAP_PYTHON "enable python wrapping" ON)
-  if(OTB_WRAP_PYTHON AND NOT PYTHON_EXECUTABLE)
-    find_package ( PythonInterp REQUIRED )
-    mark_as_advanced(PYTHON_INCLUDE_DIR)
-    mark_as_advanced(PYTHON_LIBRARY)
-  endif()
-
- if(OTB_MINGW)
-    set(OTB_BINARY_DIR "" CACHE PATH "OTB binary directory")
-    set(OTB_INSTALL_DIR "" CACHE PATH "OTB install directory")
-  else()
-    set(SUPERBUILD_BINARY_DIR "" CACHE PATH "path to superbuild binary directory")
-    set(SUPERBUILD_INSTALL_DIR "" CACHE PATH "path to superbuild install directory")
-    set(DOWNLOAD_LOCATION "" CACHE PATH "path to superbuild download archives")
-  endif()
-  
-else() #if(NOT PROJECT_NAME)
-
-  # SUPERBUILD_BINARY_DIR is only set in Packaging/CMakeLists.txt and not available
-  # in the parent scope like others. So we need to set it as CMAKE_BINARY_DIR
-  # if doing packages from source tree.
-  set( SUPERBUILD_BINARY_DIR   ${CMAKE_BINARY_DIR}     )
-  set( SUPERBUILD_INSTALL_DIR  ${SB_INSTALL_PREFIX}    )
-  set( OTB_INSTALL_DIR         ${CMAKE_INSTALL_PREFIX} )
-  
-  if(NOT PACKAGE_OTB_SRC_DIR)
-    get_filename_component(PACKAGE_OTB_SRC_DIR ${OTB-SuperBuild_SOURCE_DIR} PATH)
-  endif()
-  
-endif()
-
-if(NOT GENERATE_PACKAGE AND NOT GENERATE_XDK)
-  #well. we don't have any businees here. Let's move on..
-  return()
-endif()
-
-set(LINUX FALSE)
-set(OTB_MINGW FALSE)
-if(WIN32 AND NOT MSVC)
-  set(OTB_MINGW TRUE)
-else()
-  if( "${CMAKE_SYSTEM_NAME}"  MATCHES "Linux")
-    set(LINUX TRUE)
-  endif()
-endif()
-
-find_program(FILE_COMMAND "file")
-mark_as_advanced(FILE_COMMAND)
-
-set(SUPERBUILD_SOURCE_DIR ${PACKAGE_OTB_SRC_DIR}/SuperBuild)
-
-include(${SUPERBUILD_SOURCE_DIR}/CMake/SuperBuild_Macro.cmake)
-include(${PACKAGE_OTB_SRC_DIR}/CMake/OTBCheckTargetSystemArch.cmake)
-include(${CMAKE_CURRENT_SOURCE_DIR}/CreateCMakeProjects.cmake)
-
-if(WIN32)
-  set(ZIP_EXE_NAMES 7z 7za)
-  find_program(ZIP_EXECUTABLE NAMES ${ZIP_EXE_NAMES})
-  if(NOT ZIP_EXECUTABLE)
-    message(FATAL_ERROR "Cannot find 7z executable. searched names ${ZIP_EXE_NAMES}. Please add it to your path")
-  endif()
-endif()
-
-if(OTB_MINGW)
-  set(required_vars
-  OTB_BINARY_DIR
-  OTB_INSTALL_DIR
-  MXE_TARGET_DIR
-  )
-else()
-    set(required_vars
-  SUPERBUILD_BINARY_DIR
-  SUPERBUILD_INSTALL_DIR
-  SUPERBUILD_SOURCE_DIR
-  )
-endif()
-
-foreach(req
-  ${required_vars}
-  PACKAGE_OTB_SRC_DIR
-  OTB_TARGET_SYSTEM_ARCH
-  OTB_TARGET_SYSTEM_ARCH_IS_X64
- )
-  if(NOT DEFINED ${req} OR "${${req}}" STREQUAL "")
-    message(FATAL_ERROR "you must set ${req}")
-  endif()
-  set(vars "${vars}  ${req}=[${${req}}]\n")
-endforeach(req)
-
-message("\n${vars}\n")
-
-set(PKG_DEBUG OFF)
-
-set(EXTRA_CACHE_CONFIG)
-
-set(CMAKE_INSTALL_PREFIX "${SUPERBUILD_INSTALL_DIR}")
-
-set(PACKAGE_LONG_NAME OrfeoToolBox)
-
-# Make up part of output package file
-set(NAME_SUFFIX "" CACHE STRING "extra suffix for package name")
-
-set(PACKAGE_NAME OTB)
-
-if(NAME_SUFFIX)
-  set(PACKAGE_NAME OTB${NAME_SUFFIX})
-endif()
-
-if(APPLE)
-  set(PACKAGE_PLATFORM_NAME "Darwin")
-elseif(WIN32)
-  set(PACKAGE_PLATFORM_NAME "win")
-elseif(LINUX)
-  set(PACKAGE_PLATFORM_NAME "Linux")
-endif()
-
-set(PACKAGE_ARCH "32")
-if(OTB_TARGET_SYSTEM_ARCH_IS_X64)
-set(PACKAGE_ARCH "64")
-endif()
-
-if(OTB_MINGW)
-  get_filename_component(MXE_MXEROOT ${MXE_TARGET_DIR} PATH)
-  get_filename_component(MXE_MXEROOT ${MXE_MXEROOT} PATH)
-  set(EXTRA_CACHE_CONFIG
-    "set(CMAKE_CROSSCOMPILING TRUE)
-     set(WIN32 TRUE)
-     set(MINGW TRUE)
-     set(MXE_MXEROOT \"${MXE_MXEROOT}\")"
-    )
-  set(CMAKE_INSTALL_PREFIX "${OTB_INSTALL_DIR}")  
-endif()
-
-# get itk version from External_itk.cmake if not on mingw
-# because mxe has different version
-if(NOT OTB_MINGW)
-  get_version(
-    INPUT_FILE   "${SUPERBUILD_SOURCE_DIR}/CMake/External_itk.cmake"
-    MATCH_STRINGS "SB_ITK_VERSION_MAJOR" "SB_ITK_VERSION_MINOR"
-    PREFIX PKG
-    )
-endif()
-
-set(PKG_ITK_SB_VERSION "${PKG_SB_ITK_VERSION_MAJOR}.${PKG_SB_ITK_VERSION_MINOR}")
-
-#get version of OTB from source_dir/CMakeLists.txt
-get_version(
-  INPUT_FILE   "${PACKAGE_OTB_SRC_DIR}/CMakeLists.txt"
-  MATCH_STRINGS "OTB_VERSION_MAJOR" "OTB_VERSION_MINOR" "OTB_VERSION_PATCH"
-  PREFIX PKG
-  )
-
-set(PKG_OTB_VERSION_STRING
-  ${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}.${PKG_OTB_VERSION_PATCH})
-
-if(OTB_MINGW)
-  set(OTB_BINARY_DIR              "${OTB_BINARY_DIR}")
-  set(OTB_INSTALL_DIR             "${OTB_INSTALL_DIR}")
-  set(DEPENDENCIES_INSTALL_DIR    "${MXE_MXEROOT}/usr/${OTB_TARGET_SYSTEM_ARCH}-w64-mingw32.shared")
-  set(QT_PLUGINS_DIR              "${DEPENDENCIES_INSTALL_DIR}/qt/plugins")
-  set(QT_TRANSLATIONS_DIR         "${DEPENDENCIES_INSTALL_DIR}/qt/translations")
-else() #unixes
-  set(OTB_BINARY_DIR            "${SUPERBUILD_BINARY_DIR}/OTB/build")
-  set(OTB_INSTALL_DIR           "${SUPERBUILD_INSTALL_DIR}")
-  set(DEPENDENCIES_INSTALL_DIR  "${SUPERBUILD_INSTALL_DIR}")
-  set(QT_PLUGINS_DIR            "${SUPERBUILD_INSTALL_DIR}/plugins")
-  set(QT_TRANSLATIONS_DIR       "${SUPERBUILD_INSTALL_DIR}/translations")
-endif()
-
-macro_setup_cmake_project(OTB)
-if(GENERATE_XDK)
-  macro_setup_cmake_project(XDK)
-endif()
diff --git a/SuperBuild/Packaging/CreateCMakeProjects.cmake b/SuperBuild/Packaging/CreateCMakeProjects.cmake
deleted file mode 100644
index 6d0cb47f31eefbc1eb07173d188eb65ebc1483d6..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/CreateCMakeProjects.cmake
+++ /dev/null
@@ -1,200 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-macro(macro_setup_cmake_project pkg)
-
-  message( "-- Configuring ${pkg} package")
-
-  set(PATCHELF_PROGRAM)
-  set(MAKESELF_SCRIPT)
-  include(${SUPERBUILD_SOURCE_DIR}/CMake/External_pkgtools.cmake)
-
-  #reset it again in macro(macro_create_targets_for_package pkg)
-  #because that's the cmake macros way.
-  set(PACKAGE_PROJECT_DIR ${CMAKE_BINARY_DIR}/PACKAGE-${pkg})
-  execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory "${PACKAGE_PROJECT_DIR}/build")
-
-   if("${pkg}" STREQUAL "XDK")
-    set(PKG_GENERATE_XDK ON)
-  else()
-    set(PKG_GENERATE_XDK OFF)
-  endif()
- 
-  if(PKG_GENERATE_XDK)
-    set(archive_name ${PACKAGE_NAME}-${PKG_OTB_VERSION_STRING}-xdk-${PACKAGE_PLATFORM_NAME}${PACKAGE_ARCH})
-  else()
-    set(archive_name ${PACKAGE_NAME}-${PKG_OTB_VERSION_STRING}-${PACKAGE_PLATFORM_NAME}${PACKAGE_ARCH})
-  endif()
-    
-  #set archive name inside loop
-  file(WRITE "${PACKAGE_PROJECT_DIR}/src/CMakeLists.txt"
-  "cmake_minimum_required(VERSION 3.2)
-   include(CMakeParseArguments)
-   include(CMakeDetermineSystem)
-   set(CMAKE_BUILD_TYPE              Release)
-   set(PACKAGE_OTB_SRC_DIR           \"${PACKAGE_OTB_SRC_DIR}\")
-   set(SUPERBUILD_BINARY_DIR         \"${SUPERBUILD_BINARY_DIR}\")
-   set(OTB_BINARY_DIR                \"${OTB_BINARY_DIR}\")
-   set(OTB_INSTALL_DIR               \"${OTB_INSTALL_DIR}\")
-   set(QT_PLUGINS_DIR                \"${QT_PLUGINS_DIR}\")
-   set(QT_TRANSLATIONS_DIR           \"${QT_TRANSLATIONS_DIR}\")
-   set(DEPENDENCIES_INSTALL_DIR      \"${DEPENDENCIES_INSTALL_DIR}\")
-   set(PACKAGE_SUPPORT_FILES_DIR     \"${PACKAGE_OTB_SRC_DIR}/SuperBuild/Packaging/Files\")
-   set(CMAKE_INSTALL_PREFIX          \"${CMAKE_INSTALL_PREFIX}\")
-   set(PKG_ITK_SB_VERSION            \"${PKG_ITK_SB_VERSION}\")
-   set(PKG_OTB_VERSION_MAJOR         \"${PKG_OTB_VERSION_MAJOR}\")
-   set(PKG_OTB_VERSION_MINOR         \"${PKG_OTB_VERSION_MINOR}\")
-   set(PKG_OTB_VERSION_PATCH         \"${PKG_OTB_VERSION_PATCH}\")
-   set(PKG_OTB_VERSION_STRING        \"${PKG_OTB_VERSION_STRING}\")
-   set(PYTHON_EXECUTABLE             \"${PYTHON_EXECUTABLE}\")
-   set(PATCHELF_PROGRAM              \"${PATCHELF_PROGRAM}\")
-   set(PKG_GENERATE_XDK              ${PKG_GENERATE_XDK})
-   set(OTB_TARGET_SYSTEM_ARCH        ${OTB_TARGET_SYSTEM_ARCH})
-   set(OTB_TARGET_SYSTEM_ARCH_IS_X64 ${OTB_TARGET_SYSTEM_ARCH_IS_X64})   
-   set(OTB_WRAP_PYTHON               ${OTB_WRAP_PYTHON})
-   set(PKG_DEBUG                     ${PKG_DEBUG})
-   set(FILE_COMMAND                  \"${FILE_COMMAND}\")
-   ${EXTRA_CACHE_CONFIG}
-   include(${SUPERBUILD_SOURCE_DIR}/Packaging/PackageMacros.cmake)
-   include(${SUPERBUILD_SOURCE_DIR}/Packaging/PackageHelper.cmake)
-   include(${SUPERBUILD_SOURCE_DIR}/Packaging/InstallSupportFiles.cmake)
-   include(${SUPERBUILD_SOURCE_DIR}/Packaging/PackageGlobals.cmake)
-   macro_super_package(STAGE_DIR \"${archive_name}\")"
-  )
-
-set(README_FILE_SUFFIX)
-if(PKG_GENERATE_XDK)
-  set(README_FILE_SUFFIX "_xdk")
-endif()
-if(APPLE)
-  set(README_FILE ${PACKAGE_OTB_SRC_DIR}/Documentation/Cookbook/rst/Installation_Macx${README_FILE_SUFFIX}.txt)
-elseif(LINUX) #not osx
-  set(README_FILE ${PACKAGE_OTB_SRC_DIR}/Documentation/Cookbook/rst/Installation_Linux${README_FILE_SUFFIX}.txt)
-elseif(WIN32) #windows
-  set(README_FILE ${PACKAGE_OTB_SRC_DIR}/Documentation/Cookbook/rst/Installation_Windows${README_FILE_SUFFIX}.txt)
-endif()
-
-configure_file(
-  "${README_FILE}"
-  ${PACKAGE_PROJECT_DIR}/src/README
-  )
-
-macro_create_targets_for_package(${pkg})
-
-endmacro()
-
-macro(macro_create_targets_for_package pkg)
-
-  if(WIN32 AND NOT MSVC)
-
-     add_custom_target(PACKAGE-${pkg}-check
-       COMMAND ${CMAKE_COMMAND} --build "." --target install
-       WORKING_DIRECTORY "${OTB_BINARY_DIR}"
-       )
-  else() #Using SuperBuild
-    #For out of source build,
-    #we assume the otb is built correctly with superbuild
-    if(OUT_OF_SOURCE_BUILD)
-      add_custom_target(PACKAGE-${pkg}-check
-        COMMAND ${CMAKE_COMMAND} -E echo "Building PACKAGE-${pkg}-check")
-    else(OUT_OF_SOURCE_BUILD)
-      add_custom_target(PACKAGE-${pkg}-check
-        COMMAND ${CMAKE_COMMAND} -E echo "Building PACKAGE-${pkg}-check"
-	      DEPENDS OTB
-        WORKING_DIRECTORY ${SUPERBUILD_BINARY_DIR}
-        )      
-    endif(OUT_OF_SOURCE_BUILD)
-  endif()
-
-  add_dependencies(PACKAGE-${pkg}-check PACKAGE-TOOLS)
-#  add_dependencies(PACKAGE-${pkg}-check PACKAGE-${pkg}-clean)
-
-
-  if(NOT archive_name)
-    message(FATAL_ERROR "archive_name not set. Cannot continue")
-  endif()
-  
-  set(PACKAGE_PROJECT_DIR ${CMAKE_BINARY_DIR}/PACKAGE-${pkg})
-
-  if(WIN32)
-    set(PACKAGE_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${archive_name}.zip")
-  else()
-    set(PACKAGE_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${archive_name}.run")
-  endif()
-    
-  #configure
-  add_custom_target(PACKAGE-${pkg}-configure
-    COMMAND ${CMAKE_COMMAND} -E remove "${PACKAGE_OUTPUT_FILE}"
-  COMMAND ${CMAKE_COMMAND} -E make_directory  "${PACKAGE_PROJECT_DIR}/build"
-   WORKING_DIRECTORY "${PACKAGE_PROJECT_DIR}"
-    COMMAND ${CMAKE_COMMAND} "-G${CMAKE_GENERATOR}"
-    "${PACKAGE_PROJECT_DIR}/src"
-    WORKING_DIRECTORY "${PACKAGE_PROJECT_DIR}/build"
-    DEPENDS PACKAGE-${pkg}-check
-    )
-#  COMMAND ${CMAKE_COMMAND} -E remove_directory "${PACKAGE_PROJECT_DIR}"
-  #build
-  add_custom_target(PACKAGE-${pkg}-build
-    COMMAND ${CMAKE_COMMAND}
-    "--build" "${PACKAGE_PROJECT_DIR}/build" "--target" "install"
-    WORKING_DIRECTORY "${PACKAGE_PROJECT_DIR}/build"
-    DEPENDS PACKAGE-${pkg}-configure
-    )
-
-  #create package
-  # creation of package is different from windows and unix like
-  # WORKING_DIRECTORY must be CMAKE_INSTALL_PREFIX and not
-  # CMAKE_CURRENT_BINARY_DIR like in unix
-  if(WIN32)
-    add_custom_target(PACKAGE-${pkg}
-      COMMAND ${ZIP_EXECUTABLE} "a" "-r" "-y"
-      "${PACKAGE_OUTPUT_FILE}" "${archive_name}/*"
-      WORKING_DIRECTORY "${CMAKE_INSTALL_PREFIX}"
-      DEPENDS PACKAGE-${pkg}-build
-      COMMENT "Creating ${PACKAGE_OUTPUT_FILE}"
-      )
-  else()
-    add_custom_target(PACKAGE-${pkg}
-      COMMAND ${MAKESELF_SCRIPT}
-      "--quiet"
-      "--target"
-      "${archive_name}"
-      "${CMAKE_INSTALL_PREFIX}/${archive_name}"
-      "${archive_name}.run"
-      "${PACKAGE_LONG_NAME} ${PKG_OTB_VERSION_STRING}"
-      "./pkgsetup"
-      WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
-      DEPENDS PACKAGE-${pkg}-build
-      COMMENT "Creating ${PACKAGE_OUTPUT_FILE}"
-      )
-  endif()
-
-
-
-  #clean
-  add_custom_target(PACKAGE-${pkg}-clean
-    COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_BINARY_DIR}/PACKAGE-${pkg}"
-    COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_BINARY_DIR}/PACKAGE-TOOLS"
-    COMMAND ${CMAKE_COMMAND} -E remove "${PACKAGE_OUTPUT_FILE}"
-    COMMAND ${CMAKE_COMMAND} "${CMAKE_BINARY_DIR}"
-    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
-    )
-
-endmacro(macro_create_targets_for_package)
diff --git a/SuperBuild/Packaging/Files/linux_pkgsetup.in b/SuperBuild/Packaging/Files/linux_pkgsetup.in
deleted file mode 100644
index fcdc13fa0fe83abec1d8c1c4a2ed0dff65fc394c..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/linux_pkgsetup.in
+++ /dev/null
@@ -1,347 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-DIRNAME_0=$(dirname "$0")
-cd  "$DIRNAME_0"
-
-# NOTE: $OUT_DIR is also used in make_sylinks script (see below)
-# Avoid any pre-mature optimization on variable names here.
-
-OUT_DIR=$(pwd)
-
-PATCH_ELF_EXE="$OUT_DIR/patchelf"
-
-# No no interference with LD_LIBRARY_PATH
-LD_LIBRARY_PATH=
-
-echo "Configuring..."
-#see next call below for otb applications
-BINARY_FILES=$(find $OUT_DIR/lib $OUT_DIR/bin -maxdepth 1 -type f -exec file {} \; | grep -i elf|cut -f1 -d':')
-
-# run patchelf
-for bin_file in $BINARY_FILES; do
-    #echo "adding rpath to $bin_file"
-    if [ -f "$bin_file" ]; then
-        "$PATCH_ELF_EXE" "--set-rpath" "$OUT_DIR/lib" "$bin_file"
-    fi
-done
-
-I_AM_XDK=@IS_XDK@
-
-# if [ "$I_AM_XDK" = true ] ; then
-#     sed -i "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/Modules/ITKZLIB.cmake
-#     sed -i "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/ITKConfig.cmake
-#     sed -i "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/ITKTargets-release.cmake
-# else
-
-if [ "$I_AM_XDK" = false ] ; then
-OTB_APP_FILES=$(find $OUT_DIR/lib/otb/applications -maxdepth 1 -type f -exec file {} \; | grep -i elf|cut -f1 -d':')
- # run patchelf
-for app_file in $OTB_APP_FILES; do
-    #echo "adding rpath to $app_file"
-    if [ -f "$app_file" ]; then
-        "$PATCH_ELF_EXE" "--set-rpath" "$OUT_DIR/lib" "$app_file"
-    fi
-done
-
-cat > "$OUT_DIR/monteverdi.sh" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-. $OUT_DIR/otbenv.profile
-
-$OUT_DIR/bin/monteverdi "\$@"
-EOF
-
-chmod +x "$OUT_DIR/monteverdi.sh"
-
-cat > "$OUT_DIR/mapla.sh" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-. $OUT_DIR/otbenv.profile
-
-$OUT_DIR/bin/mapla "\$@"
-EOF
-
-chmod +x "$OUT_DIR/mapla.sh"
-
-cat > "$OUT_DIR/otbenv.profile" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-# The below environment variables only affect current shell
-# So if you run again from a terminal. you need to run the script again
-# see how this is sourced in monteverdi.sh and mapla.sh
-
-# unset any existing LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH
-
-# if OTB_USE_LOCAL_GTK is set to one,
-# we must include <OUT_DIR>/lib/gtk because glib files are
-# installed there. 
-
-# OTB_USE_LOCAL_GTK is not set by default (use GTK system)
-if [ "\$OTB_USE_LOCAL_GTK" = "1" ]; then
-  LD_LIBRARY_PATH=$OUT_DIR/lib/gtk
-  export LD_LIBRARY_PATH
-fi
-
-# check and set OTB_APPLICATION_PATH
-if [ -z "\$OTB_APPLICATION_PATH" ] || [ "\$OTB_APPLICATION_PATH" = "" ]; then
-    OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications
-else
-    OTB_APPLICATION_PATH=\$(readlink -f "\$OTB_APPLICATION_PATH")
-    if ! [ "\$OTB_APPLICATION_PATH" = "$OUT_DIR/lib/otb/applications" ]; then 
-	OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications:\$OTB_APPLICATION_PATH
-    fi
-fi
-
-# Add bin direcotory to system PATH
-PATH=$OUT_DIR/bin:\$PATH
-
-# export PYTHONPATH to import otbApplication.py
-PYTHONPATH=$OUT_DIR/lib/python:\$PYTHONPATH
-
-# set numeric locale to C
-LC_NUMERIC=C
-
-# set GDAL_DATA variable used by otb application
-GDAL_DATA=$OUT_DIR/share/gdal
-
-# set GEOTIFF_CSV variable used by otb application
-GEOTIFF_CSV=$OUT_DIR/share/epsg_csv
-
-# export variables
-export LC_NUMERIC
-export GDAL_DATA
-export GEOTIFF_CSV
-export OTB_APPLICATION_PATH
-export PATH
-export PYTHONPATH
-
-EOF
-
-
-chmod +x "$OUT_DIR/otbenv.profile"
-
-else
-
-cat > "$OUT_DIR/xdkenv.profile" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-# The below environment variables only affect current shell
-# So if you run again from a terminal. you need to run the script again
-
-# unset any existing LD_LIBRARY_PATH
-unset LD_LIBRARY_PATH
-
-# Add bin direcotory to system PATH
-PATH=$OUT_DIR/bin:\$PATH
-
-# set numeric locale to C
-LC_NUMERIC=C
-
-# set GDAL_DATA variable used by otb application
-GDAL_DATA=$OUT_DIR/share/gdal
-
-# set GEOTIFF_CSV variable used by otb application
-GEOTIFF_CSV=$OUT_DIR/share/epsg_csv
-
-CMAKE_PREFIX_PATH=$OUT_DIR
-
-# export variables
-export LC_NUMERIC
-export GDAL_DATA
-export GEOTIFF_CSV
-export CMAKE_PREFIX_PATH
-export PATH
-
-EOF
-
-
-chmod +x "$OUT_DIR/xdkenv.profile"
-
-fi
-
-#echo "Creating symbolic links..."
-. ./make_symlinks
-
-
-cat > "$OUT_DIR/bin/qt.conf" << EOF
-[Paths]
-Translations=$OUT_DIR/lib/qt4/translations
-Plugins=$OUT_DIR/lib/qt4/plugins
-EOF
-
-WITH_PYTHON=@WITH_PYTHON@
-
-if [ "$WITH_PYTHON" = true ] ; then
-
-if [ ! -f "$OTB_PYTHON_EXE" ] ; then
-    OTB_PYTHON_EXE=$(which python)
-fi
-
-python_INSTALLED_SONAME=@python_INSTALLED_SONAME@
-
-python_major_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[0])")
-python_minor_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[1])")
-python_patch_version=$($OTB_PYTHON_EXE -c "import sys;print(sys.version_info[2])")
-python_version="$python_major_version.$python_minor_version.$python_patch_version"
-
-python_check_failed() {
-    printf %s\\n "*****Error occurred during installation******"
-    printf %s\\n "OTB python bindings requires python2.6 or python2.7 but current detected python version is $python_version"
-    printf %s\\n "If you have python2.6 or Python2.7 installed in your system "
-    printf %s\\n "You should set OTB_PYTHON_EXE and re-run this installation script."
-    printf %s\\n "eg: OTB_PYTHON_EXE=/path/to/python2.7 ./OTB-X.Y-Linux64.run"
-    exit 1;
-}
-if [ "$python_major_version" -gt 2 ]; then
-python_check_failed
-fi
-
-if [ "$python_minor_version" -lt 5 ]; then
-python_check_failed
-fi
-
-python_INSTSONAME=$($OTB_PYTHON_EXE -c "import sys; from distutils import sysconfig; print (sysconfig.get_config_var('INSTSONAME'));")
-
-python_lib_dirs="/usr/lib /usr/lib64 /usr/lib/x86_64-linux-gnu"
-found_python_lib="0"
-python_lib_file_path=""
-for list_of_dir in $python_lib_dirs
-do
-    if [ -f "$list_of_dir/$python_INSTSONAME" ]; then
-        python_lib_file_path="$list_of_dir/$python_INSTSONAME"
-        found_python_lib="1"
-        break
-    fi
-done
-
-if [ "$found_python_lib" -eq "1" ]; then
-    printf %s\\n "OTB python bindings will be configured for $OTB_PYTHON_EXE ( version: $python_version )"
-    printf %s\\n "Found python library: $python_lib_file_path"
-    ln -sf "$python_lib_file_path" "$OUT_DIR/lib/$python_INSTALLED_SONAME"
-    "$PATCH_ELF_EXE" "--set-rpath" "$OUT_DIR/lib" "$OUT_DIR/lib/python/_otbApplication.so"
-    printf %s\\n "To use OTB python bindings:"
-    printf %s\\n "'export PYTHONPATH=$OUT_DIR/lib/python'"
-    printf %s\\n "To test OTB python bindings:"
-    printf %s\\n "$OTB_PYTHON_EXE -c 'import otbApplication'"
-else
-    printf %s\\n "*****Error occurred during installation******"
-    printf %s\\n "Python interpreter detected is : $OTB_PYTHON_EXE ( version: $python_version )"
-    printf %s\\n "$python_INSTSONAME cannot be found in any of search directories."
-    printf %s\\n "We had searched following directories $python_lib_dirs"
-    printf %s\\n "If you don't have python-dev package installed, install it and make a symlink"
-    printf %s\\n "If you don't have python headers and so installed on a custom location, then make a symlink"
-    printf %s\\n "eg: ln -s /usr/lib/x86_64-linux-gnu/$python_INSTSONAME $OUT_DIR/lib/$python_INSTALLED_SONAME"
-fi
-
-fi; 
-
-# PKG_OTB_VERSION_STRING=@PKG_OTB_VERSION_STRING@
-sed -i "s,|release|,@PKG_OTB_VERSION_STRING@,g" "$OUT_DIR/README"
-
-rm -fr "$OUT_DIR/tools"
-
-rm -f  "$OUT_DIR/pkgsetup"
-
-rm -f  "$OUT_DIR/make_symlinks"
-
diff --git a/SuperBuild/Packaging/Files/macx_pkgsetup.in b/SuperBuild/Packaging/Files/macx_pkgsetup.in
deleted file mode 100644
index dde59b5b45543375982a2bfb01b72809cc21c416..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/macx_pkgsetup.in
+++ /dev/null
@@ -1,266 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-
-DIRNAME_0=$(dirname "$0")
-cd  "$DIRNAME_0"
-
-# NOTE: $OUT_DIR is also used in make_sylinks script (see below)
-# Avoid any pre-mature optimization on variable names here.
-
-OUT_DIR=$(pwd)
-
-# find install_name_tool
-INSTALL_NAME_TOOL=$(which install_name_tool)
-if [ -z "$INSTALL_NAME_TOOL" ]; then
-    echo "install_name_tool does not exists.."
-    echo "please install install_name_tool and make sure it can be found from PATH"
-    exit 1;
-fi
-
-# no interference with DYLD_LIBRARY_PATH and DYLD_FALLBACK_LIBRARY_PATH
-DYLD_LIBRARY_PATH=
-DYLD_FALLBACK_LIBRARY_PATH=
-
-echo "Configuring..."
-
-LIBRARY_FILES=$(find "$OUT_DIR/lib" -maxdepth 1 -type f)
-EXE_FILES=$(find "$OUT_DIR/bin"  -type f -exec file {} \; | grep -i "Mach-O*.*executable"|cut -d ':' -f1)
-# run install_name_tool
-for lib_file in $LIBRARY_FILES $EXE_FILES; do
-    #echo "adding rpath to $OUT_DIR/$lib_file"
-    if [ -f "$lib_file" ]; then
-      lib_file_original_rpaths=$(otool -l "$lib_file" | grep -A 3 "LC_RPATH" | grep -oE 'path .* \(offset' | cut -d ' ' -f 2)
-      for original_rpath in $lib_file_original_rpaths; do
-        $INSTALL_NAME_TOOL "-delete_rpath" "$original_rpath" "$lib_file"
-      done
-      $INSTALL_NAME_TOOL "-add_rpath" "$OUT_DIR/lib" "$lib_file"
-    fi
-done
-
-
-LONG_VERSION_STRING=@Monteverdi_VERSION_MAJOR@.@Monteverdi_VERSION_MINOR@.@Monteverdi_VERSION_PATCH@
-SHORT_VERSION_STRING=@Monteverdi_VERSION_MAJOR@.@Monteverdi_VERSION_MINOR@
-
-I_AM_XDK=@IS_XDK@
-
-
-# if [ "$I_AM_XDK" = true ] ; then
-
-#     sed -i "" "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/Modules/ITKZLIB.cmake
-#     sed -i "" "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/ITKConfig.cmake
-#     sed -i "" "s,@DEPENDENCIES_INSTALL_DIR@,$OUT_DIR,g" lib/cmake/ITK-@PKG_ITK_SB_VERSION@/ITKTargets-release.cmake
-# else
-if [ "$I_AM_XDK" = false ] ; then
-    OTB_APP_FILES=$(find "$OUT_DIR/lib/otb/applications" -maxdepth 1 -type f)
-    # run install_name_tool
-    for app_file in $OTB_APP_FILES; do
-      #echo "adding rpath to $app_file"
-      if [ -f "$app_file" ]; then
-        $INSTALL_NAME_TOOL "-rpath" "@ORIGINAL_RPATH_TO_REPLACE@" "$OUT_DIR/lib" "$app_file"
-      fi
-    done
-    if [ -f "$OUT_DIR/lib/python/_otbApplication.so" ]; then
-      $INSTALL_NAME_TOOL "-rpath" "@ORIGINAL_RPATH_TO_REPLACE@" "$OUT_DIR/lib" "$OUT_DIR/lib/python/_otbApplication.so"
-    fi
-
-    rm -fr "Mapla.app"
-    rm -fr "Monteveridi.app"
-    
-    mkdir -p "Mapla.app/Contents/MacOS"
-    mkdir -p "Mapla.app/Contents/Resources"
-    mkdir -p "Monteverdi.app/Contents/MacOS"
-    mkdir -p "Monteverdi.app/Contents/Resources"
-
-    cat > "Mapla.app/Contents/Info.plist" << EOF
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-	<dict>
-	  <key>CFBundleExecutable</key>
-	  <string>STARTUP_FILE</string>
-	  <key>CFBundleIconFile</key>
-	  <string>Monteverdi.icns</string>
-	  <key>CFBundleInfoDictionaryVersion</key>
-	  <string>6.0</string>
-	  <key>CFBundlePackageType</key>
-	  <string>APPL</string>
-	  <key>CFBundleLongVersionString</key>
-	  <string>LONG_VERSION</string>
-	  <key>CFBundleShortVersionString</key>
-	  <string>SHORT_VERSION</string>
-	</dict>
-</plist>
-EOF
-
-    cat > "$OUT_DIR/Mapla.app/Contents/MacOS/Mapla" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-export LC_NUMERIC=C
-export OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications
-export GDAL_DATA=$OUT_DIR/share/gdal
-export GEOTIFF_CSV=$OUT_DIR/share/epsg_csv
-$OUT_DIR/bin/mapla "\$@"
-EOF
-
-    chmod +x "$OUT_DIR/Mapla.app/Contents/MacOS/Mapla"
-
-    cat > "$OUT_DIR/Monteverdi.app/Contents/MacOS/Monteverdi" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-export LC_NUMERIC=C
-export OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications
-export GDAL_DATA=$OUT_DIR/share/gdal
-export GEOTIFF_CSV=$OUT_DIR/share/epsg_csv
-$OUT_DIR/bin/monteverdi "\$@"
-EOF
-
-    cat > "$OUT_DIR/Monteverdi.app/Contents/Resources/qt.conf" << EOF
-[Paths]
-Translations=$OUT_DIR/lib/qt4/translations
-Plugins=$OUT_DIR/lib/qt4/plugins
-EOF
-
-    cat > "$OUT_DIR/Mapla.app/Contents/Resources/qt.conf" << EOF
-[Paths]
-Translations=$OUT_DIR/lib/qt4/translations
-Plugins=$OUT_DIR/lib/qt4/plugins
-EOF
-
-    cat > "$OUT_DIR/bin/qt.conf" << EOF
-[Paths]
-Translations=$OUT_DIR/lib/qt4/translations
-Plugins=$OUT_DIR/lib/qt4/plugins
-EOF
-        
-    
-    chmod +x "$OUT_DIR/Monteverdi.app/Contents/MacOS/Monteverdi"
-
-    cp "Mapla.app/Contents/Info.plist" "Monteverdi.app/Contents/Info.plist"
-    cp "$OUT_DIR/Monteverdi.icns" "Monteverdi.app/Contents/Resources/"
-    cp "$OUT_DIR/Monteverdi.icns" "Mapla.app/Contents/Resources/"
-
-    sed -i "" "s,STARTUP_FILE,Mapla,g" "Mapla.app/Contents/Info.plist"
-    sed -i "" "s,LONG_VERSION,$LONG_VERSION_STRING,g" "Mapla.app/Contents/Info.plist"
-    sed -i "" "s,SHORT_VERSION,$SHORT_VERSION_STRING,g" "Mapla.app/Contents/Info.plist"
-
-    sed -i "" "s,STARTUP_FILE,Monteverdi,g" "Monteverdi.app/Contents/Info.plist"
-    sed -i "" "s,LONG_VERSION,$LONG_VERSION_STRING,g" "Monteverdi.app/Contents/Info.plist"
-    sed -i "" "s,SHORT_VERSION,$SHORT_VERSION_STRING,g" "Monteverdi.app/Contents/Info.plist"
-
-cat > "$OUT_DIR/otbenv.profile" << EOF
-#!/usr/bin/env bash
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-PATH=$OUT_DIR/bin:\$PATH
-PYTHONPATH=$OUT_DIR/lib/python:\$PYTHONPATH
-GDAL_DATA=$OUT_DIR/share/gdal
-GEOTIFF_CSV=$OUT_DIR/share/epsg_csv
-if [ -z "\$OTB_APPLICATION_PATH" ] || [ "\$OTB_APPLICATION_PATH" = "" ]; then
-    OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications
-else
-    OTB_APPLICATION_PATH=\$(cd "\$OTB_APPLICATION_PATH" 2>/dev/null && pwd -P)
-    if ! [ "\$OTB_APPLICATION_PATH" = "$OUT_DIR/lib/otb/applications" ]; then
-      OTB_APPLICATION_PATH=$OUT_DIR/lib/otb/applications:\$OTB_APPLICATION_PATH
-    fi
-fi
-
-export LC_NUMERIC=C
-export PATH
-export GDAL_DATA
-export GEOTIFF_CSV
-export PYTHONPATH
-export OTB_APPLICATION_PATH
-EOF
-
-chmod +x "$OUT_DIR/otbenv.profile"
-
-fi
-
-
-# echo "Creating symbolic links..."
-. "./make_symlinks"
-
-rm -f "$OUT_DIR/Monteverdi.icns"
-
-rm -f "$OUT_DIR/pkgsetup"
-
-rm -f "$OUT_DIR/make_symlinks"
-
-rm -fr "$OUT_DIR/tools"
-
-open "$OUT_DIR"
diff --git a/SuperBuild/Packaging/Files/mapla.bat b/SuperBuild/Packaging/Files/mapla.bat
deleted file mode 100644
index 77358001e1f7fb692503c5f265d9a70f9a31882b..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/mapla.bat
+++ /dev/null
@@ -1,19 +0,0 @@
-:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-:: Mapla launcher to set up proper environment
-:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-@echo off
-setlocal
-
-:: Get the directory of the current script
-set CURRENT_SCRIPT_DIR=%~dp0
-
-:: Setup environment
-call %CURRENT_SCRIPT_DIR%otbenv.cmd
-
-:: Set current dir to HOME dir because Monteverdi generates temporary files and need write access
-cd %HOMEDRIVE%%HOMEPATH%
-
-:: Start Monteverdi
-start "Monteverdi Application Launcher" /B "%CURRENT_SCRIPT_DIR%bin\mapla.exe" %*
-
-endlocal
diff --git a/SuperBuild/Packaging/Files/monteverdi.bat b/SuperBuild/Packaging/Files/monteverdi.bat
deleted file mode 100644
index 3f1b301f97d85083119ec4e12205f2fdf1158f1e..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/monteverdi.bat
+++ /dev/null
@@ -1,19 +0,0 @@
-:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-:: Monteverdi launcher to set up proper environment
-:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-@echo off
-setlocal
-
-:: Get the directory of the current script
-set CURRENT_SCRIPT_DIR=%~dp0
-
-:: Setup environment
-call %CURRENT_SCRIPT_DIR%otbenv.cmd
-
-:: Set current dir to HOME dir because Monteverdi generates temporary files and need write access
-cd %HOMEDRIVE%%HOMEPATH%
-
-:: Start Monteverdi
-start "Monteverdi Viewer" /B "%CURRENT_SCRIPT_DIR%bin\monteverdi.exe" %*
-
-endlocal
diff --git a/SuperBuild/Packaging/Files/otbenv.bash b/SuperBuild/Packaging/Files/otbenv.bash
deleted file mode 100644
index 3eedd8eb822b9567b900f28310fb548e06785ee2..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/otbenv.bash
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/env bash
-
-CURRENT_DIR=$(cd -P -- "$(dirname -- "$BASH_SOURCE")" && printf '%s\n' "$(pwd -P)")
-
-unset LD_LIBRARY_PATH
-
-PATH=$CURRENT_DIR/bin:$PATH
-GDAL_DATA=$CURRENT_DIR/share/data
-GEOTIFF_CSV=$CURRENT_DIR/share/epsg_csv
-PYTHONPATH=$CURRENT_DIR/lib/python:$PYTHONPATH
-OTB_APPLICATION_PATH=$CURRENT_DIR/lib/otb/applications
-GDAL_DRIVER_PATH="disable"
-LC_NUMERIC=C
-
-export PATH
-export GDAL_DATA
-export GEOTIFF_CSV
-export PYTHONPATH
-export OTB_APPLICATION_PATH
-export LC_NUMERIC
diff --git a/SuperBuild/Packaging/Files/otbenv.cmd b/SuperBuild/Packaging/Files/otbenv.cmd
deleted file mode 100644
index a9d5035027c7d99e99b0aa343a4ba9429858a35a..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/Files/otbenv.cmd
+++ /dev/null
@@ -1,11 +0,0 @@
-:: Setup environment for OTB package
-set CURRENT_SCRIPT_DIR=%~dp0
-
-set PATH=%CURRENT_SCRIPT_DIR%bin;%PATH%
-set GDAL_DATA=%CURRENT_SCRIPT_DIR%share\data
-set GEOTIFF_CSV=%CURRENT_SCRIPT_DIR%share\epsg_csv
-set PYTHONPATH=%CURRENT_SCRIPT_DIR%lib\python;%PYTHONPATH%
-set OTB_APPLICATION_PATH=%CURRENT_SCRIPT_DIR%lib\otb\applications
-
-:: Set numeric locale to C
-set LC_NUMERIC=C
diff --git a/SuperBuild/Packaging/InstallSupportFiles.cmake b/SuperBuild/Packaging/InstallSupportFiles.cmake
deleted file mode 100644
index da2559ae0067bb48a76f01f482d4d117bff35153..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/InstallSupportFiles.cmake
+++ /dev/null
@@ -1,442 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# Get the translation files coming with Qt, and install them in the bundle
-# They are loaded by Monteverdi.
-function(get_qt_translation_files RESULT)
-    # These files are the "qt_<localename>.qm" files
-    # They are located in QT_TRANSLATIONS_DIR, which comes from FindQt4
-    file(GLOB translation_files ${QT_TRANSLATIONS_DIR}/qt_*)
-
-    # We need to remove the "qt_help_<localename>.qm" files from this list
-    foreach(translation_item ${translation_files})
-      if(${translation_item} MATCHES "qt_help")
-        list(REMOVE_ITEM translation_files ${translation_item})
-      endif()
-    endforeach()
-
-    set(${RESULT} ${translation_files} PARENT_SCOPE)
-  endfunction()
-
-
-function(func_install_xdk_files)
-
-  #The list of REQ_SHARE_DIR is made up from <mxe-target-dir>/share/
-  #It may vary in future. I prefer not to glob on the share dir and
-  #end up distributing man, info etc.. which ar irrelvant for windows
-
-  #TODO: cleaup this function. current
-  # code is bit of picking each .lib and .dll for now
-  # see opencv, itk, 
-  foreach(REQ_SHARE_DIR
-      aclocal
-      Armadillo
-      applications
-      cmake
-      dbus-1
-      fontconfig
-      libgta
-      locale
-      xml
-      applications
-      cmake
-      icons
-      OpenCV
-      pixmaps
-      pkgconfig
-      )
-    if(EXISTS "${DEPENDENCIES_INSTALL_DIR}/share/${REQ_SHARE_DIR}")
-      func_install_without_message("${DEPENDENCIES_INSTALL_DIR}/share/${REQ_SHARE_DIR}" "share")
-    endif()
-  endforeach()
-
-  set(ITK_CMAKE_DIR "${DEPENDENCIES_INSTALL_DIR}/lib/cmake/ITK-${PKG_ITK_SB_VERSION}")
-  message("COPY ${DEPENDENCIES_INSTALL_DIR}/lib/cmake/ITK-${PKG_ITK_SB_VERSION} to ${CMAKE_CURRENT_BINARY_DIR}/_tmp/ to patch")
-  execute_process(
-    COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/_tmp/
-    COMMAND ${CMAKE_COMMAND}
-    -E copy_directory
-    ${ITK_CMAKE_DIR}
-    ${CMAKE_CURRENT_BINARY_DIR}/_tmp/ITK-${PKG_ITK_SB_VERSION}
-    )
-
-  #reset ITK_CMAKE_DIR
-  set(ITK_CMAKE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_tmp/ITK-${PKG_ITK_SB_VERSION}")
-
-  set(DIR_LIST "${CMAKE_CURRENT_BINARY_DIR}/_tmp/ITK-${PKG_ITK_SB_VERSION}|${CMAKE_CURRENT_BINARY_DIR}/_tmp/ITK-${PKG_ITK_SB_VERSION}/Modules")
-
-  #SUPERBUILD_INSTALL_DIR
-  execute_process(
-    COMMAND ${CMAKE_COMMAND}
-    -DP_DIRS=${DIR_LIST}
-    -DP_MATCH=${CMAKE_INSTALL_PREFIX}
-    -DP_REPLACE=ITK_INSTALL_PREFIX
-    -P ${PACKAGE_OTB_SRC_DIR}/SuperBuild/CMake/post_install.cmake
-    RESULT_VARIABLE patch_itk_cmake_rv
-    )
-
-  file(STRINGS  "${SUPERBUILD_BINARY_DIR}/ITK/build/CMakeCache.txt"
-    MATCH_FOUND REGEX "ITK_USE_SYSTEM_ZLIB:BOOL=ON")
-  if(MATCH_FOUND)
-    find_package(ZLIB QUIET)
-    get_filename_component(ZLIB_PREFIX ${ZLIB_LIBRARY} PATH)
-    execute_process(
-      COMMAND ${CMAKE_COMMAND}
-      -DP_DIRS=${DIR_LIST}
-      -DP_MATCH=${ZLIB_PREFIX}
-      -DP_REPLACE=ITK_INSTALL_PREFIX
-      -P ${PACKAGE_OTB_SRC_DIR}/SuperBuild/CMake/post_install.cmake
-      )
-
-  endif()
-
-  func_install_without_message("${ITK_CMAKE_DIR}" "lib/cmake")
-
-  set(QT_REQ_DIRS)
-  if(WIN32)
-    #only affects windows due to regex on dll
-    #.lib are not taken when processing dependencies. 
-    # We just get .dlls which is enough for binary package
-    # For XDK, we need .lib files when building OTB using xdk
-    # For Linux. we get .so.X.Y.Z by finding the 'target'
-    # of any .so file. So there is no need for such a copy on
-    # Linux and OSX 
-    if(MSVC)
-      file(GLOB LIB_FILES "${DEPENDENCIES_INSTALL_DIR}/lib/*.lib")
-    else()
-      file(GLOB LIB_FILES "${DEPENDENCIES_INSTALL_DIR}/lib/*dll.*")
-    endif()
-
-    foreach(LIB_FILE ${LIB_FILES})
-      pkg_install_rule(${LIB_FILE})
-    endforeach()
-    
-    #qt/bin is also a special case for mxe.
-    file(GLOB QT_EXTRA_DLL_FILES "${DEPENDENCIES_INSTALL_DIR}/qt/bin/*.dll")
-    install(FILES ${QT_EXTRA_DLL_FILES} DESTINATION ${PKG_STAGE_DIR}/bin)
-
-    #list(APPEND QT_REQ_DIRS lib)
-    list(APPEND QT_REQ_DIRS include)
-    list(APPEND QT_REQ_DIRS imports)
-
-    #mxe installs qt in a separate directory under install prefix. So..
-    set(QT_INSTALL_DIR "${DEPENDENCIES_INSTALL_DIR}/qt")
-  else()
-    set(QT_INSTALL_DIR "${DEPENDENCIES_INSTALL_DIR}")
-
-  endif(WIN32)
-
-  list(APPEND QT_REQ_DIRS mkspecs)
-  list(APPEND QT_REQ_DIRS plugins)
-  list(APPEND QT_REQ_DIRS translations)
-  foreach(QT_REQ_DIR ${QT_REQ_DIRS} )
-    if(EXISTS "${QT_INSTALL_DIR}/${QT_REQ_DIR}")
-      func_install_without_message("${QT_INSTALL_DIR}/${QT_REQ_DIR}" "")
-    endif()
-  endforeach()
-
-  # #install ${DEPENDENCIES_INSTALL_DIR}/include directory. Attention to OTB includes
-  file(GLOB ALL_IN_INCLUDE_DIR "${DEPENDENCIES_INSTALL_DIR}/include/*")
-  foreach(INCLUDE_DIR_ITEM ${ALL_IN_INCLUDE_DIR})
-    get_filename_component(INCLUDE_DIR_ITEM_name ${INCLUDE_DIR_ITEM} NAME)
-    get_filename_component(INCLUDE_DIR_ITEM_name_we ${INCLUDE_DIR_ITEM} NAME_WE)
-    if(NOT "${INCLUDE_DIR_ITEM_name_we}" MATCHES "OTB|otb")
-      if( IS_DIRECTORY ${INCLUDE_DIR_ITEM})
-        install(CODE
-          "message(STATUS \"Installing: ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}/include/${INCLUDE_DIR_ITEM_name}/\")" )
-        install(
-          DIRECTORY   "${INCLUDE_DIR_ITEM}"
-          DESTINATION "${PKG_STAGE_DIR}/include/"
-          MESSAGE_NEVER
-          )
-      else()
-        install(
-          FILES   "${INCLUDE_DIR_ITEM}"
-          DESTINATION "${PKG_STAGE_DIR}/include/"
-          )
-      endif() #if( IS_DIRECTORY
-    endif() #if (NOT
-  endforeach()
-
-endfunction() #func_install_xdk_files
-
-function(func_install_support_files)
-
-  #a convenient cmake var for storing <prefix>/bin
-  set(PKG_STAGE_BIN_DIR "${PKG_STAGE_DIR}/bin")
-
-  #<prefix>/share for gdal data files
-  set(PKG_SHARE_DEST_DIR ${PKG_STAGE_DIR}/share)
-
-  set(PKG_SHARE_SOURCE_DIR ${DEPENDENCIES_INSTALL_DIR}/share)
-
-  set(GDAL_DATA ${PKG_SHARE_SOURCE_DIR}/gdal)
-  #MSVC install gdal-data in in a different directory. So we don't spoil it
-  if(MSVC)
-    set(GDAL_DATA ${DEPENDENCIES_INSTALL_DIR}/data)
-  endif()
-
-  # Just check if required variables are defined.
-  foreach(req
-      DEPENDENCIES_INSTALL_DIR
-      PKG_STAGE_DIR
-      PACKAGE_SUPPORT_FILES_DIR
-      OTB_INSTALL_DIR
-      )
-    if(NOT DEFINED ${req})
-      message(FATAL_ERROR "you must set ${req} before calling this method")
-    endif()
-    set(vars "${vars}  ${req}=[${${req}}]\n")
-  endforeach(req)
-
-  # one for debugging..
-  # install(CODE "message(\"CMake/PackageHelper.cmake:install_supoport_files(${outdir})\n${vars}\n\")")
-  if(NOT PKG_GENERATE_XDK)
-    func_install_otb_support_files()
-
-    #check if monteverdi executable is built?
-    if(EXISTS "${OTB_INSTALL_DIR}/bin/monteverdi${EXE_EXT}")
-      func_install_monteverdi_support_files()
-    endif()
-
-  endif() #NOT PKG_GENERATE_XDK
-
-  ####################### install GDAL data ############################
-  if(NOT EXISTS "${GDAL_DATA}/epsg.wkt")
-    message(FATAL_ERROR
-      "Cannot generate package without GDAL_DATA : ${GDAL_DATA} ${DEPENDENCIES_INSTALL_DIR}")
-  endif()
-
-
-  # install(
-  #   DIRECTORY ${GDAL_DATA}
-  #   DESTINATION ${PKG_SHARE_DEST_DIR}
-  #   )
-
-  func_install_without_message("${GDAL_DATA}" "share" )
-  ####################### install GeoTIFF data ########################
-  #install( DIRECTORY ${PKG_SHARE_SOURCE_DIR}/epsg_csv DESTINATION ${PKG_SHARE_DEST_DIR}  )
-
-  func_install_without_message("${PKG_SHARE_SOURCE_DIR}/epsg_csv" "share" )
-
-  ####################### install OSSIM data ##########################
-  #install( DIRECTORY ${PKG_SHARE_SOURCE_DIR}/ossim DESTINATION ${PKG_SHARE_DEST_DIR})
-
-  func_install_without_message("${PKG_SHARE_SOURCE_DIR}/ossim" "share" )
-
-  ####################### install proj share ##########################
-  if(EXISTS ${PKG_SHARE_SOURCE_DIR}/proj)
-    #install(DIRECTORY ${PKG_SHARE_SOURCE_DIR}/proj DESTINATION ${PKG_SHARE_DEST_DIR})
-    func_install_without_message("${PKG_SHARE_SOURCE_DIR}/proj" "share" )
-  endif()
-  
-  ####################### Install copyrights ##########################
-  #install license for windows package
-  #install(DIRECTORY ${PKG_SHARE_SOURCE_DIR}/copyright DESTINATION ${PKG_SHARE_DEST_DIR} )
-  func_install_without_message("${PKG_SHARE_SOURCE_DIR}/copyright" "share" )
-  install(FILES ${PKG_SHARE_SOURCE_DIR}/copyright/LICENSE DESTINATION ${PKG_STAGE_DIR})
-
-  ####################### Install VERSION ##########################
-
-  set(PKG_VERSION_FILE
-    "${OTB_INSTALL_DIR}/share/doc/${PKG_OTB_VERSION_MAJOR}.${PKG_OTB_VERSION_MINOR}/VERSION")
-  if(EXISTS ${PKG_VERSION_FILE} )
-    install(FILES ${PKG_VERSION_FILE} DESTINATION ${PKG_STAGE_DIR})
-  endif()
-
-endfunction()
-
-function(func_install_otb_support_files)
-  foreach(req
-      PKG_STAGE_DIR
-      OTB_INSTALL_DIR
-      DEPENDENCIES_INSTALL_DIR
-      )
-    if(NOT DEFINED ${req})
-      message(FATAL_ERROR "you must set ${req} before calling this method")
-    endif()
-    set(vars "${vars}  ${req}=[${${req}}]\n")
-  endforeach(req)
-
-  #a convenient cmake var for storing <prefix>/bin
-  set(PKG_STAGE_BIN_DIR "${PKG_STAGE_DIR}/bin")
-
-  #<prefix>/share for gdal data files
-  set(PKG_SHARE_DEST_DIR ${PKG_STAGE_DIR}/share)
-
-  set(PKG_SHARE_SOURCE_DIR ${DEPENDENCIES_INSTALL_DIR}/share)
-
-  #For Unixes we make them in the *pkgsetup.in
-  ##################### install environment setup file ##########################
-  if(WIN32)
-    install(
-      FILES ${PACKAGE_SUPPORT_FILES_DIR}/otbenv.cmd
-      DESTINATION ${PKG_STAGE_DIR}
-      )
-
-    install(
-      FILES ${PACKAGE_SUPPORT_FILES_DIR}/otbenv.bash
-      DESTINATION ${PKG_STAGE_DIR}
-      )
-    
-    #we need startup files for mapla monteverdi in the root directory
-    #For Unixes, we make them inside pkgsetup script!
-    foreach(exe_file mapla monteverdi)
-      install(
-        PROGRAMS ${PACKAGE_SUPPORT_FILES_DIR}/${exe_file}.bat
-        DESTINATION "${PKG_STAGE_DIR}"
-        )
-    endforeach()
-  endif()
-
-  ####################### install cli and gui scripts ###########################
-  file(GLOB PKG_APP_SCRIPTS
-    ${OTB_INSTALL_DIR}/bin/otbcli*
-    ${OTB_INSTALL_DIR}/bin/otbgui*) #
-
-  list(LENGTH PKG_APP_SCRIPTS PKG_APP_SCRIPTS_LENGTH)
-  if (PKG_APP_SCRIPTS_LENGTH LESS 1)
-    message(WARNING "PKG_APP_SCRIPTS is empty: ${PKG_APP_SCRIPTS}")
-  endif()
-
-  ##################### install cli and gui scripts #######################
-  install(PROGRAMS ${PKG_APP_SCRIPTS}  DESTINATION ${PKG_STAGE_BIN_DIR})
-
-  ########################## selftest script ##############################
-  if(WIN32)
-    set(PACKAGE_SELFTEST_SCRIPT selftester.bat)
-  else()
-    set(PACKAGE_SELFTEST_SCRIPT selftester.sh)
-  endif()
-  install(
-    FILES ${PACKAGE_SUPPORT_FILES_DIR}/${PACKAGE_SELFTEST_SCRIPT}
-    DESTINATION ${PKG_STAGE_BIN_DIR}
-    )
-
-
-endfunction()
-
-function(func_install_monteverdi_support_files)
-
-  #name/ext of qt's sqlite plugin. Varies with platform/OS
-  if(WIN32)
-    set(PKG_QTSQLITE_FILENAME "qsqlite4.dll")
-  elseif(APPLE)
-    set(PKG_QTSQLITE_FILENAME "libqsqlite.dylib")
-  elseif("${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
-    set(PKG_QTSQLITE_FILENAME "libqsqlite.so")
-  else()
-    message(FATAL_ERROR "func_install_monteverdi_support_files: Unknown OS/Platform")
-  endif()
-
-  #root folder where qt plugins are installed
-  set(PKG_QTPLUGINS_DIR "${PKG_STAGE_DIR}/lib/qt4/plugins")
-
-  #qt4's distributes some translation of common message string used in Qt.
-  #This are provided with any qt installation. We reuse them in otb package
-  #so as not to reinvent the wheels.
-  set(PKG_QT_TRANSLATIONS_DIR "${PKG_STAGE_DIR}/lib/qt4/translations")
-
-  #<prefix>/share for otb i18n directory. This is different from qt's i18N directory
-  #which is <prefix>/share/qt4/translations.
-  #set(PKG_xxOTB_Ixxx18N_DIR "${PKG_STAGE_DIR}/${PKG_OTB_INSTALL_DATA_DIR}/i18n")
-  # we find this value by parsing ConfigureMonteverdi.h
-  set(ConfigureMonteverdi_H "${OTB_BINARY_DIR}/Modules/Visualization/MonteverdiCore/ConfigureMonteverdi.h")
-  if(NOT EXISTS "${ConfigureMonteverdi_H}")
-    #maybe deactivate monteverdi?
-    message(FATAL_ERROR "${ConfigureMonteverdi_H} does not exists. Cannot continue")
-  endif()
-
-  file(
-    STRINGS "${ConfigureMonteverdi_H}"
-    ConfigureMonteverdi_H_CONTENTS
-    REGEX "^#define.Monteverdi_INSTALL_DATA_DIR")
-
-  string(REGEX REPLACE
-    "^#define.Monteverdi_INSTALL_DATA_DIR" ""
-    ConfigureMonteverdi_H_CONTENTS
-    ${ConfigureMonteverdi_H_CONTENTS} )
-
-  if(NOT ConfigureMonteverdi_H_CONTENTS)
-    message(FATAL_ERROR "Parse error in ${ConfigureMonteverdi_H}. Cannot continue")
-  endif()
-
-  string(
-    REGEX REPLACE "\"" ""
-    PKG_OTB_INSTALL_DATA_DIR
-    "${ConfigureMonteverdi_H_CONTENTS}")
-
-  if(NOT PKG_OTB_INSTALL_DATA_DIR)
-    message(FATAL_ERROR "parse error in ${ConfigureMonteverdi_H_CONTENTS}. Cannot continue")
-  endif()
-  
-  string(STRIP "${PKG_OTB_INSTALL_DATA_DIR}" PKG_OTB_INSTALL_DATA_DIR)
-
-  set(PKG_OTB_TRANSLATIONS_DIRNAME "${PKG_OTB_INSTALL_DATA_DIR}/i18n")
-
-  # Just check if required variables are defined.
-  foreach(req
-      PACKAGE_OTB_SRC_DIR
-      PACKAGE_SUPPORT_FILES_DIR
-      QT_PLUGINS_DIR
-      PKG_STAGE_BIN_DIR
-      PKG_QTSQLITE_FILENAME
-      PKG_QTPLUGINS_DIR
-      PKG_QT_TRANSLATIONS_DIR
-      PKG_OTB_TRANSLATIONS_DIRNAME
-      )
-    if(NOT DEFINED ${req} OR "${${req}}" STREQUAL "")
-      message(FATAL_ERROR "you must set ${req} before calling this method")
-    endif()
-    set(vars "${vars}  ${req}=[${${req}}]\n")
-  endforeach(req)
-
-  #install icon file for .app file. Monteverdi and Mapla has same icon!
-  if(APPLE)
-    install(FILES ${PACKAGE_SUPPORT_FILES_DIR}/Monteverdi.icns
-      DESTINATION ${PKG_STAGE_DIR})
-  endif()
-
-  ####################### install sqldriver plugin ########################
-  install(FILES ${QT_PLUGINS_DIR}/sqldrivers/${PKG_QTSQLITE_FILENAME}
-    DESTINATION ${PKG_QTPLUGINS_DIR}/sqldrivers)
-
-  ####################### install qt4 translations ###########################
-  #get all translations already distributed with qt4
-  get_qt_translation_files(QT_TRANSLATIONS_FILES)
-
-  #install all files in ${QT_TRANSLATIONS_FILES}
-  install(FILES ${QT_TRANSLATIONS_FILES}  DESTINATION ${PKG_QT_TRANSLATIONS_DIR})
-
-  ####################### install monteverdi translations #####################
-  #translation of monteverdi specific strings
-  if(NOT EXISTS "${OTB_INSTALL_DIR}/${PKG_OTB_TRANSLATIONS_DIRNAME}")
-    message(FATAL_ERROR "Error ${OTB_INSTALL_DIR}/${PKG_OTB_TRANSLATIONS_DIRNAME} not exists")
-  endif()
-  
-  file(GLOB APP_TS_FILES ${PACKAGE_OTB_SRC_DIR}/i18n/*.ts) # qm files
-  foreach(APP_TS_FILE ${APP_TS_FILES})
-    get_filename_component(APP_TS_FILENAME ${APP_TS_FILE} NAME_WE)
-    install(FILES ${OTB_INSTALL_DIR}/${PKG_OTB_TRANSLATIONS_DIRNAME}/${APP_TS_FILENAME}.qm
-      DESTINATION ${PKG_STAGE_DIR}/${PKG_OTB_TRANSLATIONS_DIRNAME}
-      )
-  endforeach()
-  
-endfunction()
diff --git a/SuperBuild/Packaging/PackageHelper.cmake b/SuperBuild/Packaging/PackageHelper.cmake
deleted file mode 100644
index cca27e9a0f1684cea475756bee5fb26453d5a416..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/PackageHelper.cmake
+++ /dev/null
@@ -1,577 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-macro(macro_super_package)
-  cmake_parse_arguments(PKG  "" "STAGE_DIR" "" ${ARGN} )
- 
-  set(LINUX FALSE)
-  if( "${CMAKE_SYSTEM_NAME}"  MATCHES "Linux" AND NOT MINGW)
-    set(LINUX TRUE)
-  endif()
-    
-  if("${PKG_STAGE_DIR}" STREQUAL "")
-    message(FATAL_ERROR "PKG_STAGE_DIR is empty. Just can't continue.")
-  endif()
-
-  if(NOT DEPENDENCIES_INSTALL_DIR)
-    message(FATAL_ERROR "DEPENDENCIES_INSTALL_DIR is not set of empty")
-  endif()
-
-  if(LINUX)
-    if(NOT FILE_COMMAND)
-      message(FATAL_ERROR "warning: No 'file' command, cannot continue...")
-    endif()
-
-    if(NOT PATCHELF_PROGRAM)
-      message(FATAL_ERROR "PATCHELF_PROGRAM not set")
-    endif()
-  endif(LINUX)
-  
-  #setting this variable. prints a lot of debug information
-  #set( PKG_DEBUG 1)
-
-  set(loader_program_PATHS)
-  set(eol_char "E")
-  if(MSVC)
-    set(loader_program_PATHS)
-    set(loader_program_names      "dumpbin")
-    set(loader_program_args       "/DEPENDENTS")
-    set(loader_program_regex      "^    ([^ ].*[Dd][Ll][Ll])${eol_char}$")
-  elseif(APPLE)
-    set(loader_program_PATHS)
-    set(loader_program_names    otool)
-    set(loader_program_args      "-l" )
-    set(loader_program_regex ".*name.*([ ].*dylib ).*${eol_char}$")
-  elseif(LINUX)
-    set(loader_program_PATHS)
-    set(loader_program_names    objdump)
-    set(loader_program_args    "-p" )
-    set(loader_program_regex "^..NEEDED.*([ ].*so.*)${eol_char}$")
-  elseif(MINGW)
-    set(loader_program_PATHS    "${MXE_MXEROOT}/usr/bin")
-    set(loader_program_names    "${OTB_TARGET_SYSTEM_ARCH}-w64-mingw32.shared-objdump")
-    set(loader_program_args     "-p")
-    set(loader_program_regex    "^\t*DLL Name: (.*\\.[Dd][Ll][Ll])${eol_char}$")
-  else()
-    message(FATAL_ERROR "Unknown platform: ")
-  endif()
-  
-  find_program(LOADER_PROGRAM "${loader_program_names}" PATHS ${loader_program_PATHS})
-  if(NOT LOADER_PROGRAM)
-    message(FATAL_ERROR "${loader_program_names} not found in ${loader_program_PATHS}.")
-  endif()
-
-  include(GetPrerequisites)
-
-  set(LOADER_PROGRAM_ARGS ${loader_program_args})
-
-  set(DEST_BIN_DIR bin)
-  set(DEST_APP_DIR lib/otb/applications)
-  
-  set(LIB_PREFIX lib)
-  set(DEST_LIB_DIR lib)
-  set(EXE_EXT "")
-  set(SCR_EXT ".sh")
-  set(LIB_EXT ".so")
-  set(PYMODULE_EXT ".so")
-  if(WIN32)
-    set(LIB_PREFIX)
-    set(DEST_LIB_DIR bin)
-    set(EXE_EXT ".exe")
-    set(LIB_EXT ".dll")
-    set(SCR_EXT ".bat")
-    set(PYMODULE_EXT ".pyd")
-  elseif(APPLE)
-    set(LIB_EXT ".dylib")
-  endif()
-
-  # find_loader_and_args(LOADER_PROGRAM LOADER_PROGRAM_ARGS)
-  
-  find_python_soname(python_INSTALLED_SONAME)
-
-  set(PKG_SEARCHDIRS)
-  if(WIN32)
-    if(MSVC)
-      list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/bin") #all other dlls
-      list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/lib") #Qt & Qwt dlls
-
-      if(NOT PKG_GENERATE_XDK)
-	if(DEFINED ENV{UniversalCRTSdkDir})
-          file(TO_CMAKE_PATH "$ENV{UniversalCRTSdkDir}" UCRT_SDK_DIR)
-          list(
-            APPEND
-            PKG_SEARCHDIRS
-            "${UCRT_SDK_DIR}/Redist/ucrt/DLLs/${OTB_TARGET_SYSTEM_ARCH}"
-            ) #ucrt dlls
-	else()
-          message(FATAL_ERROR
-	    "UniversalCRTSdkDir variable not set. call vcvarsall.bat <arch> first before starting build.")
-	endif()
-	
-	#additional msvc redist dll from VCINSTALLDIR
-	if(DEFINED ENV{VCINSTALLDIR})
-          file(TO_CMAKE_PATH "$ENV{VCINSTALLDIR}" PKG_VCINSTALLDIR)
-          list(
-            APPEND
-            PKG_SEARCHDIRS
-            "${PKG_VCINSTALLDIR}/redist/${OTB_TARGET_SYSTEM_ARCH}/Microsoft.VC140.CRT"
-            "${PKG_VCINSTALLDIR}/redist/${OTB_TARGET_SYSTEM_ARCH}/Microsoft.VC140.OPENMP"
-            )
-	else()
-          message(FATAL_ERROR
-	    "VCINSTALLDIR variable not set. call vcvarsall.bat <arch> first before starting build.")
-	endif()
-      endif() #NOT PKG_GENERATE_XDK
-    else()
-      file(GLOB MXE_GCC_LIB_DIR "${DEPENDENCIES_INSTALL_DIR}/bin/gcc*")
-      list(APPEND PKG_SEARCHDIRS ${MXE_GCC_LIB_DIR})
-      list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/qt/bin") #Qt
-      list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/qt/lib") #Qwt
-      list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/bin") #mxe dlls
-    endif()
-  else() #unixes
-    list(APPEND PKG_SEARCHDIRS "${OTB_INSTALL_DIR}/lib") #so
-    list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/lib") #superbuild .so /.dylib
-  endif()
-
-  #common for all platforms.
-  set(OTB_APPLICATIONS_DIR "${OTB_INSTALL_DIR}/lib/otb/applications")
-  list(APPEND PKG_SEARCHDIRS "${DEPENDENCIES_INSTALL_DIR}/bin") #superbuild, mxe binaries
-  list(APPEND PKG_SEARCHDIRS "${OTB_INSTALL_DIR}/bin") #otbApplicationLauncherCommandLine..
-  list(APPEND PKG_SEARCHDIRS "${OTB_APPLICATIONS_DIR}") #otb apps
-  list(APPEND PKG_SEARCHDIRS "${OTB_INSTALL_DIR}/lib/otb/python") #otbApplication.py
-
-  if(PKG_GENERATE_XDK)
-   list(APPEND PKG_SEARCHDIRS ${OTB_BINARY_DIR}/bin)
-  endif()
-
-  macro_empty_package_staging_directory()
-
-  set(PKG_PEFILES)
-
-  func_prepare_package()
-
-  set(program_list)
-  set(WITH_PYTHON "false")
-  if(OTB_WRAP_PYTHON)
-    set(WITH_PYTHON "true")
-  endif()
-  
-  set(IS_XDK "false")
-
-  if(LINUX)
-    set(PKGSETUP_IN_FILENAME linux_pkgsetup.in)
-  elseif(APPLE)
-    set(PKGSETUP_IN_FILENAME macx_pkgsetup.in)
-  endif()
-
-  if(PKG_GENERATE_XDK)
-    set(IS_XDK "true")
-    set(WITH_PYTHON "false")
-    message(STATUS "OTB_WRAP_PYTHON is set. But this will not be included in XDK")
-    if("${PKG_ITK_SB_VERSION}" STREQUAL "")
-      message(FATAL_ERROR "PKG_ITK_SB_VERSION not set. This is required for XDK")
-    endif()
-
-    func_install_xdk_files()
-  endif() #PKG_GENERATE_XDK
-    
-  ############# install package configure script ################
-  #if(UNIX AND NOT WIN32)
-  if(UNIX AND NOT WIN32)    
-    #avoid OTB stuff inside make_symlinks script
-    file(STRINGS "${CMAKE_BINARY_DIR}/make_symlinks_temp" make_symlinks_list)
-#    func_lisp( make_symlinks_list )
-    file(WRITE ${CMAKE_BINARY_DIR}/make_symlinks "#!/bin/sh\n")
-    foreach(make_symlink_cmd ${make_symlinks_list})
-      file(APPEND ${CMAKE_BINARY_DIR}/make_symlinks
-        "${make_symlink_cmd}\n")
-    endforeach()
-
-    if(APPLE)
-      set(ORIGINAL_RPATH_TO_REPLACE ${DEPENDENCIES_INSTALL_DIR}/lib)
-    endif()
-
-    configure_file(${PACKAGE_SUPPORT_FILES_DIR}/${PKGSETUP_IN_FILENAME}
-      ${CMAKE_BINARY_DIR}/pkgsetup @ONLY)
-    
-    list(APPEND program_list "${CMAKE_BINARY_DIR}/pkgsetup")
-    list(APPEND program_list "${CMAKE_BINARY_DIR}/make_symlinks")
- 
-    ########### install patchelf( linux only) ##################
-    if(LINUX)
-      list(APPEND program_list "${PATCHELF_PROGRAM}")
-    endif()
-  endif()
-
-  foreach(prog ${program_list})
-    install(
-      PROGRAMS ${prog}
-      DESTINATION ${PKG_STAGE_DIR})
-  endforeach()
-
-  ############# otb_loader executable ################
-  add_executable(otb_loader ${PACKAGE_SUPPORT_FILES_DIR}/otb_loader.cxx)
-  target_link_libraries(otb_loader ${CMAKE_DL_LIBS})
-  install(TARGETS otb_loader
-          RUNTIME DESTINATION ${PKG_STAGE_DIR}/bin COMPONENT Runtime)
-
-  # We need qt.conf on windows. for macx and linux we write it
-  # after extracting package
-  if(WIN32 AND NOT PKG_GENERATE_XDK)
-    install(FILES
-      ${PACKAGE_SUPPORT_FILES_DIR}/qt.conf
-      DESTINATION ${PKG_STAGE_DIR}/bin
-      )
-  endif()
-
-  install(FILES
-    ${CMAKE_CURRENT_SOURCE_DIR}/README
-    DESTINATION ${PKG_STAGE_DIR})
-
-endmacro(macro_super_package)
-
-
-function(func_prepare_package)
-
-  file(WRITE ${CMAKE_BINARY_DIR}/make_symlinks_temp  "")
-
-  #This must exist in any OTB Installation. minimal or full
-  #set(PKG_PEFILES "${OTB_INSTALL_DIR}/bin/otbApplicationLauncherCommandLine${EXE_EXT}")
-  if(NOT EXISTS "${OTB_INSTALL_DIR}/bin/otbApplicationLauncherCommandLine${EXE_EXT}")
-    message(
-      FATAL_ERROR
-      "${OTB_INSTALL_DIR}/bin/otbApplicationLauncherCommandLine${EXE_EXT} not found.")
-  endif()
-  
-  set(PKG_PEFILES "otbApplicationLauncherCommandLine${EXE_EXT}")
-
-  foreach(exe_file
-      "otbApplicationLauncherQt" "iceViewer" "otbTestDriver" "monteverdi" "mapla")
-    if(EXISTS "${OTB_INSTALL_DIR}/bin/${exe_file}${EXE_EXT}")
-        list(APPEND PKG_PEFILES "${exe_file}${EXE_EXT}")
-    else()
-      message(STATUS "${exe_file}${EXE_EXT} not found in ${OTB_INSTALL_DIR}/bin. (skipping)")
-    endif()
-  endforeach()
-  
-  if(PKG_GENERATE_XDK)
-    #Qt stuff
-    list(APPEND PKG_PEFILES "lrelease${EXE_EXT}")
-    list(APPEND PKG_PEFILES "moc${EXE_EXT}")
-    list(APPEND PKG_PEFILES "qmake${EXE_EXT}")
-    list(APPEND PKG_PEFILES "rcc${EXE_EXT}")
-    list(APPEND PKG_PEFILES "uic${EXE_EXT}")
-    list(APPEND PKG_PEFILES "proj${EXE_EXT}")
-    list(APPEND PKG_PEFILES "cs2cs${EXE_EXT}")
-
-    #shark is optional
-    if(EXISTS "${DEPENDENCIES_INSTALL_DIR}/bin/sharkVersion${EXE_EXT}")
-      list(APPEND PKG_PEFILES "sharkVersion${EXE_EXT}")
-    endif()
-    
-    #RK: there is a bug in itk cmake files in install tree 
-    #we workaround with below code
-    #start hack
-     file(GLOB itk_all_lib_files  
-     "${DEPENDENCIES_INSTALL_DIR}/${DEST_LIB_DIR}/${LIB_PREFIX}itk*${LIB_EXT}*"
-     "${DEPENDENCIES_INSTALL_DIR}/${DEST_LIB_DIR}/${LIB_PREFIX}ITK*${LIB_EXT}*"
-     )
-
-   foreach(itk_lib_file ${itk_all_lib_files})
-     func_is_file_a_symbolic_link("${itk_lib_file}" a_symlink itk_lib_file_target)
-     if(NOT a_symlink)
-       list(APPEND PKG_PEFILES "${itk_lib_file}")
-     endif()
-     endforeach()
-     #end hack
-
-    file(GLOB otb_test_exe_list 
-    "${DEPENDENCIES_INSTALL_DIR}/bin/gdal*${EXE_EXT}"    
-    "${OTB_BINARY_DIR}/bin/*Test*${EXE_EXT}"
-    )
-    foreach(otb_test_exe   ${otb_test_exe_list})
-      get_filename_component(otb_test_exe_name ${otb_test_exe} NAME)
-      list(APPEND PKG_PEFILES ${otb_test_exe_name})
-    endforeach()
-  endif()
-
-  # special case for msvc: ucrtbase.dll must be explicitly vetted.
-  # for proj.dll, see Mantis-1424
-  if(MSVC AND NOT PKG_GENERATE_XDK)
-    list(APPEND PKG_PEFILES "ucrtbase.dll")
-    list(APPEND PKG_PEFILES "proj.dll")
-  endif()
-  
-  file(GLOB OTB_APPS_LIST "${OTB_APPLICATIONS_DIR}/otbapp_*${LIB_EXT}") # /lib/otb
-  list(APPEND PKG_PEFILES ${OTB_APPS_LIST})
-
-  if(NOT PKG_GENERATE_XDK)
-    if(EXISTS "${OTB_INSTALL_DIR}/lib/otb/python/_otbApplication${PYMODULE_EXT}")
-      install(
-	DIRECTORY
-	${OTB_INSTALL_DIR}/lib/otb/python
-	DESTINATION ${PKG_STAGE_DIR}/lib
-	)
-    else()
-      if(OTB_WRAP_PYTHON)
-	message(FATAL_ERROR "OTB_WRAP_PYTHON is set , but cannot find _otbApplication${PYMODULE_EXT}")
-      endif()
-    endif()   
-  endif()#  if(NOT PKG_GENERATE_XDK)
-
-
-  func_install_support_files()
-
-  unset(matched_vars CACHE)
-  get_vars_ending_with("_USED|_RESOLVED" matched_vars)
-  foreach (var_to_unset IN LISTS matched_vars)
-    if(PKG_DEBUG)
-      message("unset ${var_to_unset} from cache")
-    endif()
-    unset(${var_to_unset} CACHE)
-  endforeach()
-
-  foreach(infile ${PKG_PEFILES})
-   get_filename_component(bn ${infile} NAME)
-   func_process_deps(${bn})
-  endforeach()
- 
-endfunction() #func_prepare_package
-
-function(func_process_deps input_file)
-
-  set(input_file_full_path)
-  search_library(${input_file} PKG_SEARCHDIRS input_file_full_path)
-
-  if(NOT input_file_full_path)
-    if(LINUX)
-      setif_value_in_list(is_gtk_lib "${input_file}" ALLOWED_SYSTEM_DLLS)
-      if(is_gtk_lib)
-	search_library(${input_file} PKG_GTK_SEARCHDIRS input_file_full_path)
-	if( NOT input_file_full_path)
-	  message(FATAL_ERROR "${input_file} not found. searched in ${PKG_GTK_SEARCHDIRS}")
-	endif()
-      endif()
-      if( NOT input_file_full_path)
-	message(FATAL_ERROR "${input_file} not found. searched in ${PKG_SEARCHDIRS}")
-	endif()
-    endif(LINUX)
-
-  endif() #if(NOT input_file_full_path)
-
-  if(NOT PKG_DEBUG)
-    message("Processing ${input_file_full_path}")
-  endif()
-
-  set(is_executable FALSE)
-  is_file_executable2(input_file_full_path is_executable)
-
-  if(NOT is_executable)
-    #copy back to input_file_full_path
-    pkg_install_rule(${input_file_full_path})
-    message("not is_executable ${input_file_full_path}")
-    return()
-  endif() #NOT is_executable
-
-  if(UNIX)
-    # Deal with symlinks.
-    # For any valid symlinks, (see 'not_valid' below) 
-    # we append ln -s source target commands to a file
-    # That file is  executed during installation. 
-    get_filename_component(bn_we ${input_file_full_path} NAME_WE)
-    get_filename_component(bn_path ${input_file_full_path} PATH)
-    
-    file(GLOB sofiles "${bn_path}/${bn_we}*")
-    foreach(sofile ${sofiles})
-      get_filename_component(basename_of_sofile ${sofile} NAME)
-      get_filename_component(sofile_ext ${sofile} EXT)
-      set(not_valid FALSE)
-      if(  "${sofile_ext}" MATCHES ".la"
-          OR "${sofile_ext}" MATCHES ".prl"
-          OR "${sofile_ext}" MATCHES ".a"
-          OR  IS_DIRECTORY "${sofile}" )
-        set(not_valid TRUE)
-      endif()
-
-      if(not_valid)
-        continue()
-      endif()
-
-      func_is_file_a_symbolic_link("${sofile}" is_symlink linked_to_file)
-
-      if(is_symlink)
-        add_to_symlink_list("${linked_to_file}" "${basename_of_sofile}")	
-      endif() # is_symlink
-
-    endforeach()
-
-  endif(UNIX)
-
-  set(raw_items)
-
-  execute_process(
-    COMMAND ${LOADER_PROGRAM} ${LOADER_PROGRAM_ARGS} "${input_file_full_path}"
-    RESULT_VARIABLE loader_rv
-    OUTPUT_VARIABLE loader_ov
-    ERROR_VARIABLE loader_ev
-    )
-  
-  if(loader_rv)
-    message(FATAL_ERROR "loader_ev=${loader_ev}\n PACKAGE-OTB: result_variable is '${loader_rv}'")
-  endif()
-
-  string(REPLACE ";" "\\;" candidates "${loader_ov}")
-  string(REPLACE "\n" "${eol_char};" candidates "${candidates}")
-  
-  get_filename_component(bn_name ${input_file_full_path} NAME)
-  set(${bn_name}_USED TRUE CACHE INTERNAL "")
-
-  if(PKG_DEBUG)
-    message("Processing ${input_file} started. Set ${bn_name}_USED=${${bn_name}_USED}")
-  endif()
-
-  foreach(candidate ${candidates})
-    if(NOT candidate)
-      continue()
-    endif()
-
-    if(NOT "${candidate}" MATCHES "${loader_program_regex}")
-      continue()
-    endif()
-   
-    string(REGEX REPLACE "${loader_program_regex}" "\\1" raw_item "${candidate}")
-
-    if(NOT raw_item)
-      continue()
-    endif()  
-
-    string(STRIP ${raw_item} raw_item)
-    set(is_system FALSE)
-    setif_value_in_list(is_system "${raw_item}" SYSTEM_DLLS)
-
-    if(APPLE AND NOT is_system)
-      if("${raw_item}" MATCHES "@rpath")
-        string(REGEX REPLACE "@rpath." "" raw_item "${raw_item}")
-      else()
-        message(FATAL_ERROR "'${raw_item}' does not have @rpath")
-      endif()
-    endif()
-
-    if(PKG_DEBUG AND ${raw_item}_RESOLVED)
-      message("${raw_item} is already resolved [${raw_item}_RESOLVED=${${raw_item}_RESOLVED}]")
-    endif()
-
-    if(is_system OR ${raw_item}_RESOLVED OR ${raw_item}_USED)
-      continue()
-    endif()
-    
-    list(APPEND raw_items ${raw_item})
-    
-  endforeach()
-
-  if(PKG_DEBUG)
-    string(REPLACE ";" "\n" raw_items_pretty_print "${raw_items}")
-    # message(FATAL_ERROR "raw_items=${raw_items_pretty_print}")
-  endif(PKG_DEBUG)
-
-  if(raw_items)
-    list(REVERSE raw_items)
-    foreach(item ${raw_items})      
-      search_library(${item} PKG_SEARCHDIRS item_full_path)
-      set(is_a_symlink FALSE)
-      set(item_target_file)
-      func_is_file_a_symbolic_link("${item_full_path}" is_a_symlink item_target_file)      
-      if(is_a_symlink)
-        set(${item}_RESOLVED TRUE CACHE INTERNAL "")
-        set(item ${item_target_file})
-      endif()
-      if(PKG_DEBUG)
-        message("${bn_name} depends on '${item}'. So we now process '${item}'") # [ ${item}_USED=${${item}_USED} ${item}_RESOLVED=${${item}_RESOLVED}]")
-      endif()
-      func_process_deps(${item})
-    endforeach()
-  endif()
-
-  set(${bn_name}_RESOLVED TRUE CACHE INTERNAL "")
-   if(PKG_DEBUG)
-     message("All dependencies of ${bn_name} are processed. Install file and set ${bn_name}_RESOLVED=${${bn_name}_RESOLVED}")
-   endif()
-
-   #Install the file with pkg_install_rule. This function has specific rules to decide wheather install file or not
-   pkg_install_rule(${input_file_full_path})
-
-endfunction() #function(func_process_deps infile)
-
-function(pkg_install_rule src_file)
-
-  get_filename_component(src_file_EXT ${src_file} EXT)
-  get_filename_component(src_file_NAME ${src_file} NAME)
-
-  set(file_type PROGRAMS)
-  if(NOT src_file_EXT)
-    set(output_dir "bin")  
-  elseif("${src_file_EXT}" MATCHES "(.[Dd][Ll][Ll]|.exe)")
-    set(output_dir "bin")
-  elseif("${src_file_EXT}" MATCHES "(.lib|.so|.dylib)")
-    set(output_dir "lib")
-    set(file_type FILES)
-  else()
-    message(FATAL_ERROR "unreachable code")
-  endif()
-  
-  set(SKIP_INSTALL FALSE)
-
-  setif_value_in_list(is_gtk_lib "${src_file_NAME}" GTK_LIB_LIST_1)
-  if(is_gtk_lib)
-    if(PKG_GENERATE_XDK)
-      set(SKIP_INSTALL TRUE)
-    else()
-      set(output_dir "lib/gtk")
-    endif() #if(PKG_GENERATE_XDK)
-  endif() #if(is_gtk_lib)
-  
-  #special case
-  if("${src_file_NAME}" MATCHES "^otbapp_")
-    set(output_dir "lib/otb/applications")
-    set(file_type PROGRAMS)
-  endif()
-
-  if(PKG_GENERATE_XDK)
-    if ("${src_file_NAME}"
-	MATCHES
-	"([Oo][Tt][Bb])|([Mm]onteverdi)|mapla|iceViewer"
-	)
-      set(SKIP_INSTALL TRUE)
-        
-      message("SKIP_INSTALL for ${src_file_NAME}")
-    endif()
-
-  endif()
-
-  if(NOT SKIP_INSTALL)
-    install(${file_type}
-      "${src_file}"
-      DESTINATION
-      "${PKG_STAGE_DIR}/${output_dir}")
-  endif()
-  
-endfunction()   
-
diff --git a/SuperBuild/Packaging/PackageMacros.cmake b/SuperBuild/Packaging/PackageMacros.cmake
deleted file mode 100644
index 237228235ad4b2040f02d28e8e7476c9bfd27887..0000000000000000000000000000000000000000
--- a/SuperBuild/Packaging/PackageMacros.cmake
+++ /dev/null
@@ -1,379 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-function(find_python_soname result)
-  set(${result} PARENT_SCOPE)
-  execute_process(
-    COMMAND ${PYTHON_EXECUTABLE}
-    -c
-    "import sys; from distutils import sysconfig; print (sysconfig.get_config_var('INSTSONAME'));"
-    RESULT_VARIABLE python_INSTALLED_SONAME_rv
-    OUTPUT_VARIABLE python_INSTALLED_SONAME_ov
-    )
-
-  if(NOT python_INSTALLED_SONAME_rv EQUAL 0)
-    message( FATAL_ERROR
-      "python_INSTALLED_SONAME_rv=${python_INSTALLED_SONAME_rv}: Cannot find python library")
-  endif()
-  set(${result} "${python_INSTALLED_SONAME_ov}" PARENT_SCOPE)
-endfunction()
-
-
-function(func_install_without_message src_dir dst_dir_suffix)
-  set (extra_func_args ${ARGN})
-  list(LENGTH extra_func_args num_extra_args)
-  if (${num_extra_args} GREATER 0)
-    list(GET extra_func_args 0 optional_msg)
-  endif()
-
-  if( "${dst_dir_suffix}" STREQUAL "")
-    set(dst_dir "${PKG_STAGE_DIR}")
-  else()
-    set(dst_dir "${PKG_STAGE_DIR}/${dst_dir_suffix}")
-  endif()
-
-  get_filename_component(src_dir_name ${src_dir} NAME)
-  set(install_msg "message(STATUS \"Installing: ${CMAKE_INSTALL_PREFIX}/${dst_dir}/${src_dir_name} ${optional_msg}\")")
-  install(CODE "${install_msg}" )
-  install(
-    DIRECTORY   ${src_dir}
-    DESTINATION ${dst_dir}
-    MESSAGE_NEVER )
-endfunction() #func_install_without_message
-
-
-macro(macro_empty_package_staging_directory)
-  message(STATUS "Empty package staging directory: ${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}")
-  execute_process(
-    COMMAND ${CMAKE_COMMAND}
-    -E remove_directory
-    "${CMAKE_INSTALL_PREFIX}/${PKG_STAGE_DIR}"
-    )
-endmacro() #macro_empty_package_staging_directory
-
-
-function(search_library input_file pkg_searchdirs result)
-  set(${result} "" PARENT_SCOPE)
-  foreach(pkg_searchdir ${${pkg_searchdirs}})
-
-    if(EXISTS ${pkg_searchdir}/${input_file} )
-      if(PKG_DEBUG)
-        message("Found '${pkg_searchdir}/${input_file}' (return)")
-      endif()
-      set(${result} "${pkg_searchdir}/${input_file}" PARENT_SCOPE)
-      return()
-    endif()
-
-    #check for file with lowercase
-    string(TOLOWER "${input_file}" input_file_lower )
-    if(EXISTS ${pkg_searchdir}/${input_file_lower})
-      set(${result} "${pkg_searchdir}/${input_file_lower}"  PARENT_SCOPE)
-      return()
-    endif()
-  endforeach()
-
-endfunction()
-
-macro(add_to_symlink_list src_file_name link_file_name)
-  #TODO: avoid code duplication here and later in install_rule
-
-  set(SKIP_INSTALL FALSE)
-
-  get_filename_component(src_file_name_NAME ${src_file_name} NAME)
-  
-  if(PKG_GENERATE_XDK)
-    if ("${src_file_name_NAME}"
-	MATCHES
-	"libOTB|libotb|otbApp|otbapp_|otbTest|libMonteverdi|monteverdi|mapla|iceViewer"
-	)
-      set(SKIP_INSTALL TRUE)
-    endif()
-  endif(PKG_GENERATE_XDK)
-  
-  setif_value_in_list(is_gtk_lib "${src_file_name_NAME}" GTK_LIB_LIST_1)
-  if(is_gtk_lib AND PKG_GENERATE_XDK)
-    set(SKIP_INSTALL TRUE)
-  endif()
-
-
-  # NOTE: $OUT_DIR is set actually in pkgsetup.in. So don't try
-  # any pre-mature optimization on that variable names
-  if(NOT SKIP_INSTALL)
-
-    set(lib_dir "lib")
-    if(is_gtk_lib)
-      set(lib_dir "lib/gtk")
-    endif()
-    file(APPEND
-      ${CMAKE_BINARY_DIR}/make_symlinks_temp
-      "ln -sf \"$OUT_DIR/${lib_dir}/${src_file_name}\" \"$OUT_DIR/${lib_dir}/${link_file_name}\" \n"
-      )
-  endif()
-endmacro()
-
-function(is_file_executable2 file_var result_var)
-  #
-  # A file is not executable until proven otherwise:
-  #
-  set(${result_var} 0 PARENT_SCOPE)
-
-  get_filename_component(file_full "${${file_var}}" ABSOLUTE)
-  string(TOLOWER "${file_full}" file_full_lower)
-  # If file name ends in .exe on Windows, *assume* executable:
-  #
-  if(WIN32 AND NOT UNIX)
-    if("${file_full_lower}" MATCHES "(\\.exe|\\.dll)$")
-      set(${result_var} 1 PARENT_SCOPE)
-      return()
-    endif()
-
-    # A clause could be added here that uses output or return value of dumpbin
-    # to determine ${result_var}. In 99%+? practical cases, the exe name
-    # match will be sufficient...
-    #
-  endif() #WIN32 AND NOT UNIX
-
-  func_is_file_a_symbolic_link("${file_full}" is_a_symlink file_full_target)
-  if(is_a_symlink)
-    message("Resolving '${file_full}' to '${file_full_target}")
-    get_filename_component(file_full_path "${file_full}" PATH)
-    set(file_full "${file_full_path}/${file_full_target}")
-    if( EXISTS "${file_full}")
-      set(${file_var} "${file_full}" PARENT_SCOPE)
-    else()
-      message(FATAL_ERROR "${file_full} does not exists. Cannot continue")
-    endif()
-
-    string(TOLOWER "${file_full}" file_full_lower)
-  endif()
-
-  # Use the information returned from the Unix shell command "file" to
-  # determine if ${file_full} should be considered an executable file...
-  #
-  # If the file command's output contains "executable" and does *not* contain
-  # "text" then it is likely an executable suitable for prerequisite analysis
-  # via the get_prerequisites macro.
-  #
-  #if we are not on a unix or unix-like platform, then we don't have any business here
-  if(NOT UNIX)
-    return()
-  endif()
-
-  if(NOT FILE_COMMAND)
-    message(FATAL_ERROR "warning: No 'file' command, cannot continue...")
-  endif()
-
-  if(NOT EXISTS "${file_full}")
-    message(FATAL_ERROR "err. '${file_full}' does not exists or is not absolute path")
-    set(${file_var} "" PARENT_SCOPE)
-  endif()
-
-  execute_process(COMMAND "${FILE_COMMAND}" "${file_full}"
-    RESULT_VARIABLE file_rv
-    OUTPUT_VARIABLE file_ov
-    ERROR_VARIABLE file_ev
-    OUTPUT_STRIP_TRAILING_WHITESPACE
-    )
-  if(NOT file_rv STREQUAL "0")
-    message(FATAL_ERROR "${FILE_COMMAND} failed: ${file_rv}\n${file_ev}")
-  endif()
-
-  # Replace the name of the file in the output with a placeholder token
-  # (the string " _file_full_ ") so that just in case the path name of
-  # the file contains the word "text" or "executable" we are not fooled
-  # into thinking "the wrong thing" because the file name matches the
-  # other 'file' command output we are looking for...
-  #
-  string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
-  string(TOLOWER "${file_ov}" file_ov)
-
-  # message(STATUS "file_ov='${file_ov}'")
-  # below executable check works for both mac osx and linux
-  # message("file_full=${file_ov}")
-  if("${file_ov}" MATCHES "executable")
-    #message(STATUS "executable!")
-    if("${file_ov}" MATCHES "text")
-      set(${result_var} 0 PARENT_SCOPE)
-      #message(FATAL_ERROR "but text, so *not* a binary executable!")
-    else()
-      set(${result_var} 1 PARENT_SCOPE)
-      return()
-    endif()
-  endif()
-
-  # detect position independent executables on Linux,
-  # where "file" gives "dynamically linked (uses shared libraries)"
-  if("${file_ov}" MATCHES "dynamically linked.*\(uses shared libs\)")
-    set(${result_var} 1 PARENT_SCOPE)
-    return()
-  endif()
-
-  # detect position independent executables on Linux,
-  # where "file" gives "shared object ... (uses shared libraries)"
-  if("${file_ov}" MATCHES "shared object.*\(uses shared libs\)")
-    set(${result_var} 1 PARENT_SCOPE)
-    return()
-  endif()
-
-  # detect shared libraries on Linux,
-  # where "file" gives "ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not stripped"
-  if("${file_ov}" MATCHES "elf.*shared object.*version")
-    set(${result_var} 1 PARENT_SCOPE)
-    return()
-  endif()
-
-  # "file" version 5.22 does not print "(used shared libraries)"
-  # but uses "interpreter"
-  if("${file_ov}" MATCHES "shared object.*interpreter")
-    set(${result_var} 1 PARENT_SCOPE)
-    return()
-  endif()
-
-  if(APPLE)
-    # detect shared libraries on Mac OSX
-    # where "file" gives "Mach-O 64-bit x86_64 dynamically linked shared library"
-    if("${file_ov}" MATCHES "mach-o.*dynamically linked shared library")
-      set(${result_var} 1 PARENT_SCOPE)
-      return()
-    endif()
-
-    #below check is redundant.  detect executables on Mac OSX
-    # where "file" gives "Mach-O 64-bit x86_64 executable"
-    if("${file_ov}" MATCHES "mach-o.*executable")
-      set(${result_var} 1 PARENT_SCOPE)
-      return()
-    endif()
-
-    # detect shared libraries on Mac OSX
-    # where "file" gives "Mach-O 64-bit x86_64 bundle"
-    if("${file_ov}" MATCHES "mach-o.*bundle")
-      set(${result_var} 1 PARENT_SCOPE)
-      return()
-    endif()
-
-  endif(APPLE)
-
-endfunction()
-
-
-# The below function is modified from GetPrerequisities.cmake
-# which is distributed with CMake.
-function(func_is_file_a_symbolic_link file result_var1 result_var2)
-  #
-  # A file is not executable until proven otherwise:
-  #
-  set(${result_var1} 0 PARENT_SCOPE)
-  set(${result_var2} "" PARENT_SCOPE)
-
-  get_filename_component(file_full "${file}" ABSOLUTE)
-  string(TOLOWER "${file_full}" file_full_lower)
-
-  # If file name ends in .exe on Windows, *assume* executable:
-  #
-  if(WIN32 AND NOT UNIX)
-    if("${file_full_lower}" MATCHES "\\.lnk$")
-      set(${result_var1} 1 PARENT_SCOPE)
-      #Assuming the file is linked to a file with same name without .lnk extension
-      get_filename_component(name_we_lnk "${file_full_lower}" NAME_WE)
-      set(${result_var2} "${name_we_lnk}" PARENT_SCOPE)
-      return()
-    endif()
-
-    # A clause could be added here that uses output or return value of dumpbin
-    # to determine ${result_var}. In 99%+? practical cases, the exe name
-    # match will be sufficient...
-    #
-  endif()
-
-  #if we are not on a unix or unix-like platform, then we don't have any business here
-  if(NOT UNIX)
-    return()
-  endif()
-
-  # Use the information returned from the Unix shell command "file" to
-  # determine if ${file_full} should be considered an executable file...
-  #
-  # If the file command's output contains "executable" and does *not* contain
-  # "text" then it is likely an executable suitable for prerequisite analysis
-  # via the get_prerequisites macro.
-  #
-  if(NOT FILE_COMMAND)
-    message(FATAL_ERROR "warning: No 'file' command, cannot continue...")
-  endif()
-
-  execute_process(COMMAND "${FILE_COMMAND}" "${file_full}"
-    RESULT_VARIABLE file_rv
-    OUTPUT_VARIABLE file_ov
-    ERROR_VARIABLE file_ev
-    OUTPUT_STRIP_TRAILING_WHITESPACE
-    )
-  if(NOT file_rv STREQUAL "0")
-    message(FATAL_ERROR "${FILE_COMMAND} failed: ${file_rv}\n${file_ev}")
-  endif()
-
-  # Replace the name of the file in the output with a placeholder token
-  # (the string " _file_full_ ") so that just in case the path name of
-  # the file contains the word "text" or "executable" we are not fooled
-  # into thinking "the wrong thing" because the file name matches the
-  # other 'file' command output we are looking for...
-  #
-  string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
-  string(TOLOWER "${file_ov}" file_ov_lower)
-
-  # message(FATAL_ERROR "file_ov='${file_ov}'")
-  if("${file_ov_lower}" MATCHES "symbolic link")
-    set(${result_var1} 1 PARENT_SCOPE)
-    #Now find where the symlink is linked to.
-    #Do a regex replace
-    string(REGEX REPLACE "_file_full_*.*symbolic.link.to." "" symlinked_to ${file_ov})
-
-    #older version of file command output has  [`} character(remove it).
-    string(REPLACE "`" "" symlinked_to ${symlinked_to} )
-
-    #older version of file command output has  {'} character(remove it).
-    string(REPLACE "'" "" symlinked_to "${symlinked_to}")
-
-    #strip final output
-    string(STRIP ${symlinked_to} symlinked_to)
-    set(${result_var2} "${symlinked_to}" PARENT_SCOPE)
-
-    #message(FATAL_ERROR "${file_full} is symlinked_to ${symlinked_to}")
-    return()
-  endif()
-
-endfunction()
-
-macro(setif_value_in_list matched value list)
-  set(${matched})
-  string(TOLOWER ${value} value_)
-  foreach (pattern ${${list}})
-    string(TOLOWER ${pattern} pattern_)
-    if("${value_}" MATCHES "${pattern_}")
-      set(${matched} TRUE)
-    endif()
-  endforeach()
-  #message("'${value}' not found in ${list}")
-endmacro()
-
-function (get_vars_ending_with suffix result)
-  get_cmake_property(all_cmake_vars VARIABLES)
-  string (REGEX MATCHALL "(^|;)[A-Za-z0-9_\\.\\-]*(${suffix})" _matchedVars "${all_cmake_vars}")
-  set(${result} ${_matchedVars} PARENT_SCOPE)
-endfunction()
diff --git a/SuperBuild/patches/CURL/curl-1-cmake-all.diff b/SuperBuild/patches/CURL/curl-1-cmake-all.diff
new file mode 100755
index 0000000000000000000000000000000000000000..e2e0807143542ebb4a73c4fa5d6821cedaa6a4df
--- /dev/null
+++ b/SuperBuild/patches/CURL/curl-1-cmake-all.diff
@@ -0,0 +1,67 @@
+diff -burN curl-7.40.0/CMake/CurlTests.c curl-7.40.0.orig/CMake/CurlTests.c
+--- curl-7.40.0/CMake/CurlTests.c	2017-07-26 15:24:27.473903048 +0200
++++ curl-7.40.0.orig/CMake/CurlTests.c	2017-07-26 15:22:05.268949035 +0200
+@@ -139,7 +139,7 @@
+   rc = gethostbyname_r(address, &h, &hdata);
+ #elif defined(HAVE_GETHOSTBYNAME_R_5) || \
+       defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT)
+-  rc = gethostbyname_r(address, &h, buffer, 8192, 0, &h_errnop);
++  rc = gethostbyname_r(address, &h, buffer, 8192, &h_errnop);
+   (void)hp; /* not used for test */
+ #elif defined(HAVE_GETHOSTBYNAME_R_6) || \
+       defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT)
+diff -burN curl-7.40.0.orig/CMake/OtherTests.cmake curl-7.40.0/CMake/OtherTests.cmake
+--- curl-7.40.0.orig/CMake/OtherTests.cmake	2014-11-20 18:42:16.000000000 +0100
++++ curl-7.40.0/CMake/OtherTests.cmake	2017-07-21 16:37:37.414343678 +0200
+@@ -10,6 +10,7 @@
+ 
+ set(signature_call_conv)
+ if(HAVE_WINDOWS_H)
++   set(_source_epilogue "${_source_epilogue}\n#define _WINSOCKAPI_")
+   add_header_include(HAVE_WINDOWS_H "windows.h")
+   add_header_include(HAVE_WINSOCK2_H "winsock2.h")
+   add_header_include(HAVE_WINSOCK_H "winsock.h")
+@@ -163,7 +164,9 @@
+     return 0;
+   }" HAVE_MSG_NOSIGNAL)
+ 
+-if(NOT HAVE_WINDOWS_H)
++if(HAVE_WINDOWS_H)
++add_header_include(HAVE_WINSOCK2_H "winsock2.h")
++else()
+   add_header_include(HAVE_SYS_TIME_H "sys/time.h")
+   add_header_include(TIME_WITH_SYS_TIME "time.h")
+   add_header_include(HAVE_TIME_H "time.h")
+diff -burN curl-7.40.0.orig/src/CMakeLists.txt curl-7.40.0/src/CMakeLists.txt
+--- curl-7.40.0.orig/src/CMakeLists.txt	2014-11-20 18:42:17.000000000 +0100
++++ curl-7.40.0/src/CMakeLists.txt	2017-07-21 16:37:41.082367733 +0200
+@@ -25,14 +25,21 @@
+       "${CMAKE_CURRENT_SOURCE_DIR}/tool_hugehelp.h"
+     VERBATIM)
+ else()
+-  add_custom_command(
+-    OUTPUT tool_hugehelp.c
+-    COMMAND echo "/* built-in manual is disabled, blank function */" > tool_hugehelp.c
+-    COMMAND echo "#include \"tool_hugehelp.h\"" >> tool_hugehelp.c
+-    COMMAND echo "void hugehelp(void) {}" >> tool_hugehelp.c
+-    DEPENDS
+-      "${CMAKE_CURRENT_SOURCE_DIR}/tool_hugehelp.h"
+-    VERBATIM)
++file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tool_hugehelp.c
++"/*built-in manual is disabled, blank function */\n"
++)
++file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/tool_hugehelp.c
++"#include \"tool_hugehelp.h\"\nvoid hugehelp(void) {}\n"
++)
++
++  # add_custom_command(
++    # OUTPUT tool_hugehelp.c
++    # COMMAND echo "/* built-in manual is disabled, blank function */" > tool_hugehelp.c
++    # COMMAND echo "#include \"tool_hugehelp.h\"" >> tool_hugehelp.c
++    # COMMAND echo "void hugehelp(void) {}" >> tool_hugehelp.c
++    # DEPENDS
++      # "${CMAKE_CURRENT_SOURCE_DIR}/tool_hugehelp.h"
++    # VERBATIM)
+ endif()
+ 
+ transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
diff --git a/SuperBuild/patches/GDAL/gdal-2-enviRotation-all.diff b/SuperBuild/patches/GDAL/gdal-2-enviRotation-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..8c7f7acdce6b34c908a9a10580f2697157534658
--- /dev/null
+++ b/SuperBuild/patches/GDAL/gdal-2-enviRotation-all.diff
@@ -0,0 +1,32 @@
+diff -burN gdal-2.2.1-orig/frmts/raw/envidataset.cpp gdal-2.2.1/frmts/raw/envidataset.cpp
+--- gdal-2.2.1-orig/frmts/raw/envidataset.cpp	2017-06-23 14:18:43.000000000 +0200
++++ gdal-2.2.1/frmts/raw/envidataset.cpp	2017-07-20 18:25:05.373655046 +0200
+@@ -620,10 +620,13 @@
+         adfGeoTransform[4] != 0.0 || adfGeoTransform[5] != 1.0;
+     if( bHasNonDefaultGT )
+     {
++        const double dfDet = adfGeoTransform[1] * adfGeoTransform[5] -
++                             adfGeoTransform[2] * adfGeoTransform[4];
++        const double dfSign = (dfDet>0.0 ? 1.0 : -1.0);
+         const double dfRotation1 =
+-            -atan2(-adfGeoTransform[2], adfGeoTransform[1]) * kdfRadToDeg;
++            -atan2(dfSign * adfGeoTransform[2], adfGeoTransform[1]) * kdfRadToDeg;
+         const double dfRotation2 =
+-            -atan2(-adfGeoTransform[4], -adfGeoTransform[5]) * kdfRadToDeg;
++            -atan2(-adfGeoTransform[4], dfSign * adfGeoTransform[5]) * kdfRadToDeg;
+         const double dfRotation = (dfRotation1 + dfRotation2) / 2.0;
+ 
+         if( fabs(dfRotation1 - dfRotation2) > 1e-5 )
+@@ -1534,7 +1537,12 @@
+ 
+     // Fallback to localcs if we don't recognise things.
+     if( oSRS.GetRoot() == NULL )
++        {
+         oSRS.SetLocalCS(papszFields[0]);
++        // assume that the Y axis isn't flipped
++        adfGeoTransform[2] *= -1.0;
++        adfGeoTransform[5] *= -1.0;
++        }
+ 
+     // Try to set datum from projection info line if we have a
+     // projected coordinate system without a GEOGCS.
diff --git a/SuperBuild/patches/GDAL/nmake_gdal_extra.opt.in b/SuperBuild/patches/GDAL/nmake_gdal_extra.opt.in
index 87f6bcd7b43280ad18f51db294000b68bcb1cbb8..72824d4104ed4ef7ae04e073ea4e264a9945be2d 100644
--- a/SuperBuild/patches/GDAL/nmake_gdal_extra.opt.in
+++ b/SuperBuild/patches/GDAL/nmake_gdal_extra.opt.in
@@ -11,60 +11,60 @@ JPEG_SUPPORTED = 1
 # This will enable 12bit libjpeg - use only with internal jpeg builds.
 #JPEG12_SUPPORTED = 1
 
-GDAL_HOME="@CMAKE_WIN_INSTALL_PREFIX@"
+GDAL_HOME="@SB_INSTALL_PREFIX_NATIVE@"
 
 #if using an external jpeg library uncomment the follwing lines
 JPEG_EXTERNAL_LIB = 1
-JPEGDIR = @CMAKE_WIN_INSTALL_PREFIX@\include
-JPEG_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\jpeg.lib
+JPEGDIR = @SB_INSTALL_PREFIX_NATIVE@\include
+JPEG_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\jpeg.lib
 
 #if using an external png library uncomment the follwing lines
 PNG_EXTERNAL_LIB = 1
-PNGDIR = @CMAKE_WIN_INSTALL_PREFIX@\include
-PNG_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\libpng.lib
+PNGDIR = @SB_INSTALL_PREFIX_NATIVE@\include
+PNG_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\libpng.lib
 
 # if using an external libtiff library
-TIFF_INC = -I@CMAKE_WIN_INSTALL_PREFIX@\include
-TIFF_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\libtiff_i.lib
+TIFF_INC = -I@SB_INSTALL_PREFIX_NATIVE@\include
+TIFF_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\tiff.lib
 # uncomment following line, if you have libtiff version >= 4.0 to enable BigTIFF support
 TIFF_OPTS= -DBIGTIFF_SUPPORT
 
 # if using an external libgeotiff library
-GEOTIFF_INC = -I@CMAKE_WIN_INSTALL_PREFIX@\include
-GEOTIFF_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\geotiff_i.lib
+GEOTIFF_INC = -I@SB_INSTALL_PREFIX_NATIVE@\include
+GEOTIFF_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\geotiff_i.lib
 
-EXPAT_DIR = @CMAKE_WIN_INSTALL_PREFIX@
+EXPAT_DIR = @SB_INSTALL_PREFIX_NATIVE@
 EXPAT_INCLUDE = -I$(EXPAT_DIR)\include
 EXPAT_LIB = $(EXPAT_DIR)\lib\expat.lib
 
 # SQLite Libraries
-SQLITE_INC=-I@CMAKE_WIN_INSTALL_PREFIX@\include
-SQLITE_LIB=@CMAKE_WIN_INSTALL_PREFIX@\lib\sqlite3.lib
+SQLITE_INC=-I@SB_INSTALL_PREFIX_NATIVE@\include
+SQLITE_LIB=@SB_INSTALL_PREFIX_NATIVE@\lib\sqlite3.lib
 # Uncomment following line if libsqlite3 has been compiled with SQLITE_HAS_COLUMN_METADATA=yes
 SQLITE_HAS_COLUMN_METADATA=yes
 
 # PROJ.4 stuff
-PROJ_INCLUDE = -I@CMAKE_WIN_INSTALL_PREFIX@\include
-PROJ_LIBRARY = @CMAKE_WIN_INSTALL_PREFIX@\lib\proj_i.lib
+PROJ_INCLUDE = -I@SB_INSTALL_PREFIX_NATIVE@\include
+PROJ_LIBRARY = @SB_INSTALL_PREFIX_NATIVE@\lib\proj.lib
 
 # Uncomment to use libcurl (DLL by default)
 # The cURL library is used for WCS, WMS, GeoJSON, SRS call importFromUrl(), WFS, GFT, CouchDB, /vsicurl/ etc.
-CURL_DIR=@CMAKE_WIN_INSTALL_PREFIX@
+CURL_DIR=@SB_INSTALL_PREFIX_NATIVE@
 CURL_INC = -I$(CURL_DIR)\include
 # Uncoment following line to use libcurl as dynamic library
-CURL_LIB = $(CURL_DIR)\lib\libcurl.lib wsock32.lib wldap32.lib winmm.lib
+CURL_LIB = $(CURL_DIR)\lib\libcurl_imp.lib wsock32.lib wldap32.lib winmm.lib
 
 # Uncomment for GEOS support (GEOS >= 3.1.0 required)
-GEOS_DIR=@CMAKE_WIN_INSTALL_PREFIX@
+GEOS_DIR=@SB_INSTALL_PREFIX_NATIVE@
 GEOS_CFLAGS = -I$(GEOS_DIR)\include -I$(GEOS_DIR)\include\geos -DHAVE_GEOS
-GEOS_LIB     = $(GEOS_DIR)\lib\geos_i.lib $(GEOS_DIR)\lib\geos_c_i.lib
+GEOS_LIB     = $(GEOS_DIR)\lib\geos.lib $(GEOS_DIR)\lib\geos_c.lib
 
 # Uncomment for OpenJpeg support
 HAVE_OPENJPEG = YES
 OPENJPEG_ENABLED = YES
 OPENJPEG_VERSION = 20100
-OPENJPEG_CFLAGS = -I@CMAKE_WIN_INSTALL_PREFIX@\include
-OPENJPEG_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\openjp2.lib
+OPENJPEG_CFLAGS = -I@SB_INSTALL_PREFIX_NATIVE@\include
+OPENJPEG_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\openjp2.lib
 
 
 ##################################################################
@@ -86,6 +86,10 @@ OPENJPEG_LIB = @CMAKE_WIN_INSTALL_PREFIX@\lib\openjp2.lib
 #		$(LIBKML_DIR)/third_party\zlib-1.2.3.win32/lib/minizip.lib \
 #		$(LIBKML_DIR)/third_party\zlib-1.2.3.win32/lib/zlib.lib
 
+#we use external zlib on windows
+ZLIB_EXTERNAL_LIB = 1
+ZLIB_INC = -I@SB_INSTALL_PREFIX_NATIVE@\include
+ZLIB_LIB = @SB_INSTALL_PREFIX_NATIVE@\lib\zlib.lib
 
 # Uncomment the following and update to enable NCSA HDF Release 4 support.
 #HDF4_PLUGIN = NO
diff --git a/SuperBuild/patches/GEOS/CMakeLists.txt b/SuperBuild/patches/GEOS/CMakeLists.txt
deleted file mode 100644
index a89103afaecae9441d1095ccab4d97bb094148eb..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/GEOS/CMakeLists.txt
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-cmake_minimum_required(VERSION 2.8)
-
-project(GEOS_SUPERBUILD)
-
-add_custom_target(build_with_nmake 
-ALL DEPENDS 
-COMMAND
-nmake /f ${GEOS_SB_SRC}/makefile.vc
-WORKING_DIRECTORY ${GEOS_SB_SRC}
-)
-
-install(FILES  ${GEOS_SB_SRC}/capi/geos_c.h DESTINATION ${CMAKE_INSTALL_PREFIX}/include)
-install(FILES  ${GEOS_SB_SRC}/include/geos.h DESTINATION ${CMAKE_INSTALL_PREFIX}/include)
-install(DIRECTORY ${GEOS_SB_SRC}/include/geos DESTINATION ${CMAKE_INSTALL_PREFIX}/include)
-install(FILES  ${GEOS_SB_SRC}/src/geos.dll DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
-install(FILES  ${GEOS_SB_SRC}/src/geos_c.dll DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
-install(FILES  ${GEOS_SB_SRC}/src/geos.lib DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
-install(FILES  ${GEOS_SB_SRC}/src/geos_i.lib DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
-install(FILES  ${GEOS_SB_SRC}/src/geos_c_i.lib DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
diff --git a/SuperBuild/patches/GEOS/geos-1-fixes-all.diff b/SuperBuild/patches/GEOS/geos-1-fixes-all.diff
index 4a516fe4697128ff5f81bbecc25568e62a46bceb..ca7663fffbf52a566124f57daf25d52e378d2da9 100644
--- a/SuperBuild/patches/GEOS/geos-1-fixes-all.diff
+++ b/SuperBuild/patches/GEOS/geos-1-fixes-all.diff
@@ -1,93 +1,22 @@
-diff -burN geos-3.5.0.orig/CMakeLists.txt geos-3.5.0/CMakeLists.txt
---- geos-3.5.0.orig/CMakeLists.txt	2016-09-02 11:02:28.833742143 +0200
-+++ geos-3.5.0/CMakeLists.txt	2016-09-02 11:05:05.897748116 +0200
-@@ -55,6 +55,9 @@
- # Check custom global options
- #################################################################################
- 
-+option(GEOS_BUILD_STATIC
-+  "Set to OFF|ON (default) to control build of GEOS tests package" OFF)
-+
- option(GEOS_ENABLE_TESTS
-   "Set to OFF|ON (default) to control build of GEOS tests package" ON)
- 
-@@ -317,18 +320,18 @@
- 
-   # Define "make check" as alias for "make test"
-   add_custom_target(check COMMAND ctest)
--
-+add_subdirectory(tests)
- endif()
- 
- #################################################################################
- # Configure subdirectories
- #################################################################################
--include(GenerateSourceGroups)
-+#include(GenerateSourceGroups)
- 
- add_subdirectory(include)
- add_subdirectory(src)
- add_subdirectory(capi)
--add_subdirectory(tests)
-+
- add_subdirectory(tools)
- 
- #################################################################################
-diff -burN geos-3.5.0.orig/include/CMakeLists.txt geos-3.5.0/include/CMakeLists.txt
---- geos-3.5.0.orig/include/CMakeLists.txt	2016-09-02 11:02:28.837742143 +0200
-+++ geos-3.5.0/include/CMakeLists.txt	2016-09-02 11:03:03.581743464 +0200
-@@ -54,4 +54,4 @@
- #################################################################################
- # Group source files for IDE source explorers (e.g. Visual Studio)
- #################################################################################
--GenerateSourceGroups(include)
-+#GenerateSourceGroups(include)
-diff -burN geos-3.5.0.orig/src/CMakeLists.txt geos-3.5.0/src/CMakeLists.txt
---- geos-3.5.0.orig/src/CMakeLists.txt	2016-09-02 11:02:28.869742144 +0200
-+++ geos-3.5.0/src/CMakeLists.txt	2016-09-02 11:05:14.621748447 +0200
-@@ -62,7 +62,18 @@
- else()
- 
-   add_library(geos SHARED ${geos_SOURCES} ${geos_ALL_HEADERS})
-+  if(GEOS_BUILD_STATIC)
-   add_library(geos-static STATIC ${geos_SOURCES} ${geos_ALL_HEADERS})
-+  set_target_properties(geos-static
-+    PROPERTIES
-+    OUTPUT_NAME "geos"
-+    PREFIX "lib"
-+    CLEAN_DIRECT_OUTPUT 1)
-+  install(TARGETS geos geos-static
-+    RUNTIME DESTINATION bin
-+    LIBRARY DESTINATION lib
-+    ARCHIVE DESTINATION lib)
-+endif()
- 
-   set_target_properties(geos
-     PROPERTIES
-@@ -70,11 +81,6 @@
-     VERSION ${VERSION}
-     CLEAN_DIRECT_OUTPUT 1)
- 
--  set_target_properties(geos-static
--    PROPERTIES
--    OUTPUT_NAME "geos"
--    PREFIX "lib"
--    CLEAN_DIRECT_OUTPUT 1)
- 
- endif()
- 
-@@ -90,7 +96,7 @@
- #################################################################################
- 
- if(NOT GEOS_ENABLE_MACOSX_FRAMEWORK)
--  install(TARGETS geos geos-static
-+  install(TARGETS geos
-     RUNTIME DESTINATION bin
-     LIBRARY DESTINATION lib
-     ARCHIVE DESTINATION lib)
-@@ -99,4 +105,4 @@
- #################################################################################
- # Group source files for IDE source explorers (e.g. Visual Studio)
- #################################################################################
--GenerateSourceGroups(src)
-+#GenerateSourceGroups(src)
+diff -burN geos-3.6.1.orig/cmake/modules/GenerateSourceGroups.cmake geos-3.6.1/cmake/modules/GenerateSourceGroups.cmake
+--- geos-3.6.1.orig/cmake/modules/GenerateSourceGroups.cmake	1970-01-01 01:00:00.000000000 +0100
++++ geos-3.6.1/cmake/modules/GenerateSourceGroups.cmake	2017-06-19 11:19:32.143054641 +0200
+@@ -0,0 +1,17 @@
++#
++# Macro generates tree of IDE source groups based on folders structure
++# Source: http://www.cmake.org/pipermail/cmake/2013-November/056332.html
++# 
++macro(GenerateSourceGroups curdir)
++  file(GLOB children RELATIVE ${PROJECT_SOURCE_DIR}/${curdir} ${PROJECT_SOURCE_DIR}/${curdir}/*)
++  foreach(child ${children})
++    if(IS_DIRECTORY ${PROJECT_SOURCE_DIR}/${curdir}/${child})
++      GenerateSourceGroups(${curdir}/${child})
++    else()
++      string(REPLACE "/" "\\" groupname ${curdir})
++      # I would like to call the src root folder in a different name, only in visual studio (not mandatory requirement)
++	  string(REPLACE "src" "Source Files" groupname ${groupname})
++      source_group(${groupname} FILES ${PROJECT_SOURCE_DIR}/${curdir}/${child})
++    endif()
++  endforeach()
++endmacro()
+\ Pas de fin de ligne à la fin du fichier
diff --git a/SuperBuild/patches/GEOS/nmake.opt b/SuperBuild/patches/GEOS/nmake.opt
deleted file mode 100644
index ca21bd252387c8b166343bc966871399a2b36abd..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/GEOS/nmake.opt
+++ /dev/null
@@ -1,250 +0,0 @@
-#
-# nmake.opt - main configuration file for NMAKE makefiles
-#
-!MESSAGE **********************************************************************
-!MESSAGE *** GEOS Build Configuration ***
-
-# TODO: Confirm as redundant and remove, nmake /P displays _NMAKE_VER anyway.
-#!INCLUDE <ntwin32.mak>
-
-###############################################################################
-# For convenience, user may put custom settings to private mynmake.opt
-# and use EXT_NMAKE_OPT option while calling nmake.exe, as follows:
-#
-# nmake -f makefile.vc EXT_NMAKE_OPT=mynmake.opt
-
-!IFDEF EXT_NMAKE_OPT
-!MESSAGE *** Setting EXT_NMAKE_OPT $(EXT_NMAKE_OPT)
-!INCLUDE $(EXT_NMAKE_OPT)
-!ENDIF
-
-###############################################################################
-# Set BUILD_DEBUG to YES if you want to make debug build
-# and to prepare not optimized binaries.
-
-!IFNDEF BUILD_DEBUG 
-BUILD_DEBUG = NO
-!ENDIF
-
-!MESSAGE *** Setting BUILD_DEBUG $(BUILD_DEBUG)
-
-###############################################################################
-# Set ENABLE_INLINE to YES if you want to make debug build
-# and to prepare not optimized binaries.
-
-!IFNDEF ENABLE_INLINE
-ENABLE_INLINE = NO
-!ENDIF
-
-!MESSAGE *** Setting ENABLE_INLINE $(ENABLE_INLINE)
-
-###############################################################################
-# Set BUILD_BATCH to YES if you want feed compiler with all
-# source .c and .cpp files in single batch.
-
-!IFNDEF BUILD_BATCH
-BUILD_BATCH = NO
-!ENDIF
-
-!MESSAGE *** Setting BUILD_BATCH $(BUILD_BATCH)
-
-###############################################################################
-# Set WIN64=YES if you are building for 64-bit windows (x64).
-# Alternatively, pass WIN64=YES as NMAKE command line argument.
-###############################################################################
-!IFNDEF WIN64
-WIN64 = NO
-!ENDIF
-
-!MESSAGE *** Setting WIN64 $(WIN64)
-
-###############################################################################
-# Derive version of Visual C++ being used from NMAKE if not specified
-#
-# WARNING:
-# If we should expect variety of NMAKE build versions, tests below may fail
-# and we will need to fall back to setting GEOS_MSVC as command line parameter.
-
-!IF "$(_NMAKE_VER)" == ""
-GEOS_MSVC = 4.0
-!ERROR *** Failed to determine version of Visual C++
-!ELSEIF "$(_NMAKE_VER)" == "162"
-GEOS_MSVC = 5.0
-!ERROR *** Detected Visual C++ 5.0 - NOT SUPPORTED
-!ELSEIF "$(_NMAKE_VER)" == "6.00.8168.0"
-GEOS_MSVC = 6.0
-GEOS_MSC = 1200
-!ERROR *** Detected Visual C++ 6.0 - NOT SUPPORTED
-!ELSEIF "$(_NMAKE_VER)" == "7.00.9466"
-GEOS_MSVC = 7.0
-GEOS_MSC = 1300
-!ELSEIF "$(_NMAKE_VER)" == "7.10.3077"
-GEOS_MSVC = 7.1
-GEOS_MSC = 1310
-!ELSEIF "$(_NMAKE_VER)" == "8.00.50727.42"
-GEOS_MSVC = 8.0
-GEOS_MSC = 1400
-!ELSEIF "$(_NMAKE_VER)" == "8.00.50727.762"
-GEOS_MSVC = 8.0
-GEOS_MSC = 1400
-!ELSEIF "$(_NMAKE_VER)" == "9.00.21022.08"
-GEOS_MSVC = 9.0
-GEOS_MSC = 1500
-!ELSEIF "$(_NMAKE_VER)" == "9.00.30729.01"
-GEOS_MSVC = 9.0
-GEOS_MSC = 1500
-!ELSEIF "$(_NMAKE_VER)" == "10.00.30128.01"
-GEOS_MSVC = 10.0
-GEOS_MSC = 1600
-!ELSEIF "$(_NMAKE_VER)" == "10.00.30319.01"
-GEOS_MSVC = 10.0
-GEOS_MSC = 1600
-!ELSEIF "$(_NMAKE_VER)" == "11.00.40825.2"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.50522.1"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.50727.1"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.51106.1"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.60315.1"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.60430.2"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.60521.0"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.60610.1"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "11.00.61030.0"
-GEOS_MSVC = 11.0
-GEOS_MSC = 1700
-!ELSEIF "$(_NMAKE_VER)" == "12.00.21005.1"
-GEOS_MSVC = 12.0
-GEOS_MSC = 1800
-!ELSEIF "$(_NMAKE_VER)" == "14.00.22816.0"
-GEOS_MSVC = 14.0
-GEOS_MSC = 1900
-!ELSEIF "$(_NMAKE_VER)" == "14.00.23026.0"
-GEOS_MSVC = 14.0
-GEOS_MSC = 1900
-!ELSEIF "$(_NMAKE_VER)" == "14.00.23918.0"
-GEOS_MSVC = 14.0
-GEOS_MSC = 1900
-!ELSEIF "$(_NMAKE_VER)" == "14.00.24210.0"
-GEOS_MSVC = 14.0
-GEOS_MSC = 1900
-!ELSE
-GEOS_MSVC = 0.0
-GEOS_MSC = 0
-!ENDIF
-
-!IF "$(GEOS_MSVC)" == "0.0" && "$(GEOS_MSC)" == "0"
-!MESSAGE *** Cannot determine Visual C++ version
-!ERROR *** Aborting make job
-!ELSE
-!MESSAGE *** Using Microsoft NMAKE version $(_NMAKE_VER)
-!MESSAGE *** Using Microsoft Visual C++ version $(GEOS_MSVC)
-!MESSAGE *** Using Microsoft C/C++ version $(GEOS_MSC)
-!ENDIF
-
-###############################################################################
-# Optional use of Visual Leak Detector (VLD) http://vld.codeplex.com/
-# Uncomment this line to use VLD in debug configuration only:
-#MSVC_VLD_DIR=$(EXTLIBDIR)\Source\vld\vld
-
-!IF "$(BUILD_DEBUG)" == "YES"
-!IFDEF MSVC_VLD_DIR
-MSVC_VLD_FLAGS=-DMSVC_USE_VLD=1 -I$(MSVC_VLD_DIR)\include
-!IFDEF WIN64
-MSVC_VLD_LIB=/LIBPATH:$(MSVC_VLD_DIR)/lib/Win64
-!ELSE
-MSVC_VLD_LIB=/LIBPATH:$(MSVC_VLD_DIR)/lib/Win32
-!ENDIF
-!ENDIF
-!ENDIF
-
-###############################################################################
-# Include directories
-
-GEOS_INCLUDE = -I..\include -I..\capi
-
-!MESSAGE *** Setting GEOS_INCLUDE $(GEOS_INCLUDE)
-!MESSAGE *** Setting INCLUDE $(INCLUDE)
-
-###############################################################################
-# Compilation flags for Release and Debug modes
-
-GEOS_CPPFLAGS = /D "NOMINMAX" /D "WIN32_LEAN_AND_MEAN" /D "NOGDI"
-GEOS_CPPFLAGS = $(GEOS_CPPFLAGS) /D "GEOS_DLL_EXPORT" $(MSVC_VLD_FLAGS)
-
-!IF "$(BUILD_DEBUG)" == "YES"
-BUILD_PREFIX=_d
-GEOS_CFLAGS = /nologo /MDd /GR /Od /W4 /Zi
-GEOS_CPPFLAGS = /D "DEBUG" /D "_DEBUG" $(GEOS_CPPFLAGS)
-!ELSE
-GEOS_CFLAGS = /nologo /MD /GR /O2 /W3
-GEOS_CPPFLAGS = /D "NDEBUG" $(GEOS_CPPFLAGS)
-!ENDIF
-
-# Compiler version specific flags
-!IF $(GEOS_MSC) >= 1400
-GEOS_CFLAGS = $(GEOS_CFLAGS) /EHs
-GEOS_CPPFLAGS = $(GEOS_CPPFLAGS) /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "_SCL_SECURE_NO_DEPRECATE"
-!ELSE
-GEOS_CFLAGS = $(GEOS_CFLAGS) /GX
-!ENDIF
-
-# For Visual C++ 9.0+ use multiple process build
-!IF "$(BUILD_BATCH)" == "YES"
-!IF $(GEOS_MSC) > 1400
-MPFLAGS = /MP
-!MESSAGE *** Setting /MP flag to number of effective processors
-!ENDIF
-!ENDIF
-
-!IF "$(ENABLE_INLINE)" == "YES"
-GEOS_CFLAGS = /D "GEOS_INLINE"
-!ENDIF
-
-!MESSAGE *** Using GEOS_CFLAGS $(GEOS_CFLAGS)
-!MESSAGE *** Using GEOS_CPPFLAGS $(GEOS_CPPFLAGS)
-
-CFLAGS=$(MPFLAGS) $(GEOS_CFLAGS) $(GEOS_CPPFLAGS) $(GEOS_INCLUDE)
-
-!MESSAGE *** Complete CFLAGS $(CFLAGS)
-
-###############################################################################
-# Output location
-
-LIBNAME = geos$(BUILD_PREFIX).lib
-DLLNAME = geos$(BUILD_PREFIX).dll
-SLIBNAME = geos_i$(BUILD_PREFIX).lib
-CDLLNAME = geos_c$(BUILD_PREFIX).dll
-CLIBNAME = geos_c_i$(BUILD_PREFIX).lib
-
-###############################################################################
-# Building toolset programs
-
-MAKE = nmake
-CC = cl
-RM = del
-CP = copy
-
-# Linker executable
-# - Dynamic-Linked Libraries
-# $(LINK) /dll
-# - Static Libraries (use of lib.exe wrapper is not portable, see VC++ Toolkit 2003)
-# $(LINK) /lib
-LINK = link.exe
-LINKER_FLAGS = $(MSVC_VLD_LIB)
-
-!MESSAGE **********************************************************************
-# EOF
diff --git a/SuperBuild/patches/GEOTIFF/geotiff-1-fix-rpath-macx.diff b/SuperBuild/patches/GEOTIFF/geotiff-1-fix-rpath-macx.diff
new file mode 100644
index 0000000000000000000000000000000000000000..64b0cfcc5278ebfe0e04afee03f083afc4cf8bc0
--- /dev/null
+++ b/SuperBuild/patches/GEOTIFF/geotiff-1-fix-rpath-macx.diff
@@ -0,0 +1,22 @@
+diff -burN libgeotiff-1.4.2.orig/CMakeLists.txt libgeotiff-1.4.2/CMakeLists.txt
+--- libgeotiff-1.4.2.orig/CMakeLists.txt	Tue Jul 25 17:16:02 2017
++++ libgeotiff-1.4.2/CMakeLists.txt	Tue Jul 25 17:16:40 2017
+@@ -451,12 +451,12 @@
+       VERSION ${LINK_VERSION}
+       SOVERSION ${LINK_SOVERSION}
+       CLEAN_DIRECT_OUTPUT 1 )
+-   if (APPLE)
+-      set_target_properties(
+-        ${GEOTIFF_LIBRARY_TARGET}
+-        PROPERTIES
+-        INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib")
+-   endif()
++   # if (APPLE)
++   #    set_target_properties(
++   #      ${GEOTIFF_LIBRARY_TARGET}
++   #      PROPERTIES
++   #      INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib")
++   # endif()
+ 
+ ELSE(UNIX)
+ # Default:
diff --git a/SuperBuild/patches/GEOTIFF/geotiff-fix-configure-for-macx.diff b/SuperBuild/patches/GEOTIFF/geotiff-fix-configure-for-macx.diff
deleted file mode 100755
index 32c001b68d59f51198d6264b5173ec282cd5e270..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/GEOTIFF/geotiff-fix-configure-for-macx.diff
+++ /dev/null
@@ -1,30 +0,0 @@
-diff -burN libgeotiff-1.4.1.orig/configure libgeotiff-1.4.1/configure
---- libgeotiff-1.4.1.orig/configure	2016-04-15 17:57:22.000000000 +0200
-+++ libgeotiff-1.4.1/configure	2016-04-19 09:33:34.000000000 +0200
-@@ -10079,9 +10079,9 @@
-   esac
-   if test "$_lt_dar_can_shared" = "yes"; then
-     output_verbose_link_cmd=func_echo_all
--    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-+    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \@rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-     module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
--    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-+    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \@rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-     module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
- 
-   else
-@@ -16101,7 +16101,7 @@
- 
-     PROJ_CONFIG="yes"
- 
--    elif test \( -f "$PROJ_HOME/lib/libproj.a" -o -f "$PROJ_HOME/lib/libproj.so" \) -a -f "$PROJ_HOME/include/proj_api.h"; then
-+    elif test \( -f "$PROJ_HOME/lib/libproj.a" -o -f "$PROJ_HOME/lib/libproj.so" -o -f "$PROJ_HOME/lib/libproj.dylib" \) -a -f "$PROJ_HOME/include/proj_api.h"; then
-     PROJ_LIB="-L$PROJ_HOME/lib -lproj"
-     PROJ_INC=$PROJ_HOME/include
- 
-@@ -21017,5 +21017,3 @@
- 
- 
- echo ""
--
--
diff --git a/SuperBuild/patches/GLFW/glfw-1-fixes-win.diff b/SuperBuild/patches/GLFW/glfw-1-fixes-all.diff
similarity index 100%
rename from SuperBuild/patches/GLFW/glfw-1-fixes-win.diff
rename to SuperBuild/patches/GLFW/glfw-1-fixes-all.diff
diff --git a/SuperBuild/patches/ITK/itk-2-itktestlib-all.diff b/SuperBuild/patches/ITK/itk-2-itktestlib-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..dc0b0cbdbb7e18c55a0490150cf92d938cb3ab59
--- /dev/null
+++ b/SuperBuild/patches/ITK/itk-2-itktestlib-all.diff
@@ -0,0 +1,35 @@
+diff -burN InsightToolkit-4.12.0.orig/Modules/ThirdParty/VNL/src/CMakeLists.txt InsightToolkit-4.12.0/Modules/ThirdParty/VNL/src/CMakeLists.txt
+--- InsightToolkit-4.12.0.orig/Modules/ThirdParty/VNL/src/CMakeLists.txt	2017-08-22 11:53:55.960938649 +0200
++++ InsightToolkit-4.12.0/Modules/ThirdParty/VNL/src/CMakeLists.txt	2017-08-22 11:56:07.289820954 +0200
+@@ -18,10 +18,14 @@
+ # Retrive the variable type to CACHE.
+ set(BUILD_EXAMPLES ${BUILD_EXAMPLES} CACHE BOOL "Build the examples from the ITK Software Guide." FORCE)
+ 
+-foreach(lib itkvcl itkv3p_netlib itktestlib itkvnl itkvnl_algo itknetlib)
++foreach(lib itkvcl itkv3p_netlib itkvnl itkvnl_algo itknetlib)
+   itk_module_target(${lib} NO_INSTALL)
+ endforeach()
+ 
++if(BUILD_TESTING)
++  itk_module_target(itktestlib NO_INSTALL)
++endif()
++
+ foreach(exe
+     netlib_integral_test
+     netlib_lbfgs_example
+diff -burN InsightToolkit-4.12.0.orig/Modules/ThirdParty/VNL/src/vxl/core/CMakeLists.txt InsightToolkit-4.12.0/Modules/ThirdParty/VNL/src/vxl/core/CMakeLists.txt
+--- InsightToolkit-4.12.0.orig/Modules/ThirdParty/VNL/src/vxl/core/CMakeLists.txt	2017-08-22 11:53:55.960938649 +0200
++++ InsightToolkit-4.12.0/Modules/ThirdParty/VNL/src/vxl/core/CMakeLists.txt	2017-08-22 11:56:56.410150930 +0200
+@@ -131,8 +131,10 @@
+   set(CORE_VIDEO_FOUND OFF CACHE INTERNAL "VXL core video libraries built")
+ endif ()
+ 
+-# common test executable
+-add_subdirectory(testlib)
++# common test executable if testing enabled
++if(BUILD_TESTING)
++  add_subdirectory(testlib)
++endif()
+ 
+ # Tests that check and output the vxl configuration
+ # NOTE: some external projects remove the tests directory (aka ITK)
diff --git a/SuperBuild/patches/OSSIM/ossim-5-compat_geos36-all.diff b/SuperBuild/patches/OSSIM/ossim-5-compat_geos36-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..53f7312b8cac596f909c9e2a36e33d278637d120
--- /dev/null
+++ b/SuperBuild/patches/OSSIM/ossim-5-compat_geos36-all.diff
@@ -0,0 +1,36 @@
+diff -burN OSSIM.orig/ossim/src/ossim/base/ossimPolyArea2d.cpp OSSIM/ossim/src/ossim/base/ossimPolyArea2d.cpp
+--- OSSIM.orig/ossim/src/ossim/base/ossimPolyArea2d.cpp	2017-07-04 15:16:30.659669941 +0200
++++ OSSIM/ossim/src/ossim/base/ossimPolyArea2d.cpp	2017-07-05 09:46:23.142041689 +0200
+@@ -28,19 +28,13 @@
+ #include <exception>
+ #include <vector>
+ 
+-class ossimGeometryFactoryWrapper : public ossimReferenced
++class ossimGeometryFactoryWrapper : public ossimReferenced, public geos::geom::GeometryFactory
+ {
+ public:
+    ossimGeometryFactoryWrapper()
+-      : m_geomFactory(0)
+-   {
+-      geos::geom::PrecisionModel *pm =
+-         new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING);
+-      m_geomFactory = new geos::geom::GeometryFactory(pm, -1); 
+-   }
+-   virtual ~ossimGeometryFactoryWrapper(){if(m_geomFactory) delete m_geomFactory;m_geomFactory=0;}
+-   
+-   geos::geom::GeometryFactory* m_geomFactory;
++      : geos::geom::GeometryFactory(new geos::geom::PrecisionModel(geos::geom::PrecisionModel::FLOATING),-1)
++    {}
++   virtual ~ossimGeometryFactoryWrapper(){}
+ };
+ 
+ class OssimPolyArea2dPrivate
+@@ -55,7 +49,7 @@
+    void deleteGeometry() { if(m_geometry) { delete m_geometry; m_geometry = 0; }}
+    void setGeometry(const ossimPolygon& polygon, const vector<ossimPolygon>& holes = vector<ossimPolygon>());
+    void setGeometry(GeometryPtr geom){deleteGeometry();m_geometry=geom;}
+-   geos::geom::GeometryFactory* geomFactory(){{return m_globalFactory.valid()?m_globalFactory->m_geomFactory:0;}}
++   geos::geom::GeometryFactory* geomFactory(){{return m_globalFactory.valid()?m_globalFactory.get():0;}}
+    GeometryPtr m_geometry;
+    static ossimRefPtr<ossimGeometryFactoryWrapper> m_globalFactory; 
+ };
diff --git a/SuperBuild/patches/PROJ/proj-1-cmakefixes-all.diff b/SuperBuild/patches/PROJ/proj-1-cmakefixes-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..a95c58fbfe34ecdfd12073c1132f9a68811c1f6e
--- /dev/null
+++ b/SuperBuild/patches/PROJ/proj-1-cmakefixes-all.diff
@@ -0,0 +1,34 @@
+diff -burN proj-4.9.3.orig/CMakeLists.txt proj-4.9.3/CMakeLists.txt
+--- proj-4.9.3.orig/CMakeLists.txt	2016-08-29 20:47:58.000000000 +0200
++++ proj-4.9.3/CMakeLists.txt	2017-07-26 12:34:26.071721900 +0200
+@@ -34,6 +34,7 @@
+ proj_version(MAJOR 4 MINOR 9 PATCH 3)
+ set(PROJ_API_VERSION "12")
+ set(PROJ_BUILD_VERSION "12.0.0")
++option(VERSIONED_OUTPUT "suffix version into output name of binaries." ON)
+ 
+ #################################################################################
+ # Build features and variants
+diff -burN proj-4.9.3.orig/src/lib_proj.cmake proj-4.9.3/src/lib_proj.cmake
+--- proj-4.9.3.orig/src/lib_proj.cmake	2016-08-29 20:47:58.000000000 +0200
++++ proj-4.9.3/src/lib_proj.cmake	2017-07-26 12:28:51.098731200 +0200
+@@ -274,11 +274,19 @@
+ 
+ 
+ if(WIN32)
++if(VERSIONED_OUTPUT)
+   set_target_properties(${PROJ_CORE_TARGET}
+     PROPERTIES
+     VERSION "${${PROJECT_INTERN_NAME}_BUILD_VERSION}"
+     OUTPUT_NAME "${PROJ_CORE_TARGET_OUTPUT_NAME}"
+     CLEAN_DIRECT_OUTPUT 1)
++    else()
++  set_target_properties(${PROJ_CORE_TARGET}
++    PROPERTIES
++    VERSION "${${PROJECT_INTERN_NAME}_BUILD_VERSION}"
++    CLEAN_DIRECT_OUTPUT 1)
++    endif() #VERSIONED_OUTPUT
++ 
+ elseif(BUILD_FRAMEWORKS_AND_BUNDLE)
+   set_target_properties(${PROJ_CORE_TARGET}
+     PROPERTIES
diff --git a/SuperBuild/patches/PROJ/proj-fix-rpath-for-macx.diff b/SuperBuild/patches/PROJ/proj-fix-rpath-for-macx.diff
deleted file mode 100644
index 1ab4acdab9cde44e6aef0930affcdcd525c7cee6..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/PROJ/proj-fix-rpath-for-macx.diff
+++ /dev/null
@@ -1,20 +0,0 @@
-diff -burN proj-4.8.0.orig/configure proj-4.8.0/configure
---- proj-4.8.0.orig/configure	2016-04-18 17:31:49.000000000 +0200
-+++ proj-4.8.0/configure	2016-04-18 17:32:47.000000000 +0200
-@@ -9044,9 +9044,9 @@
-   esac
-   if test "$_lt_dar_can_shared" = "yes"; then
-     output_verbose_link_cmd=func_echo_all
--    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-+    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \@rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-     module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
--    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-+    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \@rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-     module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
- 
-   else
-@@ -16296,4 +16296,3 @@
-   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
- $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
- fi
--
diff --git a/SuperBuild/patches/QT4/configure_qt4.bat.in b/SuperBuild/patches/QT4/configure_qt4.bat.in
index ce92ad480dce9d657b13a155cf2296568ddebc68..8ce395fc784d0c9da6743636f3f9e35713bc41d7 100755
--- a/SuperBuild/patches/QT4/configure_qt4.bat.in
+++ b/SuperBuild/patches/QT4/configure_qt4.bat.in
@@ -4,7 +4,7 @@ set SB_SAVE_LIB=%LIB%
 set INCLUDE=%INCLUDE%;@QT4_INCLUDE_PREFIX_NATIVE@;@QT4_INCLUDE_PREFIX_NATIVE@\freetype2
 set LIB=%LIB%;@QT4_LIB_PREFIX_NATIVE@
 
-@QT4_CONFIGURE_SCRIPT@ -prefix @QT4_INSTALL_PREFIX_NATIVE@ -L @QT4_LIB_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@\freetype2 -opensource -confirm-license -release -shared -nomake demos -nomake examples -nomake tools -no-phonon-backend -no-phonon -no-script -no-scripttools -no-multimedia -no-audio-backend -no-webkit -no-declarative  -no-qt3support -no-xmlpatterns -system-sqlite -qt-sql-sqlite -plugin-sql-sqlite -no-openssl -no-libtiff -no-libmng -system-libpng -system-libjpeg  -system-zlib @QT4_SB_CONFIG@
+@QT4_CONFIGURE_SCRIPT@ -prefix @QT4_INSTALL_PREFIX_NATIVE@ -L @QT4_LIB_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@\freetype2 -opensource -confirm-license -release -shared -nomake demos -nomake examples -nomake tools -no-phonon-backend -no-phonon -no-script -no-scripttools -no-multimedia -no-audio-backend -no-webkit -no-declarative -no-accessibility -no-qt3support -no-xmlpatterns -no-sql-sqlite -no-openssl -no-libtiff -no-libmng -system-libpng -system-libjpeg  -system-zlib @QT4_SB_CONFIG@
 
 set INCLUDE=%SB_SAVE_INCLUDE%
 set LIB=%SB_SAVE_LIB%
diff --git a/SuperBuild/patches/QT4/configure_qt4.sh.in b/SuperBuild/patches/QT4/configure_qt4.sh.in
index 8f8a01a3d3b41bf303a9cbd0deccbd9ac44fff72..ee254d3f306fa713ec12809ae7c3616485d31497 100755
--- a/SuperBuild/patches/QT4/configure_qt4.sh.in
+++ b/SuperBuild/patches/QT4/configure_qt4.sh.in
@@ -1 +1 @@
-@QT4_CONFIGURE_SCRIPT@ -prefix @QT4_INSTALL_PREFIX_NATIVE@ -L @QT4_LIB_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@/freetype2 -opensource -confirm-license -release -shared -nomake demos -nomake examples -nomake tools -no-phonon-backend -no-phonon -no-script -no-scripttools -no-multimedia -no-audio-backend -no-webkit -no-declarative  -no-qt3support -no-xmlpatterns -system-sqlite -qt-sql-sqlite -plugin-sql-sqlite -no-openssl -no-libtiff -no-libmng -system-libpng -system-libjpeg  -system-zlib @QT4_SB_CONFIG@
+@QT4_CONFIGURE_SCRIPT@ -prefix @QT4_INSTALL_PREFIX_NATIVE@ -L @QT4_LIB_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@ -I @QT4_INCLUDE_PREFIX_NATIVE@/freetype2 -opensource -confirm-license -release -shared -nomake demos -nomake examples -nomake tools -no-phonon-backend -no-phonon -no-script -no-scripttools -no-multimedia -no-audio-backend -no-webkit -no-declarative -no-accessibility -no-qt3support -no-xmlpatterns -no-sql-sqlite -no-openssl -no-libtiff -no-libmng -system-libpng -system-libjpeg  -system-zlib -no-dbus @QT4_SB_CONFIG@
diff --git a/SuperBuild/patches/QT4/qjpeghandler.pri b/SuperBuild/patches/QT4/qjpeghandler.pri
deleted file mode 100644
index 8b11ad8df81ab5ca5be7fd8ec847be4ccfebcc0c..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/QT4/qjpeghandler.pri
+++ /dev/null
@@ -1,10 +0,0 @@
-# common to plugin and built-in forms
-INCLUDEPATH *= $$PWD
-HEADERS += $$PWD/qjpeghandler_p.h
-SOURCES += $$PWD/qjpeghandler.cpp
-contains(QT_CONFIG, system-jpeg) {
-    if(unix|win32-g++*): LIBS += -ljpeg
-    else:win32:          LIBS += jpeg.lib
-} else {
-    include($$PWD/../../3rdparty/libjpeg.pri)
-}
diff --git a/SuperBuild/patches/QT4/qt4-1-minbuild-all.diff b/SuperBuild/patches/QT4/qt4-1-minbuild-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..ae4bdcfd5066945d1738234ee62900b04d02d1c4
--- /dev/null
+++ b/SuperBuild/patches/QT4/qt4-1-minbuild-all.diff
@@ -0,0 +1,147 @@
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/config.tests/unix/freetype/freetype.pri qt-everywhere-opensource-src-4.8.7/config.tests/unix/freetype/freetype.pri
+--- qt-everywhere-opensource-src-4.8.7.orig/config.tests/unix/freetype/freetype.pri	2017-08-18 10:54:50.327911982 +0200
++++ qt-everywhere-opensource-src-4.8.7/config.tests/unix/freetype/freetype.pri	2017-08-23 15:20:17.132268013 +0200
+@@ -1,5 +1,5 @@
+ !cross_compile {
+-    TRY_INCLUDEPATHS = /include /usr/include $$QMAKE_INCDIR $$QMAKE_INCDIR_X11 $$INCLUDEPATH
++    TRY_INCLUDEPATHS = $$INCLUDEPATH $$QMAKE_INCDIR $$QMAKE_INCDIR_X11
+     # LSB doesn't allow using headers from /include or /usr/include
+     linux-lsb-g++:TRY_INCLUDEPATHS = $$QMAKE_INCDIR $$QMAKE_INCDIR_X11 $$INCLUDEPATH
+     for(p, TRY_INCLUDEPATHS) {
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/projects.pro qt-everywhere-opensource-src-4.8.7/projects.pro
+--- qt-everywhere-opensource-src-4.8.7.orig/projects.pro	2017-08-18 10:54:46.519887277 +0200
++++ qt-everywhere-opensource-src-4.8.7/projects.pro	2017-08-23 15:20:03.224174152 +0200
+@@ -11,7 +11,7 @@
+     symbian|integrity {
+        QT_BUILD_PARTS = libs tools examples demos
+     } else {
+-       QT_BUILD_PARTS = libs tools examples demos docs translations
++       QT_BUILD_PARTS = libs tools examples demos translations
+     }
+ } else { #make sure the order makes sense
+    contains(QT_BUILD_PARTS, translations) {
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/gui/image/qjpeghandler.pri qt-everywhere-opensource-src-4.8.7/src/gui/image/qjpeghandler.pri
+--- qt-everywhere-opensource-src-4.8.7.orig/src/gui/image/qjpeghandler.pri	2017-08-18 10:54:45.407880063 +0200
++++ qt-everywhere-opensource-src-4.8.7/src/gui/image/qjpeghandler.pri	2017-08-23 15:20:03.292174610 +0200
+@@ -4,7 +4,7 @@
+ SOURCES += $$PWD/qjpeghandler.cpp
+ contains(QT_CONFIG, system-jpeg) {
+     if(unix|win32-g++*): LIBS += -ljpeg
+-    else:win32:          LIBS += libjpeg.lib
++    else:win32:          LIBS += jpeg.lib
+ } else {
+     include($$PWD/../../3rdparty/libjpeg.pri)
+ }
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/plugins/graphicssystems/graphicssystems.pro qt-everywhere-opensource-src-4.8.7/src/plugins/graphicssystems/graphicssystems.pro
+--- qt-everywhere-opensource-src-4.8.7.orig/src/plugins/graphicssystems/graphicssystems.pro	2017-08-18 10:54:45.583881205 +0200
++++ qt-everywhere-opensource-src-4.8.7/src/plugins/graphicssystems/graphicssystems.pro	2017-08-23 15:20:03.292174610 +0200
+@@ -1,5 +1,4 @@
+ TEMPLATE = subdirs
+-SUBDIRS += trace
+ !wince*:contains(QT_CONFIG, opengl):SUBDIRS += opengl
+ contains(QT_CONFIG, openvg):contains(QT_CONFIG, egl) {
+     SUBDIRS += openvg
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/plugins/imageformats/imageformats.pro qt-everywhere-opensource-src-4.8.7/src/plugins/imageformats/imageformats.pro
+--- qt-everywhere-opensource-src-4.8.7.orig/src/plugins/imageformats/imageformats.pro	2017-08-18 10:54:45.583881205 +0200
++++ qt-everywhere-opensource-src-4.8.7/src/plugins/imageformats/imageformats.pro	2017-08-23 15:20:03.292174610 +0200
+@@ -3,7 +3,7 @@
+ !contains(QT_CONFIG, no-jpeg):!contains(QT_CONFIG, jpeg):SUBDIRS += jpeg
+ !contains(QT_CONFIG, no-gif):!contains(QT_CONFIG, gif):SUBDIRS += gif
+ !contains(QT_CONFIG, no-mng):!contains(QT_CONFIG, mng):SUBDIRS += mng
+-contains(QT_CONFIG, svg):SUBDIRS += svg
++# contains(QT_CONFIG, svg):SUBDIRS += svg
+ !contains(QT_CONFIG, no-tiff):!contains(QT_CONFIG, tiff):SUBDIRS += tiff
+ !contains(QT_CONFIG, no-ico):SUBDIRS += ico
+ !contains(QT_CONFIG, no-tga):SUBDIRS += tga
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/plugins/plugins.pro qt-everywhere-opensource-src-4.8.7/src/plugins/plugins.pro
+--- qt-everywhere-opensource-src-4.8.7.orig/src/plugins/plugins.pro	2017-08-18 10:54:45.599881309 +0200
++++ qt-everywhere-opensource-src-4.8.7/src/plugins/plugins.pro	2017-08-23 15:20:03.292174610 +0200
+@@ -1,16 +1,16 @@
+ TEMPLATE = subdirs
+ 
+-SUBDIRS	*= sqldrivers script bearer
+-unix:!symbian {
+-        contains(QT_CONFIG,iconv)|contains(QT_CONFIG,gnu-libiconv)|contains(QT_CONFIG,sun-libiconv):SUBDIRS *= codecs
+-} else {
+-        SUBDIRS *= codecs
+-}
+-!contains(QT_CONFIG, no-gui): SUBDIRS *= imageformats iconengines
++# SUBDIRS	*= sqldrivers
++# unix:!symbian {
++#        contains(QT_CONFIG,iconv)|contains(QT_CONFIG,gnu-libiconv)|contains(QT_CONFIG,sun-libiconv):SUBDIRS *= codecs
++# } else {
++#         SUBDIRS *= codecs
++# }
++!contains(QT_CONFIG, no-gui): SUBDIRS *= imageformats
+ !embedded:!qpa:!contains(QT_CONFIG, no-gui):SUBDIRS *= graphicssystems
+ embedded:SUBDIRS *=  gfxdrivers decorations mousedrivers kbddrivers
+-!win32:!embedded:!mac:!symbian:!contains(QT_CONFIG, no-gui):SUBDIRS *= inputmethods
+-!symbian:!contains(QT_CONFIG, no-gui):SUBDIRS += accessible
++# !win32:!embedded:!mac:!symbian:!contains(QT_CONFIG, no-gui):SUBDIRS *= inputmethods
++# !symbian:!contains(QT_CONFIG, no-gui):SUBDIRS += accessible
+ contains(QT_CONFIG, phonon): SUBDIRS *= phonon
+ qpa:SUBDIRS += platforms
+ contains(QT_CONFIG, declarative): SUBDIRS *= qmltooling
+diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/src.pro qt-everywhere-opensource-src-4.8.7/src/src.pro
+--- qt-everywhere-opensource-src-4.8.7.orig/src/src.pro	2017-08-18 10:54:46.487887069 +0200
++++ qt-everywhere-opensource-src-4.8.7/src/src.pro	2017-08-23 15:20:03.292174610 +0200
+@@ -4,7 +4,7 @@
+ unset(SRC_SUBDIRS)
+ win32:SRC_SUBDIRS += src_winmain
+ symbian:SRC_SUBDIRS += src_s60main
+-SRC_SUBDIRS += src_corelib src_xml src_network src_sql src_testlib
++SRC_SUBDIRS += src_corelib
+ nacl: SRC_SUBDIRS -= src_network src_testlib
+ !symbian:contains(QT_CONFIG, dbus):SRC_SUBDIRS += src_dbus
+ !contains(QT_CONFIG, no-gui): SRC_SUBDIRS += src_gui
+@@ -18,7 +18,7 @@
+ contains(QT_CONFIG, xmlpatterns): SRC_SUBDIRS += src_xmlpatterns
+ contains(QT_CONFIG, phonon): SRC_SUBDIRS += src_phonon
+ contains(QT_CONFIG, multimedia): SRC_SUBDIRS += src_multimedia
+-contains(QT_CONFIG, svg): SRC_SUBDIRS += src_svg
++# contains(QT_CONFIG, svg): SRC_SUBDIRS += src_svg
+ contains(QT_CONFIG, script): SRC_SUBDIRS += src_script
+ contains(QT_CONFIG, declarative): SRC_SUBDIRS += src_declarative
+ contains(QT_CONFIG, webkit)  {
+@@ -52,8 +52,8 @@
+ src_sql.target = sub-sql
+ src_network.subdir = $$QT_SOURCE_TREE/src/network
+ src_network.target = sub-network
+-src_svg.subdir = $$QT_SOURCE_TREE/src/svg
+-src_svg.target = sub-svg
++# src_svg.subdir = $$QT_SOURCE_TREE/src/svg
++# src_svg.target = sub-svg
+ src_script.subdir = $$QT_SOURCE_TREE/src/script
+ src_script.target = sub-script
+ src_scripttools.subdir = $$QT_SOURCE_TREE/src/scripttools
+@@ -89,7 +89,7 @@
+    src_xml.depends = src_corelib
+    src_xmlpatterns.depends = src_corelib src_network
+    src_dbus.depends = src_corelib src_xml
+-   src_svg.depends = src_corelib src_gui
++   # src_svg.depends = src_corelib src_gui
+    src_script.depends = src_corelib
+    src_scripttools.depends = src_script src_gui src_network
+    src_network.depends = src_corelib
+@@ -105,7 +105,7 @@
+    contains(QT_CONFIG, opengl):src_multimedia.depends += src_opengl
+    src_activeqt.depends = src_tools_idc src_gui
+    src_declarative.depends = src_gui src_script src_network
+-   src_plugins.depends = src_gui src_sql src_svg
++   src_plugins.depends = src_gui
+    contains(QT_CONFIG, multimedia):src_plugins.depends += src_multimedia
+    contains(QT_CONFIG, declarative):src_plugins.depends += src_declarative
+    src_s60installs.depends = $$TOOLS_SUBDIRS $$SRC_SUBDIRS
+@@ -130,9 +130,9 @@
+       src_declarative.depends += src_xmlpatterns
+       src_webkit.depends += src_xmlpatterns
+    }
+-   contains(QT_CONFIG, svg) {
+-      src_declarative.depends += src_svg
+-   }
++   # contains(QT_CONFIG, svg) {
++   # src_declarative.depends += src_svg
++   # }
+ }
+ 
+ 
diff --git a/SuperBuild/patches/QT4/qt4-1-skip-qtnetwork-module-all.diff b/SuperBuild/patches/QT4/qt4-1-skip-qtnetwork-module-all.diff
deleted file mode 100755
index 215f87cecafdb32d103dfa8cd7f9b5bd3de03734..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/QT4/qt4-1-skip-qtnetwork-module-all.diff
+++ /dev/null
@@ -1,32 +0,0 @@
-diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/plugins/graphicssystems/graphicssystems.pro qt-everywhere-opensource-src-4.8.7/src/plugins/graphicssystems/graphicssystems.pro
---- qt-everywhere-opensource-src-4.8.7.orig/src/plugins/graphicssystems/graphicssystems.pro	2016-07-06 10:15:46.000000000 +0200
-+++ qt-everywhere-opensource-src-4.8.7/src/plugins/graphicssystems/graphicssystems.pro	2016-07-06 14:09:07.000000000 +0200
-@@ -1,5 +1,4 @@
- TEMPLATE = subdirs
--SUBDIRS += trace
- !wince*:contains(QT_CONFIG, opengl):SUBDIRS += opengl
- contains(QT_CONFIG, openvg):contains(QT_CONFIG, egl) {
-     SUBDIRS += openvg
-diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/plugins/plugins.pro qt-everywhere-opensource-src-4.8.7/src/plugins/plugins.pro
---- qt-everywhere-opensource-src-4.8.7.orig/src/plugins/plugins.pro	2016-07-06 10:15:46.000000000 +0200
-+++ qt-everywhere-opensource-src-4.8.7/src/plugins/plugins.pro	2016-07-06 12:58:14.000000000 +0200
-@@ -1,6 +1,6 @@
- TEMPLATE = subdirs
- 
--SUBDIRS	*= sqldrivers script bearer
-+SUBDIRS	*= sqldrivers
- unix:!symbian {
-         contains(QT_CONFIG,iconv)|contains(QT_CONFIG,gnu-libiconv)|contains(QT_CONFIG,sun-libiconv):SUBDIRS *= codecs
- } else {
-diff -burN qt-everywhere-opensource-src-4.8.7.orig/src/src.pro qt-everywhere-opensource-src-4.8.7/src/src.pro
---- qt-everywhere-opensource-src-4.8.7.orig/src/src.pro	2016-07-06 10:15:47.000000000 +0200
-+++ qt-everywhere-opensource-src-4.8.7/src/src.pro	2016-07-06 10:18:44.000000000 +0200
-@@ -4,7 +4,7 @@
- unset(SRC_SUBDIRS)
- win32:SRC_SUBDIRS += src_winmain
- symbian:SRC_SUBDIRS += src_s60main
--SRC_SUBDIRS += src_corelib src_xml src_network src_sql src_testlib
-+SRC_SUBDIRS += src_corelib src_xml src_sql
- nacl: SRC_SUBDIRS -= src_network src_testlib
- !symbian:contains(QT_CONFIG, dbus):SRC_SUBDIRS += src_dbus
- !contains(QT_CONFIG, no-gui): SRC_SUBDIRS += src_gui
diff --git a/SuperBuild/patches/README.md b/SuperBuild/patches/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..f912b067aafc01467b1d278f7005259492412261
--- /dev/null
+++ b/SuperBuild/patches/README.md
@@ -0,0 +1,20 @@
+## Synopsis
+
+Illustrates how to include a patch to the superbuild sources. This patch will be apply before the compilation of the external project.
+
+## Example
+
+Here is how to make a patch for superbuild. The example is here used libgeos but it can be done for any external projects in the OTB Superbuild. 
+
+- cd /tmp
+- wget http://download.osgeo.org/geos/geos-3.6.1.tar.bz2
+- tar xjf geos-3.6.1.tar.bz2
+- cp -r geos-3.6.1 geos-3.6.1.orig
+
+(make changes to geos-3.6.1)
+
+And prepare diff between two directories
+
+- diff -burN geos-3.6.1.orig geos-3.6.1 > geos-1-fixes-all.diff
+
+diff file naming is <project>-<number for applying in correct order>-<all/win/linux/macx>.diff
diff --git a/SuperBuild/patches/SHARK/shark-1-disable-hdf5-all.diff b/SuperBuild/patches/SHARK/shark-1-disable-hdf5-all.diff
new file mode 100755
index 0000000000000000000000000000000000000000..e7fba1953d4d93c79ac864fc175ad957d97774e6
--- /dev/null
+++ b/SuperBuild/patches/SHARK/shark-1-disable-hdf5-all.diff
@@ -0,0 +1,21 @@
+diff -burN Shark.orig/CMakeLists.txt Shark/CMakeLists.txt
+--- Shark.orig/CMakeLists.txt	2016-09-02 17:04:54.000000000 +0200
++++ Shark/CMakeLists.txt	2017-07-31 16:41:18.563473752 +0200
+@@ -194,6 +194,8 @@
+ #####################################################################
+ #           HDF5 configuration
+ #####################################################################
++option(ENABLE_HDF5 "Use HDF5" ON)
++if(ENABLE_HDF5)
+ find_package(HDF5 COMPONENTS C CXX HL QUIET)
+ mark_as_advanced(HDF5_DIR)
+ if(HDF5_FOUND)
+@@ -215,7 +217,7 @@
+ else()
+ 	message(STATUS "HDF5 not found, skip")
+ endif()
+-
++endif() #ENABLE_HDF5
+ #####################################################################
+ #           ATLAS configuration
+ #####################################################################
diff --git a/SuperBuild/patches/SHARK/shark-1-disable-hdf5-linux.diff b/SuperBuild/patches/SHARK/shark-1-disable-hdf5-linux.diff
deleted file mode 100644
index d0b3df4d7f8355a0da6f4a26ff4d0c4187bca1df..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/SHARK/shark-1-disable-hdf5-linux.diff
+++ /dev/null
@@ -1,258 +0,0 @@
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index df8be65..c6c3020 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -191,29 +191,32 @@ endif()
- #####################################################################
- #           HDF5 configuration
- #####################################################################
--find_package(HDF5 COMPONENTS C CXX HL QUIET)
--mark_as_advanced(HDF5_DIR)
--if(HDF5_FOUND)
--	if(HDF5_C_COMPILER_EXECUTABLE AND HDF5_CXX_COMPILER_EXECUTABLE)
--		message(STATUS "Checking HDF5 installation: HDF5 installation seems ok.")
--		include_directories( ${HDF5_INCLUDE_DIR} )
--		link_directories( ${HDF5_LIBRARY_DIR} )
--		list(APPEND LINK_LIBRARIES ${HDF5_LIBRARIES})
--	else()
--		message(STATUS "Checking HDF5 installation:HDF5 package might be broken.")
--		if(NOT( HDF5_C_COMPILER_EXECUTABLE))
--			message(STATUS "  C Compiler Extension not found.")
--		endif()
--		if(NOT( HDF5_CXX_COMPILER_EXECUTABLE))
--			message(STATUS "  CXX Compiler Extension not found.")
--		endif()
--			message(STATUS "Disabling HDF5.")
--		unset( HDF5_FOUND )
--	endif()
--else()
--	message(STATUS "HDF5 not found, skip")
-+option(ENABLE_HDF5 "Use HDF5" ON)
-+
-+if(ENABLE_HDF5)
-+  find_package(HDF5 COMPONENTS C CXX HL QUIET)
-+  mark_as_advanced(HDF5_DIR)
-+  if(HDF5_FOUND)
-+    if(HDF5_C_COMPILER_EXECUTABLE AND HDF5_CXX_COMPILER_EXECUTABLE)
-+      message(STATUS "Checking HDF5 installation: HDF5 installation seems ok.")
-+      include_directories( ${HDF5_INCLUDE_DIR} )
-+      link_directories( ${HDF5_LIBRARY_DIR} )
-+      list(APPEND LINK_LIBRARIES ${HDF5_LIBRARIES})
-+    else()
-+      message(STATUS "Checking HDF5 installation:HDF5 package might be broken.")
-+      if(NOT( HDF5_C_COMPILER_EXECUTABLE))
-+        message(STATUS "  C Compiler Extension not found.")
-+      endif()
-+      if(NOT( HDF5_CXX_COMPILER_EXECUTABLE))
-+        message(STATUS "  CXX Compiler Extension not found.")
-+      endif()
-+      message(STATUS "Disabling HDF5.")
-+      unset( HDF5_FOUND )
-+    endif()
-+  else()
-+    message(STATUS "HDF5 not found, skip")
-+  endif()
- endif()
--
- #####################################################################
- #           ATLAS configuration
- #####################################################################
-@@ -222,104 +225,104 @@ endif()
- option( ENABLE_CBLAS "Use Installed Linear Algebra Library" ON )
- 
- if( ENABLE_CBLAS )
--	set(CBLAS_VENDOR FALSE)
--	if( APPLE )
--		set(CBLAS_VENDOR "Accelerate")
--		set(CBLAS_INCLUDES "")
--		set(CBLAS_LIBRARIES "-framework Accelerate" )
--	else()
--		#todo: do a propper vendor check
--		find_library(OPENBLAS_LIBRARY openblas
--			HINTS ${CBLAS_ROOT}/lib /opt/local/lib
--		)
--		find_library(CBLAS_LIBRARY cblas
--			HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
--		)
--		find_library(CLAPACK_LIBRARY lapack
--			HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
--		)
--		find_library(ATLAS_LIBRARY atlas
--			HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
--		)
--		mark_as_advanced(
--			OPENBLAS_LIBRARY
--			CBLAS_LIBRARY
--			CLAPACK_LIBRARY
--			ATLAS_LIBRARY
--		)
--		#find the cblas.h include path
--		if(CBLAS_LIBRARY )
--			get_filename_component(CBLAS_LIB_PATH ${CBLAS_LIBRARY} PATH )
--		elseif( OPENBLAS_LIBRARY)	
--			get_filename_component(CBLAS_LIB_PATH ${OPENBLAS_LIBRARY} PATH )
--		endif()
--		if(CBLAS_LIB_PATH)
--			find_file(CBLAS_INCLUDES cblas.h 
--				PATHS ${CBLAS_LIB_PATH} ${CBLAS_LIB_PATH}/../include
--			)
--			get_filename_component(CBLAS_INCLUDES ${CBLAS_INCLUDES} PATH )
--		endif()
--		if(ATLAS_LIBRARY)
--			get_filename_component(ATLAS_LIBRARY_PATH ${ATLAS_LIBRARY} PATH )
--			find_file(CLAPACK_INCLUDES clapack.h 
--				PATHS
--				${ATLAS_LIBRARY_PATH} 
--				${ATLAS_LIBRARY_PATH}/../include
--				${ATLAS_LIBRARY_PATH}/../include/atlas
--				${ATLAS_LIBRARY_PATH}/../../include/atlas
--			)
--			get_filename_component(CLAPACK_INCLUDES ${CLAPACK_INCLUDES} PATH )
--			set(CBLAS_INCLUDES ${CBLAS_INCLUDES} ${CLAPACK_INCLUDES})
--		endif()
--
--		if( OPENBLAS_LIBRARY AND CBLAS_INCLUDES)
--			set(CBLAS_VENDOR "OpenBLAS")
--			set(CBLAS_LIBRARIES ${OPENBLAS_LIBRARY})
--		elseif( CBLAS_LIBRARY AND CLAPACK_LIBRARY AND ATLAS_LIBRARY AND CBLAS_INCLUDES)
--			set(CBLAS_VENDOR "ATLAS")
--			set(CBLAS_LIBRARIES ${CLAPACK_LIBRARY} ${CBLAS_LIBRARY} ${ATLAS_LIBRARY})
--		elseif( CBLAS_LIBRARY AND CBLAS_INCLUDES)
--			#check that we can compile a basic program with the libraries we have found
--			#vendor versions might come with additional libraries which would be bad.
--			try_compile(CBLAS_COMPILE 
--				"${PROJECT_BINARY_DIR}/cBlasCheck"
--				"${CMAKE_SOURCE_DIR}/cBlasCheck.cpp"
--				CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${CBLAS_INCLUDES}"
--				LINK_LIBRARIES ${CBLAS_LIBRARY}
--			)
--			if(CBLAS_COMPILE)
--				set(CBLAS_VENDOR "GENERIC")
--				set(CBLAS_LIBRARIES ${CBLAS_LIBRARY})
--			else()
--				message(WARNING "Unknown CBLAS. Can not use it")
--			endif()
--		endif()
--	endif()
-+  set(CBLAS_VENDOR FALSE)
-+  if( APPLE )
-+    set(CBLAS_VENDOR "Accelerate")
-+    set(CBLAS_INCLUDES "")
-+    set(CBLAS_LIBRARIES "-framework Accelerate" )
-+  else()
-+    #todo: do a propper vendor check
-+    find_library(OPENBLAS_LIBRARY openblas
-+      HINTS ${CBLAS_ROOT}/lib /opt/local/lib
-+      )
-+    find_library(CBLAS_LIBRARY cblas
-+      HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
-+      )
-+    find_library(CLAPACK_LIBRARY lapack
-+      HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
-+      )
-+    find_library(ATLAS_LIBRARY atlas
-+      HINTS ${ATLAS_ROOT}/lib ${CBLAS_ROOT}/lib /opt/local/lib /usr/lib64/atlas/
-+      )
-+    mark_as_advanced(
-+      OPENBLAS_LIBRARY
-+      CBLAS_LIBRARY
-+      CLAPACK_LIBRARY
-+      ATLAS_LIBRARY
-+      )
-+    #find the cblas.h include path
-+    if(CBLAS_LIBRARY )
-+      get_filename_component(CBLAS_LIB_PATH ${CBLAS_LIBRARY} PATH )
-+    elseif( OPENBLAS_LIBRARY)	
-+      get_filename_component(CBLAS_LIB_PATH ${OPENBLAS_LIBRARY} PATH )
-+    endif()
-+    if(CBLAS_LIB_PATH)
-+      find_file(CBLAS_INCLUDES cblas.h 
-+	PATHS ${CBLAS_LIB_PATH} ${CBLAS_LIB_PATH}/../include
-+	)
-+      get_filename_component(CBLAS_INCLUDES ${CBLAS_INCLUDES} PATH )
-+    endif()
-+    if(ATLAS_LIBRARY)
-+      get_filename_component(ATLAS_LIBRARY_PATH ${ATLAS_LIBRARY} PATH )
-+      find_file(CLAPACK_INCLUDES clapack.h 
-+	PATHS
-+	${ATLAS_LIBRARY_PATH} 
-+	${ATLAS_LIBRARY_PATH}/../include
-+	${ATLAS_LIBRARY_PATH}/../include/atlas
-+	${ATLAS_LIBRARY_PATH}/../../include/atlas
-+	)
-+      get_filename_component(CLAPACK_INCLUDES ${CLAPACK_INCLUDES} PATH )
-+      set(CBLAS_INCLUDES ${CBLAS_INCLUDES} ${CLAPACK_INCLUDES})
-+    endif()
-+
-+    if( OPENBLAS_LIBRARY AND CBLAS_INCLUDES)
-+      set(CBLAS_VENDOR "OpenBLAS")
-+      set(CBLAS_LIBRARIES ${OPENBLAS_LIBRARY})
-+    elseif( CBLAS_LIBRARY AND CLAPACK_LIBRARY AND ATLAS_LIBRARY AND CBLAS_INCLUDES)
-+      set(CBLAS_VENDOR "ATLAS")
-+      set(CBLAS_LIBRARIES ${CLAPACK_LIBRARY} ${CBLAS_LIBRARY} ${ATLAS_LIBRARY})
-+    elseif( CBLAS_LIBRARY AND CBLAS_INCLUDES)
-+      #check that we can compile a basic program with the libraries we have found
-+      #vendor versions might come with additional libraries which would be bad.
-+      try_compile(CBLAS_COMPILE 
-+	"${PROJECT_BINARY_DIR}/cBlasCheck"
-+	"${CMAKE_SOURCE_DIR}/cBlasCheck.cpp"
-+	CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${CBLAS_INCLUDES}"
-+	LINK_LIBRARIES ${CBLAS_LIBRARY}
-+	)
-+      if(CBLAS_COMPILE)
-+	set(CBLAS_VENDOR "GENERIC")
-+	set(CBLAS_LIBRARIES ${CBLAS_LIBRARY})
-+      else()
-+	message(WARNING "Unknown CBLAS. Can not use it")
-+      endif()
-+    endif()
-+  endif()
- 	
--	if(CBLAS_VENDOR)
--		message(STATUS "CBLAS FOUND: " ${CBLAS_VENDOR} " with include directory " ${CBLAS_INCLUDES} )
--		set(SHARK_USE_CBLAS 1)
--		list(APPEND EXTRA_INCLUDE_DIRECTORIES ${CBLAS_INCLUDES} )
--		list(APPEND LINK_LIBRARIES ${CBLAS_LIBRARIES})
--		include_directories ( ${CBLAS_INCLUDES} )
--	else()
--		message(STATUS "No usable CBLAS Library found. No fast linear Algebra used.")
--	endif()
-+  if(CBLAS_VENDOR)
-+    message(STATUS "CBLAS FOUND: " ${CBLAS_VENDOR} " with include directory " ${CBLAS_INCLUDES} )
-+    set(SHARK_USE_CBLAS 1)
-+    list(APPEND EXTRA_INCLUDE_DIRECTORIES ${CBLAS_INCLUDES} )
-+    list(APPEND LINK_LIBRARIES ${CBLAS_LIBRARIES})
-+    include_directories ( ${CBLAS_INCLUDES} )
-+  else()
-+    message(STATUS "No usable CBLAS Library found. No fast linear Algebra used.")
-+  endif()
- 	
--	#Special setup for ATLAS
--	if( CBLAS_VENDOR MATCHES "ATLAS" )
--		set( SHARK_USE_ATLAS_LAPACK 1) # ATLAS always contains some LAPACK methods that we can use
-+  #Special setup for ATLAS
-+  if( CBLAS_VENDOR MATCHES "ATLAS" )
-+    set( SHARK_USE_ATLAS_LAPACK 1) # ATLAS always contains some LAPACK methods that we can use
- 		
--		#check for full lapack
--		set(CMAKE_REQUIRE_QUIET 1)
--		set(CMAKE_REQUIRED_LIBRARIES ${CBLAS_LIBRARIES})
--		check_function_exists(dsyev_ ATLAS_FULL_LAPACK)
-+    #check for full lapack
-+    set(CMAKE_REQUIRE_QUIET 1)
-+    set(CMAKE_REQUIRED_LIBRARIES ${CBLAS_LIBRARIES})
-+    check_function_exists(dsyev_ ATLAS_FULL_LAPACK)
- 		
--		if( ATLAS_FULL_LAPACK )
--			set( SHARK_USE_LAPACK 1)
--			message(STATUS "Detected ATLAS with full LAPACK package. Using it!")
--		endif()
--	endif()
-+    if( ATLAS_FULL_LAPACK )
-+      set( SHARK_USE_LAPACK 1)
-+      message(STATUS "Detected ATLAS with full LAPACK package. Using it!")
-+    endif()
-+  endif()
- endif()
- #####################################################################
- #                       Static Code Analysis
diff --git a/SuperBuild/patches/SHARK/shark-2-find-boost-all.diff b/SuperBuild/patches/SHARK/shark-2-find-boost-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..a97c1ac4afd1f56118fdba14cf7b993755bb5c00
--- /dev/null
+++ b/SuperBuild/patches/SHARK/shark-2-find-boost-all.diff
@@ -0,0 +1,16 @@
+diff -burN Shark-349f29bd71c370e0f88f7fc9aa66fa5c4768fcb0.orig/CMakeLists.txt Shark-349f29bd71c370e0f88f7fc9aa66fa5c4768fcb0/CMakeLists.txt
+--- Shark-349f29bd71c370e0f88f7fc9aa66fa5c4768fcb0.orig/CMakeLists.txt	2017-08-22 11:31:50.472052695 +0200
++++ Shark-349f29bd71c370e0f88f7fc9aa66fa5c4768fcb0/CMakeLists.txt	2017-08-22 11:32:36.448358789 +0200
+@@ -141,10 +141,8 @@
+ 
+ find_package( 
+ 	Boost 1.48.0 REQUIRED COMPONENTS
+-	system date_time filesystem
+-	program_options serialization thread
+-	unit_test_framework
+-)
++	serialization
++	)
+ 
+ if(NOT Boost_FOUND)
+ 	message(FATAL_ERROR "Please make sure Boost 1.48.0 is installed on your system")
diff --git a/SuperBuild/patches/TIFF/CMakeLists.txt b/SuperBuild/patches/TIFF/CMakeLists.txt
deleted file mode 100644
index 287ba9ceba8ccc92673fcc929496438f557a6050..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/TIFF/CMakeLists.txt
+++ /dev/null
@@ -1,45 +0,0 @@
-#
-# Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
-#
-# This file is part of Orfeo Toolbox
-#
-#     https://www.orfeo-toolbox.org/
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-cmake_minimum_required(VERSION 2.8.3)
-
-project(tiff_install)
-
-file(GLOB ${PROJECT_NAME}_HEADERS "${TIFF_BUILD_DIR}/tif*.h" )
-file(GLOB ${PROJECT_NAME}_LIBS "${TIFF_BUILD_DIR}/libtiff*.lib" )
-file(GLOB ${PROJECT_NAME}_DLLS "${TIFF_BUILD_DIR}/libtiff*.dll" )
-
-foreach(${PROJECT_NAME}_HEADER ${${PROJECT_NAME}_HEADERS})
-install(FILES ${${PROJECT_NAME}_HEADER}
-  DESTINATION include
-  COMPONENT Development)
-endforeach()
-  
-foreach(${PROJECT_NAME}_LIB ${${PROJECT_NAME}_LIBS})
-install(FILES ${${PROJECT_NAME}_LIB}
-  DESTINATION lib
-  COMPONENT Development)
-endforeach()
-
-foreach(${PROJECT_NAME}_DLL ${${PROJECT_NAME}_DLLS})
-install(FILES ${${PROJECT_NAME}_DLL}
-  DESTINATION bin
-  COMPONENT Development)
-endforeach()
\ No newline at end of file
diff --git a/SuperBuild/patches/TIFF/nmake.opt b/SuperBuild/patches/TIFF/nmake.opt
deleted file mode 100644
index cb1c9ea849db145f3ce36c0e00aeeecfaa6ea0ff..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/TIFF/nmake.opt
+++ /dev/null
@@ -1,218 +0,0 @@
-# $Id: nmake.opt,v 1.18 2006/06/07 16:33:45 dron Exp $
-#
-# Copyright (C) 2004, Andrey Kiselev <dron@ak4719.spb.edu>
-#
-# Permission to use, copy, modify, distribute, and sell this software and 
-# its documentation for any purpose is hereby granted without fee, provided
-# that (i) the above copyright notices and this permission notice appear in
-# all copies of the software and related documentation, and (ii) the names of
-# Sam Leffler and Silicon Graphics may not be used in any advertising or
-# publicity relating to the software without the specific, prior written
-# permission of Sam Leffler and Silicon Graphics.
-# 
-# THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
-# EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
-# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
-# 
-# IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
-# ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
-# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-# WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
-# LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
-# OF THIS SOFTWARE.
-
-# Compile time parameters for MS Visual C++ compiler.
-# You may edit this file to specify building options.
-
-#
-###### Edit the following lines to choose a feature set you need. #######
-#
-
-# 
-# Select WINMODE_CONSOLE to build a library which reports errors to stderr, or
-# WINMODE_WINDOWED to build such that errors are reported via MessageBox().
-#
-WINMODE_CONSOLE = 1
-#WINMODE_WINDOWED = 1
-
-#
-# Comment out the following lines to disable internal codecs.
-#
-# Support for CCITT Group 3 & 4 algorithms
-CCITT_SUPPORT	= 1
-# Support for Macintosh PackBits algorithm
-PACKBITS_SUPPORT = 1
-# Support for LZW algorithm
-LZW_SUPPORT	= 1
-# Support for ThunderScan 4-bit RLE algorithm
-THUNDER_SUPPORT	= 1
-# Support for NeXT 2-bit RLE algorithm
-NEXT_SUPPORT	= 1
-# Support for LogLuv high dynamic range encoding
-LOGLUV_SUPPORT	= 1
-
-#
-# Uncomment and edit following lines to enable JPEG support.
-#
-JPEG_SUPPORT = 1
-JPEGDIR 	 = @CMAKE_WIN_INSTALL_PREFIX@
-JPEG_INCLUDE = -I$(JPEGDIR)\include
-JPEG_LIB 	 = $(JPEGDIR)\lib\jpeg.lib
-
-#
-# Uncomment and edit following lines to enable ZIP support
-# (required for Deflate compression and Pixar log-format)
-#
-ZIP_SUPPORT	 = 1
-ZLIBDIR 	 = @CMAKE_WIN_INSTALL_PREFIX@
-ZLIB_INCLUDE = -I$(ZLIBDIR)\include
-ZLIB_LIB 	 = $(ZLIBDIR)\lib\zlib.lib
-
-#
-# Uncomment and edit following lines to enable ISO JBIG support
-#
-#JBIG_SUPPORT	= 1
-#JBIGDIR 	= d:/projects/jbigkit
-#JBIG_INCLUDE	= -I$(JBIGDIR)/libjbig
-#JBIG_LIB 	= $(JBIGDIR)/libjbig/jbig.lib
-
-#
-# Uncomment following line to enable Pixar log-format algorithm
-# (Zlib required).
-#
-#PIXARLOG_SUPPORT = 1
-
-#
-# Comment out the following lines to disable strip chopping
-# (whether or not to convert single-strip uncompressed images to mutiple
-# strips of specified size to reduce memory usage). Default strip size
-# is 8192 bytes, it can be configured via the STRIP_SIZE_DEFAULT parameter
-#
-STRIPCHOP_SUPPORT = 1
-STRIP_SIZE_DEFAULT = 8192
-
-#
-# Comment out the following lines to disable treating the fourth sample with
-# no EXTRASAMPLE_ value as being ASSOCALPHA. Many packages produce RGBA
-# files but don't mark the alpha properly.
-#
-EXTRASAMPLE_AS_ALPHA_SUPPORT = 1
-
-#
-# Comment out the following lines to disable picking up YCbCr subsampling
-# info from the JPEG data stream to support files lacking the tag.
-# See Bug 168 in Bugzilla, and JPEGFixupTestSubsampling() for details.
-#
-CHECK_JPEG_YCBCR_SUBSAMPLING = 1
-
-#
-####################### Compiler related options. #######################
-#
-
-#
-# Pick debug or optimized build flags.  We default to an optimized build
-# with no debugging information.
-# NOTE: /EHsc option required if you want to build the C++ stream API
-#
-OPTFLAGS =	/Ox /MD /EHsc /W3 /D_CRT_SECURE_NO_DEPRECATE -DHAVE_SNPRINTF
-#OPTFLAGS = 	/Zi 
-
-#
-# Uncomment following line to enable using Windows Common RunTime Library
-# instead of Windows specific system calls. See notes on top of tif_unix.c
-# module for details.
-#
-USE_WIN_CRT_LIB = 1
-
-# Compiler specific options. You may probably want to adjust compilation
-# parameters in CFLAGS variable. Refer to your compiler documentation
-# for the option reference.
-#
-MAKE	=	nmake /nologo
-CC	=	cl /nologo
-CXX	=	cl /nologo
-AR	=	lib /nologo
-LD	=	link /nologo
-
-CFLAGS  =	$(OPTFLAGS) $(INCL) $(EXTRAFLAGS)
-CXXFLAGS =	$(OPTFLAGS) $(INCL) $(EXTRAFLAGS)
-EXTRAFLAGS =
-LIBS	=
-
-# Name of the output shared library
-DLLNAME	= libtiff.dll
-
-#
-########### There is nothing to edit below this line normally. ###########
-#
-
-# Set the native cpu bit order
-EXTRAFLAGS	= -DFILLODER_LSB2MSB $(EXTRAFLAGS)
-
-!IFDEF WINMODE_WINDOWED
-EXTRAFLAGS	= -DTIF_PLATFORM_WINDOWED $(EXTRAFLAGS)
-LIBS		= user32.lib $(LIBS)
-!ELSE
-EXTRAFLAGS	= -DTIF_PLATFORM_CONSOLE $(EXTRAFLAGS)
-!ENDIF
-
-# Codec stuff
-!IFDEF CCITT_SUPPORT
-EXTRAFLAGS	= -DCCITT_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF PACKBITS_SUPPORT
-EXTRAFLAGS	= -DPACKBITS_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF LZW_SUPPORT
-EXTRAFLAGS	=  -DLZW_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF THUNDER_SUPPORT
-EXTRAFLAGS	= -DTHUNDER_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF NEXT_SUPPORT
-EXTRAFLAGS	= -DNEXT_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF LOGLUV_SUPPORT
-EXTRAFLAGS	= -DLOGLUV_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF JPEG_SUPPORT
-LIBS		= $(LIBS) $(JPEG_LIB)
-EXTRAFLAGS	= -DJPEG_SUPPORT -DOJPEG_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF ZIP_SUPPORT
-LIBS		= $(LIBS) $(ZLIB_LIB)
-EXTRAFLAGS	= -DZIP_SUPPORT $(EXTRAFLAGS)
-!IFDEF PIXARLOG_SUPPORT
-EXTRAFLAGS	= -DPIXARLOG_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-!ENDIF
-
-!IFDEF JBIG_SUPPORT
-LIBS		= $(LIBS) $(JBIG_LIB)
-EXTRAFLAGS	= -DJBIG_SUPPORT $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF STRIPCHOP_SUPPORT
-EXTRAFLAGS	= -DSTRIPCHOP_DEFAULT=TIFF_STRIPCHOP -DSTRIP_SIZE_DEFAULT=$(STRIP_SIZE_DEFAULT) $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF EXTRASAMPLE_AS_ALPHA_SUPPORT
-EXTRAFLAGS	= -DDEFAULT_EXTRASAMPLE_AS_ALPHA $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF CHECK_JPEG_YCBCR_SUBSAMPLING
-EXTRAFLAGS	= -DCHECK_JPEG_YCBCR_SUBSAMPLING $(EXTRAFLAGS)
-!ENDIF
-
-!IFDEF USE_WIN_CRT_LIB
-EXTRAFLAGS	= -DAVOID_WIN32_FILEIO $(EXTRAFLAGS)
-!ELSE
-EXTRAFLAGS	= -DUSE_WIN32_FILEIO $(EXTRAFLAGS)
-!ENDIF
diff --git a/SuperBuild/patches/TIFF/tiff-1-cmakefixes-all.diff b/SuperBuild/patches/TIFF/tiff-1-cmakefixes-all.diff
new file mode 100644
index 0000000000000000000000000000000000000000..a0c3b6f08bcaa234f96f07d266cf1bdbaae189bc
--- /dev/null
+++ b/SuperBuild/patches/TIFF/tiff-1-cmakefixes-all.diff
@@ -0,0 +1,163 @@
+diff -burN tiff-4.0.8.orig/CMakeLists.txt tiff-4.0.8/CMakeLists.txt
+--- tiff-4.0.8.orig/CMakeLists.txt	Thu Jul 20 12:53:54 2017
++++ tiff-4.0.8/CMakeLists.txt	Thu Jul 20 13:17:05 2017
+@@ -601,21 +601,35 @@
+   set(CXX_SUPPORT TRUE)
+ endif()
+ 
+-# OpenGL and GLUT
+-find_package(OpenGL)
+-find_package(GLUT)
+-set(HAVE_OPENGL FALSE)
+-if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
++# OpenGL support
++option(with_opengl "Enable opengl support (requires opengl and glut packages)" ON)
++if(with_opengl)
++  # OpenGL and GLUT
++  find_package(OpenGL)
++  find_package(GLUT)
++  set(HAVE_OPENGL FALSE)
++  if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
+   set(HAVE_OPENGL TRUE)
+-endif()
+-# Purely to satisfy the generated headers:
+-check_include_file(GL/gl.h HAVE_GL_GL_H)
+-check_include_file(GL/glu.h HAVE_GL_GLU_H)
+-check_include_file(GL/glut.h HAVE_GL_GLUT_H)
+-check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
+-check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
+-check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
++  endif()
++  # Purely to satisfy the generated headers:
++  check_include_file(GL/gl.h HAVE_GL_GL_H)
++  check_include_file(GL/glu.h HAVE_GL_GLU_H)
++  check_include_file(GL/glut.h HAVE_GL_GLUT_H)
++  check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
++  check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
++  check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
++else() #with_opengl
++  set(HAVE_OPENGL FALSE)
++  #force  opengl headers check to FALSE.
++  set(HAVE_GL_GL_H FALSE)
++  set(HAVE_GL_GLU_H FALSE)
++  set(HAVE_GL_GLUT_H FALSE)
++  set(HAVE_GLUT_GLUT_H FALSE)
++  set(HAVE_OPENGL_GL_H FALSE)
++  set(HAVE_OPENGL_GLU_H FALSE)
++endif() #with_opengl
+ 
++
+ # Win32 IO
+ set(win32_io FALSE)
+ if(WIN32)
+@@ -713,19 +727,38 @@
+ if(LIBLZMA_LIBRARIES)
+   list(APPEND TIFF_LIBRARY_DEPS ${LIBLZMA_LIBRARIES})
+ endif()
+-
+ #report_values(TIFF_INCLUDES TIFF_LIBRARY_DEPS)
+ 
++# NEED_LIBPORT is later updated in port/CMakeLists.txt and 
++# used in libtiff/CMakeLists.txt to generate tif_config.h.
++# see libtiff/tif_config.h.cmake.in for usage
++set(NEED_LIBPORT FALSE)
++
+ # Process subdirectories
+ add_subdirectory(port)
+ add_subdirectory(libtiff)
+-add_subdirectory(tools)
+-add_subdirectory(test)
+-add_subdirectory(contrib)
++
++option(with_tools "build executables in tools directory" ON)
++if(with_tools)
++  add_subdirectory(tools)
++endif()
++option(with_test "build executables in tests directory" ON)
++if(with_test)
++  add_subdirectory(test)
++endif()
++
++option(with_contrib "build executables in contrib directory" ON)
++if(with_contrib)
++  add_subdirectory(contrib)
++endif()
++
+ add_subdirectory(build)
+-add_subdirectory(man)
+-add_subdirectory(html)
+-
++
++option(with_docs "build html and man docs" ON)
++if(with_docs)
++  add_subdirectory(man)
++  add_subdirectory(html)
++endif()
+ #message(STATUS "EXTRA_DIST: ${EXTRA_DIST}")
+ 
+ message(STATUS "")
+diff -burN tiff-4.0.8.orig/contrib/iptcutil/iptcutil.c tiff-4.0.8/contrib/iptcutil/iptcutil.c
+--- tiff-4.0.8.orig/contrib/iptcutil/iptcutil.c	Thu Jul 20 12:53:54 2017
++++ tiff-4.0.8/contrib/iptcutil/iptcutil.c	Thu Jul 20 13:14:55 2017
+@@ -19,7 +19,7 @@
+ # include <fcntl.h>
+ #endif
+ 
+-#ifdef WIN32
++#ifdef _MSC_VER
+ #define STRNICMP strnicmp
+ #else 
+ #define STRNICMP strncasecmp
+diff -burN tiff-4.0.8.orig/libtiff/tif_config.h.cmake.in tiff-4.0.8/libtiff/tif_config.h.cmake.in
+--- tiff-4.0.8.orig/libtiff/tif_config.h.cmake.in	Thu Jul 20 12:53:54 2017
++++ tiff-4.0.8/libtiff/tif_config.h.cmake.in	Thu Jul 20 13:15:21 2017
+@@ -259,3 +259,9 @@
+ 
+ /* Define to `unsigned int' if <sys/types.h> does not define. */
+ #undef size_t
++
++#ifdef _MSC_VER
++#pragma warning(disable : 4996) /* function deprecation warnings */
++#endif
++
++#cmakedefine NEED_LIBPORT 1
+diff -burN tiff-4.0.8.orig/port/CMakeLists.txt tiff-4.0.8/port/CMakeLists.txt
+--- tiff-4.0.8.orig/port/CMakeLists.txt	Thu Jul 20 12:53:54 2017
++++ tiff-4.0.8/port/CMakeLists.txt	Thu Jul 20 13:15:32 2017
+@@ -32,25 +32,35 @@
+   strtoull.c)
+ 
+ set(port_USED_FILES ${port_SOURCES} ${port_HEADERS})
+-
++  set(LIBPORT_USED FALSE)
+ if(NOT HAVE_GETOPT)
+   list(APPEND port_USED_FILES getopt.c)
++    set(LIBPORT_USED TRUE)
+ endif()
+ if(NOT HAVE_LFIND)
+   list(APPEND port_USED_FILES lfind.c)
++    set(LIBPORT_USED TRUE)
+ endif()
+ if(MSVC AND NOT HAVE_SNPRINTF)
+   list(APPEND port_USED_FILES snprintf.c)
++    set(LIBPORT_USED TRUE)
+ endif()
+ if(NOT HAVE_STRCASECMP)
+   list(APPEND port_USED_FILES strcasecmp.c)
++    set(LIBPORT_USED TRUE)
+ endif()
+ if(NOT HAVE_STRTOUL)
+   list(APPEND port_USED_FILES strtoul.c)
++    set(LIBPORT_USED TRUE)
+ endif()
+ if(NOT HAVE_STRTOULL)
+   list(APPEND port_USED_FILES strtoull.c)
++  set(LIBPORT_USED TRUE)
+ endif()
++
++# We set NEED_LIBPORT with PARENT_SCOPE 
++# because it is used in libtiff/CMakeLists.txt
++set(NEED_LIBPORT ${LIBPORT_USED} PARENT_SCOPE)
+ 
+ add_library(port STATIC ${port_USED_FILES})
+ 
diff --git a/SuperBuild/patches/TIFF/tiff-1-noopengl-linux.diff b/SuperBuild/patches/TIFF/tiff-1-noopengl-linux.diff
deleted file mode 100755
index 04b1ef4f181fe243c5d9413e76a129e57981689d..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/TIFF/tiff-1-noopengl-linux.diff
+++ /dev/null
@@ -1,38 +0,0 @@
-diff -burN tiff-4.0.6.orig/CMakeLists.txt tiff-4.0.6/CMakeLists.txt
---- tiff-4.0.6.orig/CMakeLists.txt	2016-10-27 17:24:17.000000000 +0200
-+++ tiff-4.0.6/CMakeLists.txt	2016-10-27 17:25:43.000000000 +0200
-@@ -602,19 +602,23 @@
- endif()
- 
- # OpenGL and GLUT
--find_package(OpenGL)
--find_package(GLUT)
--set(HAVE_OPENGL FALSE)
--if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
-+option(WITH_OPENGL "Enable opengl and glut support" ON)
-+
-+if(WITH_OPENGL)  
-+  find_package(OpenGL)
-+  find_package(GLUT)
-+  set(HAVE_OPENGL FALSE)
-+  if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
-   set(HAVE_OPENGL TRUE)
-+  endif()
-+  # Purely to satisfy the generated headers:
-+  check_include_file(GL/gl.h HAVE_GL_GL_H)
-+  check_include_file(GL/glu.h HAVE_GL_GLU_H)
-+  check_include_file(GL/glut.h HAVE_GL_GLUT_H)
-+  check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
-+  check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
-+  check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
- endif()
--# Purely to satisfy the generated headers:
--check_include_file(GL/gl.h HAVE_GL_GL_H)
--check_include_file(GL/glu.h HAVE_GL_GLU_H)
--check_include_file(GL/glut.h HAVE_GL_GLUT_H)
--check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
--check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
--check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
- 
- # Win32 IO
- set(win32_io FALSE)
diff --git a/SuperBuild/patches/TIFF/tiff-1-noopengl-macx.diff b/SuperBuild/patches/TIFF/tiff-1-noopengl-macx.diff
deleted file mode 100755
index 04b1ef4f181fe243c5d9413e76a129e57981689d..0000000000000000000000000000000000000000
--- a/SuperBuild/patches/TIFF/tiff-1-noopengl-macx.diff
+++ /dev/null
@@ -1,38 +0,0 @@
-diff -burN tiff-4.0.6.orig/CMakeLists.txt tiff-4.0.6/CMakeLists.txt
---- tiff-4.0.6.orig/CMakeLists.txt	2016-10-27 17:24:17.000000000 +0200
-+++ tiff-4.0.6/CMakeLists.txt	2016-10-27 17:25:43.000000000 +0200
-@@ -602,19 +602,23 @@
- endif()
- 
- # OpenGL and GLUT
--find_package(OpenGL)
--find_package(GLUT)
--set(HAVE_OPENGL FALSE)
--if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
-+option(WITH_OPENGL "Enable opengl and glut support" ON)
-+
-+if(WITH_OPENGL)  
-+  find_package(OpenGL)
-+  find_package(GLUT)
-+  set(HAVE_OPENGL FALSE)
-+  if(OPENGL_FOUND AND OPENGL_GLU_FOUND AND GLUT_FOUND)
-   set(HAVE_OPENGL TRUE)
-+  endif()
-+  # Purely to satisfy the generated headers:
-+  check_include_file(GL/gl.h HAVE_GL_GL_H)
-+  check_include_file(GL/glu.h HAVE_GL_GLU_H)
-+  check_include_file(GL/glut.h HAVE_GL_GLUT_H)
-+  check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
-+  check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
-+  check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
- endif()
--# Purely to satisfy the generated headers:
--check_include_file(GL/gl.h HAVE_GL_GL_H)
--check_include_file(GL/glu.h HAVE_GL_GLU_H)
--check_include_file(GL/glut.h HAVE_GL_GLUT_H)
--check_include_file(GLUT/glut.h HAVE_GLUT_GLUT_H)
--check_include_file(OpenGL/gl.h HAVE_OPENGL_GL_H)
--check_include_file(OpenGL/glu.h HAVE_OPENGL_GLU_H)
- 
- # Win32 IO
- set(win32_io FALSE)
diff --git a/Utilities/Maintenance/SuperbuildDownloadList.sh b/Utilities/Maintenance/SuperbuildDownloadList.sh
index 6b09c62d4173125b529c295ed58ebea2bda67d7e..d7bd8c493517194cf2ef22accbc6b0e4565d3291 100755
--- a/Utilities/Maintenance/SuperbuildDownloadList.sh
+++ b/Utilities/Maintenance/SuperbuildDownloadList.sh
@@ -20,77 +20,62 @@
 #
 
 
-export LC_ALL=C
-if [ $# -eq 2 ]; then
-DOWNLOAD_DIR=$(readlink -f $1)
-OUTPUT_DIR=$(readlink -f $2)
-else
-echo 'Usage: '$0' <download_directory> <archive_output_directory>'
-exit 1
+
+if [ $# -lt 2 ]; then
+    echo "Usage: $0 <download_directory> <archive_output_directory>"
+    exit 1
 fi
 
-WGET="wget -nv -q"
+export LC_ALL=C
 
-SB_CMAKE_DIR_REL=$(dirname $0)/../../SuperBuild/CMake
-SB_CMAKE_DIR=$(readlink -f ${SB_CMAKE_DIR_REL})
+DOWNLOAD_DIR=$(readlink -f "$1")
+OUTPUT_DIR=$(readlink -f "$2")
+WGET=$(which wget)
 
-cd $(dirname $0)/../../
 
-GIT_BRANCH=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
+CUR_DIR="$( cd "$( dirname "$0" )" && pwd )"
 
+SB_CMAKE_DIR_REL=$CUR_DIR/../../SuperBuild/CMake
+SB_CMAKE_DIR=$(readlink -f "${SB_CMAKE_DIR_REL}")
+cd "$CUR_DIR/../../" || echo "cannot cd to CUR_DIR/../../"
+GIT_BRANCH=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
 #if a branch contains release-X.Y then xdk is taken from packages/xdk/OTB-X.Y
 if [[ "$GIT_BRANCH" =~ release-* ]]; then
-    VERSION=$(echo ${GIT_BRANCH}| sed 's/.*release-//'| cut -d'-' -f 1)
+    VERSION=$(echo "${GIT_BRANCH}"| sed 's/.*release-//'| cut -d'-' -f 1)
 else
     VERSION="develop"
 fi
-DOWNLOAD_LIST=$(grep -h -E "^[^#]*\"https?://.*(\.tar\.gz|\.tar\.bz2|\.tgz|\.tar\.xz|\.zip|export=download).*\"" ${SB_CMAKE_DIR}/*.cmake | grep -o -E "https?://[^\"]*" | sed "s/\/\(download\)\?$//" | sort | uniq)
+CMAKE_FILES=$(find $SB_CMAKE_DIR -maxdepth 1 -type f -name "External_*")
+DOWNLOAD_LIST=$(grep -h -E '^[^#]*\"https?://.*(\.tar\.gz|\.tar\.bz2|\.tgz|\.tar\.xz|\.zip|export=download).*\"' ${CMAKE_FILES} |
+		    grep -o -E 'https?://[^\"]*' | sort | uniq)
 
 DOWNLOAD_NAMES=
 
-mkdir -p ${DOWNLOAD_DIR}
-cd ${DOWNLOAD_DIR}
+#echo "DOWNLOAD_LIST=$DOWNLOAD_LIST"
 
+mkdir -p "${DOWNLOAD_DIR}"
+cd "${DOWNLOAD_DIR}" || echo "cannot cd to DOWNLOAD_DIR"
 echo "Downloading files to ${DOWNLOAD_DIR}/"
-
 for url in ${DOWNLOAD_LIST}; do
-  # clean log file
-
-  file_name=$(echo "${url}" | grep -o -E "[^\/]+$")
-  docs_google=$(echo "${file_name}" | grep -F "export=download")
-  if [ "${docs_google}" = "" ]; then
-      if [ -f "$file_name" ]; then
-          echo "$file_name exists, skipping"
-      fi;
-      $WGET -N ${url}
-      ret="$?"
-   if [ $ret -gt 0 -a $ret -ne 8  ]; then
-       echo "Download failed for URL: '${url}'. wget finished with exit status '$ret'."
-       exit 1;
-   fi
-  else
-    # look into the original file for a valid download name
-    file_name=$(grep -h -A 3 -B 3 -F "${url}" ${SB_CMAKE_DIR}/*.cmake | grep -E "^[^#]*DOWNLOAD_NAME" | grep -o -E "[^ ]*\.(tar\.gz|tar\.bz2|tar\.xz|zip)" | uniq)
-    if [ -z "$file_name" ]; then
-        echo "Can't find correct filename for url ${url} : skip download"
-        exit 1;
-    else
-        # echo "Download ${file_name}..."
-        $WGET ${url} -O ${file_name}
-    fi
+  file_name=$(echo "${url}" | grep -o -E '[^\/]+$')
+  $WGET -N "${url}"
+  ret="$?"
+  if [ $ret -gt 0 ] && [ $ret -ne 8 ]; then
+     echo "Download failed for URL: '${url}'. wget finished with exit status '$ret'."
+     exit 1;
   fi
 
   if [ "$file_name" != "" ]; then
-      DOWNLOAD_NAMES="${DOWNLOAD_NAMES} ${file_name}"
+     DOWNLOAD_NAMES="${DOWNLOAD_NAMES} ${file_name}"
+  else
+     echo "invalid filename for url=${url}" && exit 1;
   fi
-
 done
 
 ARCHIVE_NAME="SuperBuild-archives-$VERSION"
 echo "Creating archive ${OUTPUT_DIR}/$ARCHIVE_NAME.tar.bz2"
-
-cd ${OUTPUT_DIR}
-tar -cjf $ARCHIVE_NAME.tar.bz2 -C ${DOWNLOAD_DIR} ${DOWNLOAD_NAMES}
-
+cd "${OUTPUT_DIR}" || echo "cannot cd to OUTPUT_DIR"
+touch "${DOWNLOAD_DIR}/OTBSuperBuild.readme"
+tar -cjf "$ARCHIVE_NAME.tar.bz2" -C "${DOWNLOAD_DIR}" ${DOWNLOAD_NAMES} OTBSuperBuild.readme
 echo "Saving md5sum to ${OUTPUT_DIR}/$ARCHIVE_NAME.md5"
-md5sum $ARCHIVE_NAME.tar.bz2 > $ARCHIVE_NAME.md5
+md5sum "$ARCHIVE_NAME.tar.bz2" > "$ARCHIVE_NAME.md5"