[SCM] blender/master: debian/patches/: patchset updated against v2.78a

mfv at users.alioth.debian.org mfv at users.alioth.debian.org
Tue Nov 15 21:26:19 UTC 2016


The following commit has been merged in the master branch:
commit 4d2551e07f0a9e1f5caa0b428267ad5023720443
Author: Matteo F. Vescovi <mfv at debian.org>
Date:   Thu Nov 3 14:23:18 2016 +0100

    debian/patches/: patchset updated against v2.78a
    
    - #0001 -> #0006 refreshed
    - #0009 renamed to 0007-fix_OpenJPEG2_build.patch
    - 0007-fix_FTBFS_on_armel.patch dropped (applied upstream)
    - 0008-make_blender_reproducible.patch dropped (applied upstream)
    - 0010-fix_manpage_creation.patch dropped (applied upstream)
    - 0011-fix_ld-gold_issue.patch dropped (become useless)

diff --git a/debian/patches/0001-blender_thumbnailer.patch b/debian/patches/0001-blender_thumbnailer.patch
index 21de67c..85bc0eb 100644
--- a/debian/patches/0001-blender_thumbnailer.patch
+++ b/debian/patches/0001-blender_thumbnailer.patch
@@ -1,15 +1,13 @@
 From: "Matteo F. Vescovi" <mfv at debian.org>
-Date: Thu, 9 Jul 2015 22:31:02 +0200
+Date: Sat, 29 Oct 2016 14:31:49 +0200
 Subject: blender_thumbnailer
 
 * Add blender.thumbnailer file
-* Change to python3 since lintian is messing around with that
 * Move thumbnailer script to an appropriate destination
 ---
- blender.thumbnailer                | 4 ++++
- release/bin/blender-thumbnailer.py | 2 +-
- source/creator/CMakeLists.txt      | 2 +-
- 3 files changed, 6 insertions(+), 2 deletions(-)
+ blender.thumbnailer           | 4 ++++
+ source/creator/CMakeLists.txt | 2 +-
+ 2 files changed, 5 insertions(+), 1 deletion(-)
  create mode 100644 blender.thumbnailer
 
 diff --git a/blender.thumbnailer b/blender.thumbnailer
@@ -22,26 +20,16 @@ index 0000000..05d4fae
 +TryExec=/usr/share/blender/scripts/blender-thumbnailer.py
 +Exec=/usr/share/blender/scripts/blender-thumbnailer.py %i %o
 +MimeType=application/x-blender;
-diff --git a/release/bin/blender-thumbnailer.py b/release/bin/blender-thumbnailer.py
-index fe5d462..5d2dd95 100755
---- a/release/bin/blender-thumbnailer.py
-+++ b/release/bin/blender-thumbnailer.py
-@@ -1,4 +1,4 @@
--#!/usr/bin/env python
-+#!/usr/bin/env python3
- 
- # ##### BEGIN GPL LICENSE BLOCK #####
- #
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index ff6544c..e7729d4 100644
+index f65688e..2f57417 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -497,7 +497,7 @@ if(UNIX AND NOT APPLE)
- 		)
+@@ -486,7 +486,7 @@ if(UNIX AND NOT APPLE)
  		install(
- 			PROGRAMS ${CMAKE_SOURCE_DIR}/release/bin/blender-thumbnailer.py
--			DESTINATION bin
+ 			PROGRAMS
+ 			${CMAKE_SOURCE_DIR}/release/bin/blender-thumbnailer.py
+-			DESTINATION "."
 +			DESTINATION ${CMAKE_INSTALL_PREFIX}/share/blender/scripts
  		)
- 		set(BLENDER_TEXT_FILES_DESTINATION share/doc/blender)
- 	endif()
+ 
+ 		set(BLENDER_TEXT_FILES_DESTINATION ".")
diff --git a/debian/patches/0002-install_in_usr_share.patch b/debian/patches/0002-install_in_usr_share.patch
index 5c603e2..20e624e 100644
--- a/debian/patches/0002-install_in_usr_share.patch
+++ b/debian/patches/0002-install_in_usr_share.patch
@@ -1,5 +1,5 @@
 From: "Matteo F. Vescovi" <mfv at debian.org>
-Date: Thu, 8 Jan 2015 11:45:50 +0100
+Date: Sat, 29 Oct 2016 14:38:58 +0200
 Subject: install_in_usr_share
 
 * Arch-specific files go to /usr/share
@@ -9,10 +9,10 @@ Subject: install_in_usr_share
  1 file changed, 2 insertions(+), 2 deletions(-)
 
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index e7729d4..118d807 100644
+index 2f57417..c3140c9 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -327,8 +327,8 @@ if(WITH_PYTHON)
+@@ -353,8 +353,8 @@ if(WITH_PYTHON)
  	endif()
  
  	install(
@@ -21,5 +21,5 @@ index e7729d4..118d807 100644
 +		DIRECTORY ${CMAKE_SOURCE_DIR}/release/scripts/
 +		DESTINATION ${CMAKE_INSTALL_PREFIX}/share/blender/scripts/
  		PATTERN ".git" EXCLUDE
- 		PATTERN "__pycache__" EXCLUDE
- 		PATTERN "${ADDON_EXCLUDE_CONDITIONAL}" EXCLUDE
+ 		PATTERN ".gitignore" EXCLUDE
+ 		PATTERN ".arcconfig" EXCLUDE
diff --git a/debian/patches/0003-locales_directory_install.patch b/debian/patches/0003-locales_directory_install.patch
index a48bd03..53ece14 100644
--- a/debian/patches/0003-locales_directory_install.patch
+++ b/debian/patches/0003-locales_directory_install.patch
@@ -27,7 +27,7 @@ index 077fe2a..905106d 100644
  
  /* for BKE_appdir_folder_id_version only */
 diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c
-index de21d91..aaf73ec 100644
+index b1dcc40..de2014e 100644
 --- a/source/blender/blenkernel/intern/appdir.c
 +++ b/source/blender/blenkernel/intern/appdir.c
 @@ -398,6 +398,9 @@ const char *BKE_appdir_folder_id(const int folder_id, const char *subfolder)
@@ -41,10 +41,10 @@ index de21d91..aaf73ec 100644
  			BLI_assert(0);
  			break;
 diff --git a/source/blender/blentranslation/intern/blt_lang.c b/source/blender/blentranslation/intern/blt_lang.c
-index 1ad62fa..3c70e0c 100644
+index 74c2b4b..9dc3c88 100644
 --- a/source/blender/blentranslation/intern/blt_lang.c
 +++ b/source/blender/blentranslation/intern/blt_lang.c
-@@ -84,9 +84,9 @@ static void free_locales(void)
+@@ -88,9 +88,9 @@ static void free_locales(void)
  	num_locales = num_locales_menu = 0;
  }
  
@@ -56,7 +56,7 @@ index 1ad62fa..3c70e0c 100644
  	char languages[FILE_MAX];
  	LinkNode *lines = NULL, *line;
  	char *str;
-@@ -94,7 +94,7 @@ static void fill_locales(void)
+@@ -98,7 +98,7 @@ static void fill_locales(void)
  
  	free_locales();
  
@@ -65,7 +65,7 @@ index 1ad62fa..3c70e0c 100644
  	line = lines = BLI_file_read_as_lines(languages);
  
  	/* This whole "parsing" code is a bit weak, in that it expects strictly formatted input file...
-@@ -194,7 +194,7 @@ EnumPropertyItem *BLT_lang_RNA_enum_properties(void)
+@@ -198,7 +198,7 @@ EnumPropertyItem *BLT_lang_RNA_enum_properties(void)
  void BLT_lang_init(void)
  {
  #ifdef WITH_INTERNATIONAL
@@ -74,7 +74,7 @@ index 1ad62fa..3c70e0c 100644
  #endif
  
  	/* Make sure LANG is correct and wouldn't cause std::rumtime_error. */
-@@ -227,7 +227,7 @@ void BLT_lang_init(void)
+@@ -231,7 +231,7 @@ void BLT_lang_init(void)
  #ifdef WITH_INTERNATIONAL
  	if (messagepath) {
  		bl_locale_init(messagepath, TEXT_DOMAIN_NAME);
@@ -84,10 +84,10 @@ index 1ad62fa..3c70e0c 100644
  	else {
  		printf("%s: 'locale' data path for translations not found, continuing\n", __func__);
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index 118d807..7733b4b 100644
+index c3140c9..504f85d 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -344,11 +344,11 @@ if(WITH_INTERNATIONAL)
+@@ -372,11 +372,11 @@ if(WITH_INTERNATIONAL)
  	install(
  		DIRECTORY
  			${CMAKE_SOURCE_DIR}/release/datafiles/fonts
diff --git a/debian/patches/0004-update_manpages.patch b/debian/patches/0004-update_manpages.patch
index 6b8de9f..25e67b2 100644
--- a/debian/patches/0004-update_manpages.patch
+++ b/debian/patches/0004-update_manpages.patch
@@ -148,10 +148,10 @@ index 0000000..5435c63
 +.SH AUTHORS
 +This manpage was written for a Debian by Kevin Roy <kiniou at gmail.com>.
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index 7733b4b..3edeb4a 100644
+index 504f85d..10ce80a 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -451,6 +451,7 @@ if(UNIX AND NOT APPLE)
+@@ -480,6 +480,7 @@ if(UNIX AND NOT APPLE)
  			FILES
  				${CMAKE_SOURCE_DIR}/release/freedesktop/blender.desktop
  				${CMAKE_SOURCE_DIR}/release/freedesktop/icons/scalable/apps/blender.svg
@@ -159,7 +159,7 @@ index 7733b4b..3edeb4a 100644
  			DESTINATION "."
  		)
  
-@@ -473,6 +474,10 @@ if(UNIX AND NOT APPLE)
+@@ -502,6 +503,10 @@ if(UNIX AND NOT APPLE)
  				FILES ${CMAKE_CURRENT_BINARY_DIR}/blender.1
  				DESTINATION share/man/man1
  			)
diff --git a/debian/patches/0005-do_not_use_version_number_in_system_path.patch b/debian/patches/0005-do_not_use_version_number_in_system_path.patch
index bf62399..7938f74 100644
--- a/debian/patches/0005-do_not_use_version_number_in_system_path.patch
+++ b/debian/patches/0005-do_not_use_version_number_in_system_path.patch
@@ -28,10 +28,10 @@ index 8738b8d..91d336c 100644
  	if (static_path) {
  		static string system_path = string(static_path) + "/blender/" + versionstr;
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index 3edeb4a..5a84745 100644
+index 10ce80a..69e53b3 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -281,7 +281,7 @@ if(UNIX AND NOT APPLE)
+@@ -306,7 +306,7 @@ if(UNIX AND NOT APPLE)
  		if(WITH_INSTALL_PORTABLE)
  			set(TARGETDIR_VER ${BLENDER_VERSION})
  		else()
diff --git a/debian/patches/0006-look_for_dejavu_ttf_with_fontconfig.patch b/debian/patches/0006-look_for_dejavu_ttf_with_fontconfig.patch
index f5c6d67..ed0b098 100644
--- a/debian/patches/0006-look_for_dejavu_ttf_with_fontconfig.patch
+++ b/debian/patches/0006-look_for_dejavu_ttf_with_fontconfig.patch
@@ -1,27 +1,28 @@
 From: "Matteo F. Vescovi" <mfv at debian.org>
-Date: Sat, 21 Nov 2015 21:16:38 +0100
+Date: Mon, 31 Oct 2016 22:28:15 +0100
 Subject: look_for_dejavu_ttf_with_fontconfig
 
 * Avoid using the droid font shipped with upstream source
-  and use fontconfig to get Dajavu instead.
+  and use fontconfig to get DejaVu instead.
 * Remove bad installation of fonts directory into locales.
 ---
- CMakeLists.txt                                 | 13 +++++++
+ CMakeLists.txt                                 |  6 ++++
  build_files/cmake/Modules/FindFontconfig.cmake | 48 ++++++++++++++++++++++++++
  build_files/cmake/macros.cmake                 |  6 ++++
+ build_files/cmake/platform/platform_unix.cmake |  7 ++++
  source/blender/blenfont/CMakeLists.txt         |  7 ++++
- source/blender/blenfont/intern/blf_font_i18n.c | 44 ++++++++++++++++++++++-
+ source/blender/blenfont/intern/blf_font_i18n.c | 46 ++++++++++++++++++++++--
  source/blender/blenlib/BLI_fileops.h           |  1 +
  source/blender/blenlib/intern/fileops.c        | 43 +++++++++++++++++++++++
  source/creator/CMakeLists.txt                  |  6 ----
- 8 files changed, 161 insertions(+), 7 deletions(-)
+ 9 files changed, 162 insertions(+), 8 deletions(-)
  create mode 100644 build_files/cmake/Modules/FindFontconfig.cmake
 
 diff --git a/CMakeLists.txt b/CMakeLists.txt
-index 1efaa14..fa05865 100644
+index 578f913..d9fdaaa 100644
 --- a/CMakeLists.txt
 +++ b/CMakeLists.txt
-@@ -200,6 +200,9 @@ option(WITH_BLENDER "Build blender (disable to build only the blender player)" O
+@@ -202,6 +202,9 @@ option(WITH_BLENDER "Build blender (disable to build only the blender player)" O
  mark_as_advanced(WITH_BLENDER)
  
  option(WITH_INTERNATIONAL "Enable I18N (International fonts and text)" ON)
@@ -31,21 +32,7 @@ index 1efaa14..fa05865 100644
  
  option(WITH_PYTHON        "Enable Embedded Python API  (only disable for development)" ON)
  option(WITH_PYTHON_SECURITY "Disables execution of scripts within blend files by default" ON) 
-@@ -952,6 +955,13 @@ if(UNIX AND NOT APPLE)
- 		endif()
- 	endif()
- 
-+	if(WITH_FONTCONFIG)
-+		find_package(Fontconfig)
-+		if(NOT FONTCONFIG_FOUND)
-+			set(WITH_FONTCONFIG OFF)
-+		endif()
-+	endif()
-+
- 	# Codecs
- 	if(WITH_CODEC_SNDFILE)
- 		find_package_wrapper(SndFile)
-@@ -3100,6 +3110,9 @@ if(FIRST_RUN)
+@@ -1781,6 +1784,9 @@ if(FIRST_RUN)
  		info_cfg_option(WITH_GL_ANGLE)
  	endif()
  
@@ -110,20 +97,20 @@ index 0000000..7dc09f3
 +
 +endif (FONTCONFIG_LIBRARIES AND FONTCONFIG_INCLUDE_DIR)
 diff --git a/build_files/cmake/macros.cmake b/build_files/cmake/macros.cmake
-index 7bdf790..39926dc 100644
+index 5a67ac9..aa0675f 100644
 --- a/build_files/cmake/macros.cmake
 +++ b/build_files/cmake/macros.cmake
-@@ -298,6 +298,9 @@ function(SETUP_LIBDIRS)
- 	if(WITH_MEM_JEMALLOC)
- 		link_directories(${JEMALLOC_LIBPATH})
+@@ -302,6 +302,9 @@ function(SETUP_LIBDIRS)
+ 	if(WITH_BOOST)
+ 		link_directories(${BOOST_LIBPATH})
  	endif()
 +	if(WITH_FONTCONFIG)
 +		link_directories(${FONTCONFIG_LIBPATH})
 +	endif()
- 
- 	if(WIN32 AND NOT UNIX)
- 		link_directories(${PTHREADS_LIBPATH})
-@@ -344,6 +347,9 @@ function(setup_liblinks
+ 	if(WITH_OPENIMAGEIO)
+ 		link_directories(${OPENIMAGEIO_LIBPATH})
+ 	endif()
+@@ -382,6 +385,9 @@ function(setup_liblinks
  	if(WITH_SYSTEM_GLEW)
  		target_link_libraries(${target} ${BLENDER_GLEW_LIBRARIES})
  	endif()
@@ -133,6 +120,24 @@ index 7bdf790..39926dc 100644
  	if(WITH_BULLET AND WITH_SYSTEM_BULLET)
  		target_link_libraries(${target} ${BULLET_LIBRARIES})
  	endif()
+diff --git a/build_files/cmake/platform/platform_unix.cmake b/build_files/cmake/platform/platform_unix.cmake
+index e33141f..3e3c883 100644
+--- a/build_files/cmake/platform/platform_unix.cmake
++++ b/build_files/cmake/platform/platform_unix.cmake
+@@ -132,6 +132,13 @@ if(WITH_JACK)
+ 	endif()
+ endif()
+ 
++if(WITH_FONTCONFIG)
++	find_package(Fontconfig)
++	if(NOT FONTCONFIG_FOUND)
++		set(WITH_FONTCONFIG OFF)
++	endif()
++endif()
++
+ # Codecs
+ if(WITH_CODEC_SNDFILE)
+ 	find_package_wrapper(SndFile)
 diff --git a/source/blender/blenfont/CMakeLists.txt b/source/blender/blenfont/CMakeLists.txt
 index 36ad6fe..19d2bab 100644
 --- a/source/blender/blenfont/CMakeLists.txt
@@ -152,7 +157,7 @@ index 36ad6fe..19d2bab 100644
  	add_definitions(-DWITH_PYTHON)
  	list(APPEND INC
 diff --git a/source/blender/blenfont/intern/blf_font_i18n.c b/source/blender/blenfont/intern/blf_font_i18n.c
-index b6ff7ed..a208fde 100644
+index b6ff7ed..e343c73 100644
 --- a/source/blender/blenfont/intern/blf_font_i18n.c
 +++ b/source/blender/blenfont/intern/blf_font_i18n.c
 @@ -45,10 +45,14 @@
@@ -204,10 +209,11 @@ index b6ff7ed..a208fde 100644
  	}
  
  	*r_unifont_size = unifont_size;
-@@ -92,6 +115,24 @@ unsigned char *BLF_get_unifont_mono(int *r_unifont_size)
+@@ -92,7 +115,25 @@ unsigned char *BLF_get_unifont_mono(int *r_unifont_size)
  {
  #ifdef WITH_INTERNATIONAL
  	if (unifont_mono_ttf == NULL) {
+-		const char *fontpath = BKE_appdir_folder_id(BLENDER_DATAFILES, "fonts");
 +#ifdef WITH_FONTCONFIG
 +		FcFontSet *fontset = NULL;
 +		FcValue v;
@@ -226,9 +232,10 @@ index b6ff7ed..a208fde 100644
 +			printf("%s: 'Dejavu Sans Mono' font not found with fontconfig\n", __func__);
 +		}
 +#else
- 		const char *fontpath = BKE_appdir_folder_id(BLENDER_DATAFILES, "fonts");
++       	const char *fontpath = BKE_appdir_folder_id(BLENDER_DATAFILES, "fonts");
  		if (fontpath) {
  			char unifont_path[1024];
+ 
 @@ -103,6 +144,7 @@ unsigned char *BLF_get_unifont_mono(int *r_unifont_size)
  		else {
  			printf("%s: 'fonts' data path not found for international monospace font, continuing\n", __func__);
@@ -304,10 +311,10 @@ index db4b3bc..dc240ee 100644
   * Returns true if the file with the specified name can be written.
   * This implementation uses access(2), which makes the check according
 diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index 5a84745..e1e72d2 100644
+index 69e53b3..7421477 100644
 --- a/source/creator/CMakeLists.txt
 +++ b/source/creator/CMakeLists.txt
-@@ -341,12 +341,6 @@ endif()
+@@ -369,12 +369,6 @@ endif()
  
  # localization
  if(WITH_INTERNATIONAL)
diff --git a/debian/patches/0007-fix_FTBFS_on_armel.patch b/debian/patches/0007-fix_FTBFS_on_armel.patch
deleted file mode 100644
index f87b2f6..0000000
--- a/debian/patches/0007-fix_FTBFS_on_armel.patch
+++ /dev/null
@@ -1,33 +0,0 @@
-From: Sergey Sharybin <sergey at blender.org>
-Date: Fri, 29 Apr 2016 09:43:58 +0200
-Subject: fix_FTBFS_on_armel
-
----
- intern/atomic/atomic_ops.h | 7 +++++++
- 1 file changed, 7 insertions(+)
-
-diff --git a/intern/atomic/atomic_ops.h b/intern/atomic/atomic_ops.h
-index dc06a51..06eb8f2 100644
---- a/intern/atomic/atomic_ops.h
-+++ b/intern/atomic/atomic_ops.h
-@@ -45,6 +45,7 @@
-  * arm7 architecture does have both 32 and 64bit atomics, however
-  * it's gcc doesn't have __GCC_HAVE_SYNC_COMPARE_AND_SWAP_n defined.
-  */
-+#  define JE_FORCE_SYNC_COMPARE_AND_SWAP_1
- #  define JE_FORCE_SYNC_COMPARE_AND_SWAP_8
- #  define JE_FORCE_SYNC_COMPARE_AND_SWAP_4
- #endif
-@@ -399,6 +400,12 @@ atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
- 	return _InterlockedAnd8((char *)p, (char)b);
- #endif
- }
-+#elif defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_1)
-+ATOMIC_INLINE uint8_t
-+atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
-+{
-+	return __sync_fetch_and_and(p, b);
-+}
- #else
- #  error "Missing implementation for 8-bit atomic operations"
- #endif
diff --git a/debian/patches/0009-fix_OpenJPEG2_build.patch b/debian/patches/0007-fix_OpenJPEG2_build.patch
similarity index 97%
rename from debian/patches/0009-fix_OpenJPEG2_build.patch
rename to debian/patches/0007-fix_OpenJPEG2_build.patch
index b7a10be..1b62c06 100644
--- a/debian/patches/0009-fix_OpenJPEG2_build.patch
+++ b/debian/patches/0007-fix_OpenJPEG2_build.patch
@@ -1,96 +1,85 @@
-From: Campbell Barton <ideasman42 at gmail.com>
-Date: Wed, 13 Jul 2016 12:11:33 +1000
+From: Sergey Sharybin <sergey at blender.org>
+Date: Thu, 3 Nov 2016 14:18:28 +0100
 Subject: fix_OpenJPEG2_build
 
 Temp branch for quick testing.
-Keep this until OpenImageIO add support and we can add the changes back to master.
+Keep this until OpenImageIO add support and
+we can add the changes back to master.
 ---
- build_files/cmake/Modules/FindOpenJPEG.cmake |     5 +-
- extern/libopenjpeg/CMakeLists.txt            |    30 +-
- extern/libopenjpeg/bio.c                     |    93 +-
- extern/libopenjpeg/bio.h                     |    47 +-
- extern/libopenjpeg/cidx_manager.c            |   228 +-
- extern/libopenjpeg/cidx_manager.h            |    18 +-
- extern/libopenjpeg/cio.c                     |   696 +-
- extern/libopenjpeg/cio.h                     |   371 +-
- extern/libopenjpeg/dwt.c                     |   761 +-
- extern/libopenjpeg/dwt.h                     |    33 +-
- extern/libopenjpeg/event.c                   |    74 +-
- extern/libopenjpeg/event.h                   |    58 +-
- extern/libopenjpeg/fix.h                     |    64 -
- extern/libopenjpeg/function_list.c           |   119 +
- extern/libopenjpeg/function_list.h           |   131 +
- extern/libopenjpeg/image.c                   |   166 +-
- extern/libopenjpeg/image.h                   |    28 +-
- extern/libopenjpeg/indexbox_manager.h        |    44 +-
- extern/libopenjpeg/int.h                     |   119 -
- extern/libopenjpeg/invert.c                  |   294 +
- extern/libopenjpeg/invert.h                  |    64 +
- extern/libopenjpeg/j2k.c                     | 12341 ++++++++++++++++++++-----
- extern/libopenjpeg/j2k.h                     |   804 +-
- extern/libopenjpeg/j2k_lib.c                 |    59 -
- extern/libopenjpeg/j2k_lib.h                 |    54 -
- extern/libopenjpeg/jp2.c                     |  3260 +++++--
- extern/libopenjpeg/jp2.h                     |   485 +-
- extern/libopenjpeg/jpt.c                     |   155 -
- extern/libopenjpeg/jpt.h                     |    75 -
- extern/libopenjpeg/license.txt               |    30 -
- extern/libopenjpeg/mct.c                     |   249 +-
- extern/libopenjpeg/mct.h                     |    75 +-
- extern/libopenjpeg/mqc.c                     |   230 +-
- extern/libopenjpeg/mqc.h                     |    67 +-
- extern/libopenjpeg/openjpeg.c                |   951 +-
- extern/libopenjpeg/openjpeg.h                |  1285 ++-
- extern/libopenjpeg/opj_clock.c               |    64 +
- extern/libopenjpeg/opj_clock.h               |    59 +
- extern/libopenjpeg/opj_codec.h               |   165 +
- extern/libopenjpeg/opj_config.h              |    41 +-
- extern/libopenjpeg/opj_config_private.h      |     6 +
- extern/libopenjpeg/opj_includes.h            |    88 +-
- extern/libopenjpeg/opj_intmath.h             |   178 +
- extern/libopenjpeg/opj_inttypes.h            |    48 +
- extern/libopenjpeg/opj_malloc.h              |    20 +
- extern/libopenjpeg/opj_stdint.h              |    52 +
- extern/libopenjpeg/phix_manager.c            |   113 +-
- extern/libopenjpeg/pi.c                      |  2057 +++--
- extern/libopenjpeg/pi.h                      |   166 +-
- extern/libopenjpeg/ppix_manager.c            |   113 +-
- extern/libopenjpeg/raw.c                     |    28 +-
- extern/libopenjpeg/raw.h                     |    36 +-
- extern/libopenjpeg/t1.c                      |  2189 +++--
- extern/libopenjpeg/t1.h                      |    70 +-
- extern/libopenjpeg/t1_generate_luts.c        |   282 +
- extern/libopenjpeg/t1_luts.h                 |    14 +-
- extern/libopenjpeg/t2.c                      |  1947 ++--
- extern/libopenjpeg/t2.h                      |    86 +-
- extern/libopenjpeg/tcd.c                     |  3501 ++++---
- extern/libopenjpeg/tcd.h                     |   354 +-
- extern/libopenjpeg/tgt.c                     |   456 +-
- extern/libopenjpeg/tgt.h                     |    68 +-
- extern/libopenjpeg/thix_manager.c            |   102 +-
- extern/libopenjpeg/tpix_manager.c            |   164 +-
- source/blender/imbuf/intern/IMB_filetype.h   |     5 +-
- source/blender/imbuf/intern/filetype.c       |     2 +-
- source/blender/imbuf/intern/jp2.c            |   494 +-
- 67 files changed, 26500 insertions(+), 10031 deletions(-)
- delete mode 100644 extern/libopenjpeg/fix.h
+ build_files/cmake/Modules/FindOpenJPEG.cmake       |     5 +-
+ extern/libopenjpeg/CMakeLists.txt                  |    30 +-
+ extern/libopenjpeg/bio.c                           |    95 +-
+ extern/libopenjpeg/bio.h                           |    47 +-
+ extern/libopenjpeg/cidx_manager.c                  |   228 +-
+ extern/libopenjpeg/cidx_manager.h                  |    18 +-
+ extern/libopenjpeg/cio.c                           |   704 +-
+ extern/libopenjpeg/cio.h                           |   378 +-
+ extern/libopenjpeg/dwt.c                           |   761 +-
+ extern/libopenjpeg/dwt.h                           |    33 +-
+ extern/libopenjpeg/event.c                         |    75 +-
+ extern/libopenjpeg/event.h                         |    58 +-
+ extern/libopenjpeg/function_list.c                 |   119 +
+ extern/libopenjpeg/function_list.h                 |   131 +
+ extern/libopenjpeg/image.c                         |   163 +-
+ extern/libopenjpeg/image.h                         |    28 +-
+ extern/libopenjpeg/indexbox_manager.h              |    44 +-
+ extern/libopenjpeg/invert.c                        |   294 +
+ extern/libopenjpeg/{jpt.h => invert.h}             |    71 +-
+ extern/libopenjpeg/j2k.c                           | 12514 +++++++++++++++----
+ extern/libopenjpeg/j2k.h                           |   804 +-
+ extern/libopenjpeg/jp2.c                           |  3331 +++--
+ extern/libopenjpeg/jp2.h                           |   485 +-
+ extern/libopenjpeg/jpt.c                           |   155 -
+ extern/libopenjpeg/mct.c                           |   249 +-
+ extern/libopenjpeg/mct.h                           |    75 +-
+ extern/libopenjpeg/mqc.c                           |   230 +-
+ extern/libopenjpeg/mqc.h                           |    67 +-
+ extern/libopenjpeg/openjpeg.c                      |   951 +-
+ extern/libopenjpeg/openjpeg.h                      |  1289 +-
+ extern/libopenjpeg/{j2k_lib.c => opj_clock.c}      |    15 +-
+ extern/libopenjpeg/{j2k_lib.h => opj_clock.h}      |    19 +-
+ extern/libopenjpeg/opj_codec.h                     |   165 +
+ extern/libopenjpeg/opj_config.h                    |    42 +-
+ extern/libopenjpeg/opj_config_private.h            |     6 +
+ extern/libopenjpeg/opj_includes.h                  |    99 +-
+ extern/libopenjpeg/{int.h => opj_intmath.h}        |    91 +-
+ extern/libopenjpeg/{license.txt => opj_inttypes.h} |    32 +-
+ extern/libopenjpeg/opj_malloc.h                    |    20 +
+ extern/libopenjpeg/{fix.h => opj_stdint.h}         |    60 +-
+ extern/libopenjpeg/phix_manager.c                  |   113 +-
+ extern/libopenjpeg/pi.c                            |  2057 ++-
+ extern/libopenjpeg/pi.h                            |   166 +-
+ extern/libopenjpeg/ppix_manager.c                  |   113 +-
+ extern/libopenjpeg/raw.c                           |    28 +-
+ extern/libopenjpeg/raw.h                           |    36 +-
+ extern/libopenjpeg/t1.c                            |  2190 ++--
+ extern/libopenjpeg/t1.h                            |    70 +-
+ extern/libopenjpeg/t1_generate_luts.c              |   282 +
+ extern/libopenjpeg/t1_luts.h                       |    14 +-
+ extern/libopenjpeg/t2.c                            |  1973 +--
+ extern/libopenjpeg/t2.h                            |    86 +-
+ extern/libopenjpeg/tcd.c                           |  3568 +++---
+ extern/libopenjpeg/tcd.h                           |   354 +-
+ extern/libopenjpeg/tgt.c                           |   456 +-
+ extern/libopenjpeg/tgt.h                           |    68 +-
+ extern/libopenjpeg/thix_manager.c                  |   102 +-
+ extern/libopenjpeg/tpix_manager.c                  |   164 +-
+ source/blender/imbuf/intern/IMB_filetype.h         |     5 +-
+ source/blender/imbuf/intern/filetype.c             |     2 +-
+ source/blender/imbuf/intern/jp2.c                  |   494 +-
+ 61 files changed, 26191 insertions(+), 10131 deletions(-)
  create mode 100644 extern/libopenjpeg/function_list.c
  create mode 100644 extern/libopenjpeg/function_list.h
- delete mode 100644 extern/libopenjpeg/int.h
  create mode 100644 extern/libopenjpeg/invert.c
- create mode 100644 extern/libopenjpeg/invert.h
- delete mode 100644 extern/libopenjpeg/j2k_lib.c
- delete mode 100644 extern/libopenjpeg/j2k_lib.h
+ rename extern/libopenjpeg/{jpt.h => invert.h} (50%)
  delete mode 100644 extern/libopenjpeg/jpt.c
- delete mode 100644 extern/libopenjpeg/jpt.h
- delete mode 100644 extern/libopenjpeg/license.txt
- create mode 100644 extern/libopenjpeg/opj_clock.c
- create mode 100644 extern/libopenjpeg/opj_clock.h
+ rename extern/libopenjpeg/{j2k_lib.c => opj_clock.c} (80%)
+ rename extern/libopenjpeg/{j2k_lib.h => opj_clock.h} (78%)
  create mode 100644 extern/libopenjpeg/opj_codec.h
  create mode 100644 extern/libopenjpeg/opj_config_private.h
- create mode 100644 extern/libopenjpeg/opj_intmath.h
- create mode 100644 extern/libopenjpeg/opj_inttypes.h
- create mode 100644 extern/libopenjpeg/opj_stdint.h
+ rename extern/libopenjpeg/{int.h => opj_intmath.h} (54%)
+ rename extern/libopenjpeg/{license.txt => opj_inttypes.h} (66%)
+ rename extern/libopenjpeg/{fix.h => opj_stdint.h} (56%)
  create mode 100644 extern/libopenjpeg/t1_generate_luts.c
 
 diff --git a/build_files/cmake/Modules/FindOpenJPEG.cmake b/build_files/cmake/Modules/FindOpenJPEG.cmake
@@ -196,7 +185,7 @@ index ad49eee..0af2a90 100644
  
  blender_add_lib(extern_openjpeg "${SRC}" "${INC}" "${INC_SYS}")
 diff --git a/extern/libopenjpeg/bio.c b/extern/libopenjpeg/bio.c
-index 4c02f46..5d49580 100644
+index f04f3e5..5d49580 100644
 --- a/extern/libopenjpeg/bio.c
 +++ b/extern/libopenjpeg/bio.c
 @@ -1,9 +1,15 @@
@@ -222,7 +211,7 @@ index 4c02f46..5d49580 100644
  @param bio BIO handle
  @param b Bit to write (0 or 1)
  */
--static void bio_putbit(opj_bio_t *bio, int b);
+-static void bio_putbit(opj_bio_t *bio, unsigned int b);
 +static void opj_bio_putbit(opj_bio_t *bio, OPJ_UINT32 b);
  /**
  Read a bit
@@ -262,7 +251,7 @@ index 4c02f46..5d49580 100644
 -		return 1;
 +		return OPJ_FALSE;
  	}
--	*bio->bp++ = bio->buf >> 8;
+-	*bio->bp++ = (unsigned char)(bio->buf >> 8);
 -	return 0;
 +	*bio->bp++ = (OPJ_BYTE)(bio->buf >> 8);
 +	return OPJ_TRUE;
@@ -281,7 +270,7 @@ index 4c02f46..5d49580 100644
 +	return OPJ_TRUE;
  }
  
--static void bio_putbit(opj_bio_t *bio, int b) {
+-static void bio_putbit(opj_bio_t *bio, unsigned int b) {
 +void opj_bio_putbit(opj_bio_t *bio, OPJ_UINT32 b) {
  	if (bio->ct == 0) {
 -		bio_byteout(bio);
@@ -317,8 +306,9 @@ index 4c02f46..5d49580 100644
  }
  
 -int bio_numbytes(opj_bio_t *bio) {
+-	return (int)(bio->bp - bio->start);
 +ptrdiff_t opj_bio_numbytes(opj_bio_t *bio) {
- 	return (bio->bp - bio->start);
++	return (bio->bp - bio->start);
  }
  
 -void bio_init_enc(opj_bio_t *bio, unsigned char *bp, int len) {
@@ -523,7 +513,7 @@ index 764d7cb..fba2428 100644
  /*@}*/
  
 diff --git a/extern/libopenjpeg/cidx_manager.c b/extern/libopenjpeg/cidx_manager.c
-index 6131b93..14f2d9c 100644
+index f3b251f..ff2dbda 100644
 --- a/extern/libopenjpeg/cidx_manager.c
 +++ b/extern/libopenjpeg/cidx_manager.c
 @@ -1,8 +1,8 @@
@@ -537,7 +527,7 @@ index 6131b93..14f2d9c 100644
   * Copyright (c) 2003-2004, Yannick Verschueren
   * Copyright (c) 2010-2011, Kaori Hagihara
   * All rights reserved.
-@@ -41,39 +41,24 @@
+@@ -39,39 +39,24 @@
   * @param[in] clen length of j2k codestream
   * @param[in] cio  file output handle
   */
@@ -586,7 +576,7 @@ index 6131b93..14f2d9c 100644
  
    lenp = -1;
    box = (opj_jp2_box_t *)opj_calloc( 32, sizeof(opj_jp2_box_t));
-@@ -81,133 +66,176 @@ int write_cidx( int offset, opj_cio_t *cio, opj_image_t *image, opj_codestream_i
+@@ -79,133 +64,176 @@ int write_cidx( int offset, opj_cio_t *cio, opj_image_t *image, opj_codestream_i
    for (i=0;i<2;i++){
    
      if(i)
@@ -874,7 +864,7 @@ index 23eebd5..d0bbef8 100644
  
  #endif      /* !CIDX_MANAGER_H_ */
 diff --git a/extern/libopenjpeg/cio.c b/extern/libopenjpeg/cio.c
-index b8a7ecf..1fc2393 100644
+index 97cccea..1fc2393 100644
 --- a/extern/libopenjpeg/cio.c
 +++ b/extern/libopenjpeg/cio.c
 @@ -1,10 +1,18 @@
@@ -899,7 +889,11 @@ index b8a7ecf..1fc2393 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -33,159 +41,605 @@
+@@ -30,170 +38,608 @@
+  */
+ 
+ #include "opj_includes.h"
+-#include <assert.h>
  
  /* ----------------------------------------------------------------------- */
  
@@ -1135,6 +1129,7 @@ index b8a7ecf..1fc2393 100644
 - * pos : position, in number of bytes, from the beginning of the stream
 - */
 -void OPJ_CALLCONV cio_seek(opj_cio_t *cio, int pos) {
+-  assert((cio->start + pos) <= cio->end);
 -	cio->bp = cio->start + pos;
 +void OPJ_CALLCONV opj_stream_set_seek_function(opj_stream_t* p_stream, opj_stream_seek_fn p_function)
 +{
@@ -1150,6 +1145,7 @@ index b8a7ecf..1fc2393 100644
 - * Number of bytes left before the end of the stream.
 - */
 -int cio_numbytesleft(opj_cio_t *cio) {
+-  assert((cio->end - cio->bp) >= 0);
 -	return cio->end - cio->bp;
 +void OPJ_CALLCONV opj_stream_set_write_function(opj_stream_t* p_stream, opj_stream_write_fn p_function)
 +{
@@ -1391,6 +1387,7 @@ index b8a7ecf..1fc2393 100644
 - * Read a byte.
 - */
 -unsigned char cio_bytein(opj_cio_t *cio) {
+-  assert(cio->bp >= cio->start);
 -	if (cio->bp >= cio->end) {
 -		opj_event_msg(cio->cinfo, EVT_ERROR, "read error: passed the end of the codestream (start = %d, current = %d, end = %d\n", cio->start, cio->bp, cio->end);
 -		return 0;
@@ -1455,7 +1452,7 @@ index b8a7ecf..1fc2393 100644
 - * v : value to write
 - * n : number of bytes to write
 - */
--unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n) {
+-unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n) {
 -	int i;
 -	for (i = n - 1; i >= 0; i--) {
 -		if( !cio_byteout(cio, (unsigned char) ((v >> (i << 3)) & 0xff)) )
@@ -1513,7 +1510,7 @@ index b8a7ecf..1fc2393 100644
 -	unsigned int v;
 -	v = 0;
 -	for (i = n - 1; i >= 0; i--) {
--		v += cio_bytein(cio) << (i << 3);
+-		v += (unsigned int)cio_bytein(cio) << (i << 3);
 +OPJ_OFF_T opj_stream_tell (const opj_stream_private_t * p_stream)
 +{
 +	return p_stream->m_byte_offset;
@@ -1582,6 +1579,10 @@ index b8a7ecf..1fc2393 100644
 - * n : number of bytes to skip
 - */
 -void cio_skip(opj_cio_t *cio, int n) {
+-  assert((cio->bp + n) >= cio->bp);
+-  if (((cio->bp + n) < cio->start) || ((cio->bp + n) > cio->end)) {
+-    assert(0);
+-  }
 -	cio->bp += n;
 +OPJ_BOOL opj_stream_seek (opj_stream_private_t * p_stream, OPJ_OFF_T p_size, struct opj_event_mgr * p_event_mgr)
 +{
@@ -1624,7 +1625,7 @@ index b8a7ecf..1fc2393 100644
 +	return OPJ_FALSE;
 +}
 diff --git a/extern/libopenjpeg/cio.h b/extern/libopenjpeg/cio.h
-index ce1a13e..6dfa5bb 100644
+index e627431..6dfa5bb 100644
 --- a/extern/libopenjpeg/cio.h
 +++ b/extern/libopenjpeg/cio.h
 @@ -1,10 +1,18 @@
@@ -1649,7 +1650,21 @@ index ce1a13e..6dfa5bb 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -41,46 +49,351 @@ The functions in CIO.C have for goal to realize a byte input / output process.
+@@ -31,13 +39,6 @@
+ 
+ #ifndef __CIO_H
+ #define __CIO_H
+-
+-#if defined(_MSC_VER) || defined(__BORLANDC__)
+-#define int64 __int64
+-#else
+-#define int64 long long
+-#endif
+-
+ /**
+ @file cio.h
+ @brief Implementation of a byte input-output process (CIO)
+@@ -48,46 +49,351 @@ The functions in CIO.C have for goal to realize a byte input / output process.
  /** @defgroup CIO CIO - byte input-output stream */
  /*@{*/
  
@@ -1813,7 +1828,7 @@ index ce1a13e..6dfa5bb 100644
 + * @param p_nb_bytes	the number of bytes to write
 + * @return				the number of bytes written or -1 if an error occured
  */
--unsigned int cio_write(opj_cio_t *cio, unsigned long long int v, int n);
+-unsigned int cio_write(opj_cio_t *cio, unsigned int64 v, int n);
 +void opj_write_bytes_LE (OPJ_BYTE * p_buffer, OPJ_UINT32 p_value, OPJ_UINT32 p_nb_bytes);
 +
  /**
@@ -3289,7 +3304,7 @@ index adf73e5..f8b57bc 100644
  /*@}*/
  
 diff --git a/extern/libopenjpeg/event.c b/extern/libopenjpeg/event.c
-index 0dc22f1..b6034b4 100644
+index 38db33a..b6034b4 100644
 --- a/extern/libopenjpeg/event.c
 +++ b/extern/libopenjpeg/event.c
 @@ -1,5 +1,12 @@
@@ -3305,7 +3320,7 @@ index 0dc22f1..b6034b4 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -60,63 +67,80 @@ _itoa(int i, char *a, int r) {
+@@ -60,62 +67,80 @@ _itoa(int i, char *a, int r) {
  
  #endif /* !_WIN32 */
  #endif
@@ -3377,24 +3392,24 @@ index 0dc22f1..b6034b4 100644
  		va_list arg;
 -		int str_length/*, i, j*/; /* UniPG */
 -		char message[MSG_SIZE];
--		memset(message, 0, MSG_SIZE);
 +		size_t str_length/*, i, j*/; /* UniPG */
 +		char message[OPJ_MSG_SIZE];
 +		memset(message, 0, OPJ_MSG_SIZE);
  		/* initialize the optional parameter list */
  		va_start(arg, fmt);
- 		/* check the length of the format string */
--		str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt);
++		/* check the length of the format string */
 +		str_length = (strlen(fmt) > OPJ_MSG_SIZE) ? OPJ_MSG_SIZE : strlen(fmt);
 +        (void)str_length;
  		/* parse the format string and put the result in 'message' */
--		vsprintf(message, fmt, arg); /* UniPG */
+-		str_length = vsnprintf(message, MSG_SIZE, fmt, arg); /* UniPG */
 +		vsnprintf(message, OPJ_MSG_SIZE, fmt, arg); /* UniPG */
  		/* deinitialize the optional parameter list */
  		va_end(arg);
  
  		/* output the message to the user program */
--		msg_handler(message, cinfo->client_data);
+-    if( str_length > -1 && str_length < MSG_SIZE )
+-      msg_handler(message, cinfo->client_data);
+-    else return OPJ_FALSE;
 +		msg_handler(message, l_data);
  	}
  
@@ -3495,76 +3510,6 @@ index 9c59787..88e0395 100644
  /*@}*/
  
  /*@}*/
-diff --git a/extern/libopenjpeg/fix.h b/extern/libopenjpeg/fix.h
-deleted file mode 100644
-index bcb2acb..0000000
---- a/extern/libopenjpeg/fix.h
-+++ /dev/null
-@@ -1,64 +0,0 @@
--/*
-- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
-- * Copyright (c) 2002-2007, Professor Benoit Macq
-- * Copyright (c) 2001-2003, David Janssens
-- * Copyright (c) 2002-2003, Yannick Verschueren
-- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
--#ifndef __FIX_H
--#define __FIX_H
--
--#if defined(_MSC_VER) || defined(__BORLANDC__)
--#define int64 __int64
--#else
--#define int64 long long
--#endif
--
--/**
-- at file fix.h
-- at brief Implementation of operations of specific multiplication (FIX)
--
--The functions in FIX.H have for goal to realize specific multiplication.
--*/
--
--/** @defgroup FIX FIX - Implementation of operations of specific multiplication */
--/*@{*/
--
--/**
--Multiply two fixed-precision rational numbers.
-- at param a
-- at param b
-- at return Returns a * b
--*/
--static INLINE int fix_mul(int a, int b) {
--    int64 temp = (int64) a * (int64) b ;
--    temp += temp & 4096;
--    return (int) (temp >> 13) ;
--}
--
--/*@}*/
--
--#endif /* __FIX_H */
 diff --git a/extern/libopenjpeg/function_list.c b/extern/libopenjpeg/function_list.c
 new file mode 100644
 index 0000000..4c8aae6
@@ -3828,7 +3773,7 @@ index 0000000..749ad9e
 +#endif /* __FUNCTION_LIST_H */
 +
 diff --git a/extern/libopenjpeg/image.c b/extern/libopenjpeg/image.c
-index 7c1e7f7..2c3540c 100644
+index 579fd73..2c3540c 100644
 --- a/extern/libopenjpeg/image.c
 +++ b/extern/libopenjpeg/image.c
 @@ -1,4 +1,9 @@
@@ -3852,15 +3797,6 @@ index 7c1e7f7..2c3540c 100644
  	opj_image_t *image = NULL;
  
  	image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t));
-@@ -40,7 +45,7 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
- 		image->color_space = clrspc;
- 		image->numcomps = numcmpts;
- 		/* allocate memory for the per-component information */
--		image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(opj_image_comp_t));
-+		image->comps = (opj_image_comp_t*)opj_calloc(1,image->numcomps * sizeof(opj_image_comp_t));
- 		if(!image->comps) {
- 			fprintf(stderr,"Unable to allocate memory for image.\n");
- 			opj_image_destroy(image);
 @@ -58,7 +63,7 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
  			comp->prec = cmptparms[compno].prec;
  			comp->bpp = cmptparms[compno].bpp;
@@ -3870,7 +3806,7 @@ index 7c1e7f7..2c3540c 100644
  			if(!comp->data) {
  				fprintf(stderr,"Unable to allocate memory for image.\n");
  				opj_image_destroy(image);
-@@ -71,18 +76,165 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
+@@ -71,19 +76,165 @@ opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *c
  }
  
  void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) {
@@ -3898,7 +3834,7 @@ index 7c1e7f7..2c3540c 100644
  		opj_free(image);
  	}
  }
-+
+ 
 +/**
 + * Updates the components characteristics of the image from the coding parameters.
 + *
@@ -4179,131 +4115,6 @@ index 7364df6..ec5525f 100644
 +              opj_event_mgr_t * p_manager );
  
  #endif      /* !INDEXBOX_MANAGER_H_ */
-diff --git a/extern/libopenjpeg/int.h b/extern/libopenjpeg/int.h
-deleted file mode 100644
-index 4e5fe08..0000000
---- a/extern/libopenjpeg/int.h
-+++ /dev/null
-@@ -1,119 +0,0 @@
--/*
-- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
-- * Copyright (c) 2002-2007, Professor Benoit Macq
-- * Copyright (c) 2001-2003, David Janssens
-- * Copyright (c) 2002-2003, Yannick Verschueren
-- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
--#ifndef __INT_H
--#define __INT_H
--/**
-- at file int.h
-- at brief Implementation of operations on integers (INT)
--
--The functions in INT.H have for goal to realize operations on integers.
--*/
--
--/** @defgroup INT INT - Implementation of operations on integers */
--/*@{*/
--
--/** @name Exported functions (see also openjpeg.h) */
--/*@{*/
--/* ----------------------------------------------------------------------- */
--/**
--Get the minimum of two integers
-- at return Returns a if a < b else b
--*/
--static INLINE int int_min(int a, int b) {
--	return a < b ? a : b;
--}
--/**
--Get the maximum of two integers
-- at return Returns a if a > b else b
--*/
--static INLINE int int_max(int a, int b) {
--	return (a > b) ? a : b;
--}
--/**
--Clamp an integer inside an interval
-- at return
--<ul>
--<li>Returns a if (min < a < max)
--<li>Returns max if (a > max)
--<li>Returns min if (a < min) 
--</ul>
--*/
--static INLINE int int_clamp(int a, int min, int max) {
--	if (a < min)
--		return min;
--	if (a > max)
--		return max;
--	return a;
--}
--/**
-- at return Get absolute value of integer
--*/
--static INLINE int int_abs(int a) {
--	return a < 0 ? -a : a;
--}
--/**
--Divide an integer and round upwards
-- at return Returns a divided by b
--*/
--static INLINE int int_ceildiv(int a, int b) {
--	return (a + b - 1) / b;
--}
--/**
--Divide an integer by a power of 2 and round upwards
-- at return Returns a divided by 2^b
--*/
--static INLINE int int_ceildivpow2(int a, int b) {
--	return (a + (1 << b) - 1) >> b;
--}
--/**
--Divide an integer by a power of 2 and round downwards
-- at return Returns a divided by 2^b
--*/
--static INLINE int int_floordivpow2(int a, int b) {
--	return a >> b;
--}
--/**
--Get logarithm of an integer and round downwards
-- at return Returns log2(a)
--*/
--static INLINE int int_floorlog2(int a) {
--	int l;
--	for (l = 0; a > 1; l++) {
--		a >>= 1;
--	}
--	return l;
--}
--/* ----------------------------------------------------------------------- */
--/*@}*/
--
--/*@}*/
--
--#endif
 diff --git a/extern/libopenjpeg/invert.c b/extern/libopenjpeg/invert.c
 new file mode 100644
 index 0000000..4c1ee78
@@ -4604,59 +4415,77 @@ index 0000000..4c1ee78
 +    }
 +}
 +
-diff --git a/extern/libopenjpeg/invert.h b/extern/libopenjpeg/invert.h
-new file mode 100644
-index 0000000..2fae8e5
---- /dev/null
+diff --git a/extern/libopenjpeg/jpt.h b/extern/libopenjpeg/invert.h
+similarity index 50%
+rename from extern/libopenjpeg/jpt.h
+rename to extern/libopenjpeg/invert.h
+index eb01f98..2fae8e5 100644
+--- a/extern/libopenjpeg/jpt.h
 +++ b/extern/libopenjpeg/invert.h
-@@ -0,0 +1,64 @@
-+/*
+@@ -1,8 +1,10 @@
+ /*
+- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+- * Copyright (c) 2002-2007, Professor Benoit Macq
+- * Copyright (c) 2002-2003, Yannick Verschueren
+- * Copyright (c) 2005, Herve Drolon, FreeImage Team
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
 + * are granted under this license.
 + *
 + * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes at c-s.fr>
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
-+ */
-+
+  * All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+@@ -27,49 +29,36 @@
+  * POSSIBILITY OF SUCH DAMAGE.
+  */
+ 
+-#ifndef __JPT_H
+-#define __JPT_H
 +#ifndef __INVERT_H
 +#define __INVERT_H
-+/**
+ /**
+- at file jpt.h
+- at brief JPT-stream reader (JPEG 2000, JPIP)
 + at file invert.h
 + at brief Implementation of the matrix inversion
-+
+ 
+-JPT-stream functions are implemented in J2K.C. 
 +The function in INVERT.H compute a matrix inversion with a LUP method
-+*/
-+
+ */
+ 
+-/**
+-Message Header JPT stream structure
+-*/
+-typedef struct opj_jpt_msg_header {
+-	/** In-class Identifier */
+-	unsigned int Id;
+-	/** Last byte information */
+-	unsigned int last_byte;	
+-	/** Class Identifier */
+-	unsigned int Class_Id;	
+-	/** CSn : index identifier */
+-	unsigned int CSn_Id;
+-	/** Message offset */
+-	unsigned int Msg_offset;
+-	/** Message length */
+-	unsigned int Msg_length;
+-	/** Auxiliary for JPP case */
+-	unsigned int Layer_nb;
+-} opj_jpt_msg_header_t;
+-
 +/** @defgroup INVERT INVERT - Implementation of a matrix inversion */
 +/*@{*/
 +/** @name Exported functions */
 +/*@{*/
-+/* ----------------------------------------------------------------------- */
-+
-+/**
+ /* ----------------------------------------------------------------------- */
+ 
+ /**
+-Initialize the value of the message header structure 
+- at param header Message header structure
+-*/
+-void jpt_init_msg_header(opj_jpt_msg_header_t * header);
 + * Calculates a n x n double matrix inversion with a LUP method. Data is aligned, rows after rows (or columns after columns).
 + * The function does not take ownership of any memory block, data must be fred by the user.
 + *
@@ -4670,12 +4499,20 @@ index 0000000..2fae8e5
 +                                OPJ_UINT32 nb_compo);
 +/* ----------------------------------------------------------------------- */
 +/*@}*/
-+
+ 
+-/**
+-Read the message header for a JPP/JPT - stream
+- at param cinfo Codec context info
+- at param cio CIO handle
+- at param header Message header structure
+-*/
+-void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header);
 +/*@}*/
-+
+ 
+-#endif
 +#endif /* __INVERT_H */ 
 diff --git a/extern/libopenjpeg/j2k.c b/extern/libopenjpeg/j2k.c
-index d34c75f..881cc72 100644
+index 93e5c9e..881cc72 100644
 --- a/extern/libopenjpeg/j2k.c
 +++ b/extern/libopenjpeg/j2k.c
 @@ -1,12 +1,21 @@
@@ -4703,7 +4540,15 @@ index d34c75f..881cc72 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -40,2495 +49,10265 @@
+@@ -32,7 +41,6 @@
+  */
+ 
+ #include "opj_includes.h"
+-#include <assert.h>
+ 
+ /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
+ /*@{*/
+@@ -41,2659 +49,10265 @@
  /*@{*/
  
  /**
@@ -11734,25 +11579,18 @@ index d34c75f..881cc72 100644
 +        l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
 +#endif
 +        l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
- 
--/*@}*/
++
 +        /* POINTER validation */
 +        /* make sure a p_j2k codec is present */
 +        /* make sure a procedure list is present */
 +        l_is_valid &= (p_j2k->m_procedure_list != 00);
 +        /* make sure a validation list is present */
 +        l_is_valid &= (p_j2k->m_validation_list != 00);
- 
--/*@}*/
++
 +        /* PARAMETER VALIDATION */
 +        return l_is_valid;
 +}
- 
--/* ----------------------------------------------------------------------- */
--typedef struct j2k_prog_order{
--	OPJ_PROG_ORDER enum_prog;
--	char str_prog[5];
--}j2k_prog_order_t;
++
 +OPJ_BOOL opj_j2k_read_header_procedure( opj_j2k_t *p_j2k,
 +                                                                            opj_stream_private_t *p_stream,
 +                                                                            opj_event_mgr_t * p_manager)
@@ -11881,15 +11719,7 @@ index d34c75f..881cc72 100644
 +
 +        return OPJ_TRUE;
 +}
- 
--j2k_prog_order_t j2k_prog_order_list[] = {
--	{CPRL, "CPRL"},
--	{LRCP, "LRCP"},
--	{PCRL, "PCRL"},
--	{RLCP, "RLCP"},
--	{RPCL, "RPCL"},
--	{(OPJ_PROG_ORDER)-1, ""}
--};
++
 +OPJ_BOOL opj_j2k_exec ( opj_j2k_t * p_j2k,
 +                                        opj_procedure_list_t * p_procedure_list,
 +                                        opj_stream_private_t *p_stream,
@@ -11917,15 +11747,7 @@ index d34c75f..881cc72 100644
 +        opj_procedure_list_clear(p_procedure_list);
 +        return l_result;
 +}
- 
--char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
--	j2k_prog_order_t *po;
--	for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
--		if(po->enum_prog == prg_order){
--			break;
--		}
--	}
--	return po->str_prog;
++
 +/* FIXME DOC*/
 +static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd (       opj_j2k_t * p_j2k,
 +                                                            opj_stream_private_t *p_stream,
@@ -12054,72 +11876,8 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        return OPJ_TRUE;
- }
- 
--/* ----------------------------------------------------------------------- */
--static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){
--	char *prog;
--	int i;
--	int tpnum=1,tpend=0;
--	opj_tcp_t *tcp = &cp->tcps[tileno];
--	prog = j2k_convert_progression_order(tcp->prg);
--	
--	if(cp->tp_on == 1){
--		for(i=0;i<4;i++){
--			if(tpend!=1){
--				if( cp->tp_flag == prog[i] ){
--					tpend=1;cp->tp_pos=i;
--				}
--				switch(prog[i]){
--				case 'C':
--					tpnum= tpnum * tcp->pocs[pino].compE;
--					break;
--				case 'R':
--					tpnum= tpnum * tcp->pocs[pino].resE;
--					break;
--				case 'P':
--					tpnum= tpnum * tcp->pocs[pino].prcE;
--					break;
--				case 'L':
--					tpnum= tpnum * tcp->pocs[pino].layE;
--					break;
--				}
--			}
--		}
--	}else{
--		tpnum=1;
--	}
--	return tpnum;
--}
--
--/**	mem allocation for TLM marker*/
--int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){
--	int pino,tileno,totnum_tp=0;
--
--	OPJ_ARG_NOT_USED(img_numcomp);
--
--	j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int));
--	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
--		int cur_totnum_tp = 0;
--		opj_tcp_t *tcp = &cp->tcps[tileno];
--		for(pino = 0; pino <= tcp->numpocs; pino++) {
--			int tp_num=0;
--			opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS);
--			if(!pi) { return -1;}
--			tp_num = j2k_get_num_tp(cp,pino,tileno);
--			totnum_tp = totnum_tp + tp_num;
--			cur_totnum_tp = cur_totnum_tp + tp_num;
--			pi_destroy(pi, cp, tileno);
--		}
--		j2k->cur_totnum_tp[tileno] = cur_totnum_tp;
--		/* INDEX >> */
--		if (j2k->cstr_info) {
--			j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp;
--			j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
--		}
--		/* << INDEX */
--	}
--	return totnum_tp;
++}
++
 +const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler (OPJ_UINT32 p_id)
 +{
 +        const opj_dec_memory_marker_handler_t *e;
@@ -12129,34 +11887,22 @@ index d34c75f..881cc72 100644
 +                }
 +        }
 +        return e;
- }
- 
--static void j2k_write_soc(opj_j2k_t *j2k) {
--	opj_cio_t *cio = j2k->cio;
--	cio_write(cio, J2K_MS_SOC, 2);
++}
++
 +void opj_j2k_destroy (opj_j2k_t *p_j2k)
 +{
 +        if (p_j2k == 00) {
 +                return;
 +        }
- 
--	if(j2k->cstr_info)
--	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio), 0);
++
 +        if (p_j2k->m_is_decoder) {
- 
--/* UniPG>> */
--#ifdef USE_JPWL
++
 +                if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
 +                        opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
 +                        opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
 +                        p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
 +                }
- 
--	/* update markers struct */
--	j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2);
--#endif /* USE_JPWL */
--/* <<UniPG */
--}
++
 +                if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
 +                        opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
 +                        p_j2k->m_specific_param.m_decoder.m_header_data = 00;
@@ -12164,506 +11910,39 @@ index d34c75f..881cc72 100644
 +                }
 +        }
 +        else {
- 
--static void j2k_read_soc(opj_j2k_t *j2k) {	
--	j2k->state = J2K_STATE_MHSIZ;
--	/* Index */
--	if (j2k->cstr_info) {
--		j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2;
--		j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start;
--	}
--}
--
--static void j2k_write_siz(opj_j2k_t *j2k) {
--	int i;
--	int lenp, len;
--
--	opj_cio_t *cio = j2k->cio;
--	opj_image_t *image = j2k->image;
--	opj_cp_t *cp = j2k->cp;
--
--	cio_write(cio, J2K_MS_SIZ, 2);	/* SIZ */
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);
--	cio_write(cio, cp->rsiz, 2);			/* Rsiz (capabilities) */
--	cio_write(cio, image->x1, 4);	/* Xsiz */
--	cio_write(cio, image->y1, 4);	/* Ysiz */
--	cio_write(cio, image->x0, 4);	/* X0siz */
--	cio_write(cio, image->y0, 4);	/* Y0siz */
--	cio_write(cio, cp->tdx, 4);		/* XTsiz */
--	cio_write(cio, cp->tdy, 4);		/* YTsiz */
--	cio_write(cio, cp->tx0, 4);		/* XT0siz */
--	cio_write(cio, cp->ty0, 4);		/* YT0siz */
--	cio_write(cio, image->numcomps, 2);	/* Csiz */
--	for (i = 0; i < image->numcomps; i++) {
--		cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1);	/* Ssiz_i */
--		cio_write(cio, image->comps[i].dx, 1);	/* XRsiz_i */
--		cio_write(cio, image->comps[i].dy, 1);	/* YRsiz_i */
--	}
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);		/* Lsiz */
--	cio_seek(cio, lenp + len);
--	
--	if(j2k->cstr_info)
--	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SIZ, lenp, len);
--}
--
--static void j2k_read_siz(opj_j2k_t *j2k) {
--	int len, i;
--	
--	opj_cio_t *cio = j2k->cio;
--	opj_image_t *image = j2k->image;
--	opj_cp_t *cp = j2k->cp;
--	
--	len = cio_read(cio, 2);			/* Lsiz */
--	cio_read(cio, 2);				/* Rsiz (capabilities) */
--	image->x1 = cio_read(cio, 4);	/* Xsiz */
--	image->y1 = cio_read(cio, 4);	/* Ysiz */
--	image->x0 = cio_read(cio, 4);	/* X0siz */
--	image->y0 = cio_read(cio, 4);	/* Y0siz */
--	cp->tdx = cio_read(cio, 4);		/* XTsiz */
--	cp->tdy = cio_read(cio, 4);		/* YTsiz */
--	cp->tx0 = cio_read(cio, 4);		/* XT0siz */
--	cp->ty0 = cio_read(cio, 4);		/* YT0siz */
--	
--	if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
--		opj_event_msg(j2k->cinfo, EVT_ERROR,
--									"%s: invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
--									image->x0,image->x1,image->y0,image->y1);
--		return;
--	}
--	
--	image->numcomps = cio_read(cio, 2);	/* Csiz */
++
 +                if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
 +                        opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
 +                        p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
 +                }
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--		/* if JPWL is on, we check whether TX errors have damaged
--		  too much the SIZ parameters */
--		if (!(image->x1 * image->y1)) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"JPWL: bad image size (%d x %d)\n",
--				image->x1, image->y1);
--			if (!JPWL_ASSUME || JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--		}
--		if (image->numcomps != ((len - 38) / 3)) {
--			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
--				"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
--				image->numcomps, ((len - 38) / 3));
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n");
--			if (image->numcomps < ((len - 38) / 3)) {
--				len = 38 + 3 * image->numcomps;
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
--					len);				
--			} else {
--				image->numcomps = ((len - 38) / 3);
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
--					image->numcomps);				
--			}
--		}
++
 +                if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
 +                        opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
 +                        p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
 +                        p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
 +                }
- 
--		/* update components number in the jpwl_exp_comps filed */
--		cp->exp_comps = image->numcomps;
--	}
--#endif /* USE_JPWL */
++
 +                if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
 +                        opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
 +                        p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
 +                        p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
 +                }
 +        }
- 
--	image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
--	for (i = 0; i < image->numcomps; i++) {
--		int tmp, w, h;
--		tmp = cio_read(cio, 1);		/* Ssiz_i */
--		image->comps[i].prec = (tmp & 0x7f) + 1;
--		image->comps[i].sgnd = tmp >> 7;
--		image->comps[i].dx = cio_read(cio, 1);	/* XRsiz_i */
--		image->comps[i].dy = cio_read(cio, 1);	/* YRsiz_i */
--		
--#ifdef USE_JPWL
--		if (j2k->cp->correct) {
--		/* if JPWL is on, we check whether TX errors have damaged
--			too much the SIZ parameters, again */
--			if (!(image->comps[i].dx * image->comps[i].dy)) {
--				opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
--					"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
--					i, i, image->comps[i].dx, image->comps[i].dy);
--				if (!JPWL_ASSUME) {
--					opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--					return;
--				}
--				/* we try to correct */
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
--				if (!image->comps[i].dx) {
--					image->comps[i].dx = 1;
--					opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
--						i, image->comps[i].dx);
--				}
--				if (!image->comps[i].dy) {
--					image->comps[i].dy = 1;
--					opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
--						i, image->comps[i].dy);
--				}
--			}
--			
--		}
--#endif /* USE_JPWL */
++
 +        opj_tcd_destroy(p_j2k->m_tcd);
- 
--		/* TODO: unused ? */
--		w = int_ceildiv(image->x1 - image->x0, image->comps[i].dx);
--		h = int_ceildiv(image->y1 - image->y0, image->comps[i].dy);
++
 +        opj_j2k_cp_destroy(&(p_j2k->m_cp));
 +        memset(&(p_j2k->m_cp),0,sizeof(opj_cp_t));
- 
--		image->comps[i].resno_decoded = 0;	/* number of resolution decoded */
--		image->comps[i].factor = cp->reduce; /* reducing factor per component */
--	}
--	
--	cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
--	cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
++
 +        opj_procedure_list_destroy(p_j2k->m_procedure_list);
 +        p_j2k->m_procedure_list = 00;
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--		/* if JPWL is on, we check whether TX errors have damaged
--		  too much the SIZ parameters */
--		if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) {
--			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
--				"JPWL: bad number of tiles (%d x %d)\n",
--				cp->tw, cp->th);
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
--			if (cp->tw < 1) {
--				cp->tw= 1;
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
--					cp->tw);
--			}
--			if (cp->tw > cp->max_tiles) {
--				cp->tw= 1;
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n"
--					"- setting %d tiles in x => HYPOTHESIS!!!\n",
--					cp->max_tiles, cp->tw);
--			}
--			if (cp->th < 1) {
--				cp->th= 1;
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
--					cp->th);
--			}
--			if (cp->th > cp->max_tiles) {
--				cp->th= 1;
--				opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
--					"- setting %d tiles in y => HYPOTHESIS!!!\n",
--					cp->max_tiles, cp->th);
--			}
--		}
--	}
--#endif /* USE_JPWL */
++
 +        opj_procedure_list_destroy(p_j2k->m_validation_list);
 +        p_j2k->m_procedure_list = 00;
- 
--	cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
--	cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
--	cp->tileno_size = 0;
--	
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--		if (!cp->tcps) {
--			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
--				"JPWL: could not alloc tcps field of cp\n");
--			if (!JPWL_ASSUME || JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--		}
--	}
--#endif /* USE_JPWL */
++
 +        j2k_destroy_cstr_index(p_j2k->cstr_index);
 +        p_j2k->cstr_index = NULL;
- 
--	for (i = 0; i < cp->tw * cp->th; i++) {
--		cp->tcps[i].POC = 0;
--		cp->tcps[i].numpocs = 0;
--		cp->tcps[i].first = 1;
--	}
--	
--	/* Initialization for PPM marker */
--	cp->ppm = 0;
--	cp->ppm_data = NULL;
--	cp->ppm_data_first = NULL;
--	cp->ppm_previous = 0;
--	cp->ppm_store = 0;
--
--	j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
--	for (i = 0; i < cp->tw * cp->th; i++) {
--		cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t));
--	}	
--	j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*));
--	j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int));
--	j2k->state = J2K_STATE_MH;
--
--	/* Index */
--	if (j2k->cstr_info) {
--		opj_codestream_info_t *cstr_info = j2k->cstr_info;
--		cstr_info->image_w = image->x1 - image->x0;
--		cstr_info->image_h = image->y1 - image->y0;
--		cstr_info->numcomps = image->numcomps;
--		cstr_info->tw = cp->tw;
--		cstr_info->th = cp->th;
--		cstr_info->tile_x = cp->tdx;	
--		cstr_info->tile_y = cp->tdy;	
--		cstr_info->tile_Ox = cp->tx0;	
--		cstr_info->tile_Oy = cp->ty0;			
--		cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t));		
--	}
--}
--
--static void j2k_write_com(opj_j2k_t *j2k) {
--	unsigned int i;
--	int lenp, len;
--
--	if(j2k->cp->comment) {
--		opj_cio_t *cio = j2k->cio;
--		char *comment = j2k->cp->comment;
--
--		cio_write(cio, J2K_MS_COM, 2);
--		lenp = cio_tell(cio);
--		cio_skip(cio, 2);
--		cio_write(cio, 1, 2);		/* General use (IS 8859-15:1999 (Latin) values) */
--		for (i = 0; i < strlen(comment); i++) {
--			cio_write(cio, comment[i], 1);
--		}
--		len = cio_tell(cio) - lenp;
--		cio_seek(cio, lenp);
--		cio_write(cio, len, 2);
--		cio_seek(cio, lenp + len);
--
--		
--		if(j2k->cstr_info)
--		  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COM, lenp, len);
--
--	}
--}
--
--static void j2k_read_com(opj_j2k_t *j2k) {
--	int len;
--	
--	opj_cio_t *cio = j2k->cio;
--
--	len = cio_read(cio, 2);
--	cio_skip(cio, len - 2);  
--}
--
--static void j2k_write_cox(opj_j2k_t *j2k, int compno) {
--	int i;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
--	opj_tccp_t *tccp = &tcp->tccps[compno];
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, tccp->numresolutions - 1, 1);	/* SPcox (D) */
--	cio_write(cio, tccp->cblkw - 2, 1);				/* SPcox (E) */
--	cio_write(cio, tccp->cblkh - 2, 1);				/* SPcox (F) */
--	cio_write(cio, tccp->cblksty, 1);				/* SPcox (G) */
--	cio_write(cio, tccp->qmfbid, 1);				/* SPcox (H) */
--	
--	if (tccp->csty & J2K_CCP_CSTY_PRT) {
--		for (i = 0; i < tccp->numresolutions; i++) {
--			cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1);	/* SPcox (I_i) */
--		}
--	}
--}
--
--static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
--	int i;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_tccp_t *tccp = &tcp->tccps[compno];
--	opj_cio_t *cio = j2k->cio;
--
--	tccp->numresolutions = cio_read(cio, 1) + 1;	/* SPcox (D) */
--
--	/* If user wants to remove more resolutions than the codestream contains, return error*/
--	if (cp->reduce >= tccp->numresolutions) {
--		opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
--					"of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
--		j2k->state |= J2K_STATE_ERR;
--	}
--
--	tccp->cblkw = cio_read(cio, 1) + 2;	/* SPcox (E) */
--	tccp->cblkh = cio_read(cio, 1) + 2;	/* SPcox (F) */
--	tccp->cblksty = cio_read(cio, 1);	/* SPcox (G) */
--	tccp->qmfbid = cio_read(cio, 1);	/* SPcox (H) */
--	if (tccp->csty & J2K_CP_CSTY_PRT) {
--		for (i = 0; i < tccp->numresolutions; i++) {
--			int tmp = cio_read(cio, 1);	/* SPcox (I_i) */
--			tccp->prcw[i] = tmp & 0xf;
--			tccp->prch[i] = tmp >> 4;
--		}
--	}
--
--	/* INDEX >> */
--	if(j2k->cstr_info && compno == 0) {
--		for (i = 0; i < tccp->numresolutions; i++) {
--			if (tccp->csty & J2K_CP_CSTY_PRT) {
--				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i];
--				j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i];
--			}
--			else {
--				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
--				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
--			}
--		}
--	}
--	/* << INDEX */
--}
--
--static void j2k_write_cod(opj_j2k_t *j2k) {
--	opj_cp_t *cp = NULL;
--	opj_tcp_t *tcp = NULL;
--	int lenp, len;
--
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, J2K_MS_COD, 2);	/* COD */
--	
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);
--	
--	cp = j2k->cp;
--	tcp = &cp->tcps[j2k->curtileno];
--
--	cio_write(cio, tcp->csty, 1);		/* Scod */
--	cio_write(cio, tcp->prg, 1);		/* SGcod (A) */
--	cio_write(cio, tcp->numlayers, 2);	/* SGcod (B) */
--	cio_write(cio, tcp->mct, 1);		/* SGcod (C) */
--	
--	j2k_write_cox(j2k, 0);
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);		/* Lcod */
--	cio_seek(cio, lenp + len);
--
--	if(j2k->cstr_info)
--	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COD, lenp, len);
--
--}
--
--static void j2k_read_cod(opj_j2k_t *j2k) {
--	int len, i, pos;
--	
--	opj_cio_t *cio = j2k->cio;
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_image_t *image = j2k->image;
--	
--	len = cio_read(cio, 2);				/* Lcod */
--	tcp->csty = cio_read(cio, 1);		/* Scod */
--	tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);		/* SGcod (A) */
--	tcp->numlayers = cio_read(cio, 2);	/* SGcod (B) */
--	tcp->mct = cio_read(cio, 1);		/* SGcod (C) */
--	
--	pos = cio_tell(cio);
--	for (i = 0; i < image->numcomps; i++) {
--		tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT;
--		cio_seek(cio, pos);
--		j2k_read_cox(j2k, i);
--	}
--
--	/* Index */
--	if (j2k->cstr_info) {
--		opj_codestream_info_t *cstr_info = j2k->cstr_info;
--		cstr_info->prog = tcp->prg;
--		cstr_info->numlayers = tcp->numlayers;
--		cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
--		for (i = 0; i < image->numcomps; i++) {
--			cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1;
--		}
--	}
--}
--
--static void j2k_write_coc(opj_j2k_t *j2k, int compno) {
--	int lenp, len;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
--	opj_image_t *image = j2k->image;
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, J2K_MS_COC, 2);	/* COC */
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);
--	cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2);	/* Ccoc */
--	cio_write(cio, tcp->tccps[compno].csty, 1);	/* Scoc */
--	j2k_write_cox(j2k, compno);
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);			/* Lcoc */
--	cio_seek(cio, lenp + len);
--}
--
--static void j2k_read_coc(opj_j2k_t *j2k) {
--	int len, compno;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_image_t *image = j2k->image;
--	opj_cio_t *cio = j2k->cio;
--	
--	len = cio_read(cio, 2);		/* Lcoc */
--	compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2);	/* Ccoc */
--	tcp->tccps[compno].csty = cio_read(cio, 1);	/* Scoc */
--	j2k_read_cox(j2k, compno);
--}
--
--static void j2k_write_qcx(opj_j2k_t *j2k, int compno) {
--	int bandno, numbands;
--	int expn, mant;
--	
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
--	opj_tccp_t *tccp = &tcp->tccps[compno];
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);	/* Sqcx */
--	numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
--	
--	for (bandno = 0; bandno < numbands; bandno++) {
--		expn = tccp->stepsizes[bandno].expn;
--		mant = tccp->stepsizes[bandno].mant;
--		
--		if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
--			cio_write(cio, expn << 3, 1);	/* SPqcx_i */
--		} else {
--			cio_write(cio, (expn << 11) + mant, 2);	/* SPqcx_i */
--		}
--	}
++
 +        opj_image_destroy(p_j2k->m_private_image);
 +        p_j2k->m_private_image = NULL;
 +
@@ -12671,448 +11950,47 @@ index d34c75f..881cc72 100644
 +        p_j2k->m_output_image = NULL;
 +
 +        opj_free(p_j2k);
- }
- 
--static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
--	int tmp;
--	int bandno, numbands;
++}
++
 +void j2k_destroy_cstr_index (opj_codestream_index_t *p_cstr_ind)
 +{
 +        if (p_cstr_ind) {
- 
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_tccp_t *tccp = &tcp->tccps[compno];
--	opj_cio_t *cio = j2k->cio;
++
 +                if (p_cstr_ind->marker) {
 +                        opj_free(p_cstr_ind->marker);
 +                        p_cstr_ind->marker = NULL;
 +                }
- 
--	tmp = cio_read(cio, 1);		/* Sqcx */
--	tccp->qntsty = tmp & 0x1f;
--	tccp->numgbits = tmp >> 5;
--	numbands = (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 
--		1 : ((tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);
++
 +                if (p_cstr_ind->tile_index) {
 +                        OPJ_UINT32 it_tile = 0;
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--
--		/* if JPWL is on, we check whether there are too many subbands */
--		if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
--			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
--				"JPWL: bad number of subbands in Sqcx (%d)\n",
--				numbands);
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			numbands = 1;
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"
--				"- setting number of bands to %d => HYPOTHESIS!!!\n",
--				numbands);
--		};
--
--	};
--
--#else
--	/* We check whether there are too many subbands */
--	if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
--		opj_event_msg(j2k->cinfo, EVT_WARNING ,
--					"bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n"
--				    "- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS);
--	}
++
 +                        for (it_tile=0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
- 
--#endif /* USE_JPWL */
++
 +                                if(p_cstr_ind->tile_index[it_tile].packet_index) {
 +                                        opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
 +                                        p_cstr_ind->tile_index[it_tile].packet_index = NULL;
 +                                }
- 
--	for (bandno = 0; bandno < numbands; bandno++) {
--		int expn, mant;
--		if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
--			expn = cio_read(cio, 1) >> 3;	/* SPqcx_i */
--			mant = 0;
--		} else {
--			tmp = cio_read(cio, 2);	/* SPqcx_i */
--			expn = tmp >> 11;
--			mant = tmp & 0x7ff;
--		}
--		if (bandno < J2K_MAXBANDS){
--			tccp->stepsizes[bandno].expn = expn;
--			tccp->stepsizes[bandno].mant = mant;
--		}
--	}
--	
--	/* Add Antonin : if scalar_derived -> compute other stepsizes */
--	if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
--		for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
--			tccp->stepsizes[bandno].expn = 
--				((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? 
--					(tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0;
--			tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;
--		}
--	}
--	/* ddA */
--}
--
--static void j2k_write_qcd(opj_j2k_t *j2k) {
--	int lenp, len;
--
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, J2K_MS_QCD, 2);	/* QCD */
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);
--	j2k_write_qcx(j2k, 0);
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);			/* Lqcd */
--	cio_seek(cio, lenp + len);
--
--	if(j2k->cstr_info)
--	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_QCD, lenp, len);
--}
--
--static void j2k_read_qcd(opj_j2k_t *j2k) {
--	int len, i, pos;
--
--	opj_cio_t *cio = j2k->cio;
--	opj_image_t *image = j2k->image;
--	
--	len = cio_read(cio, 2);		/* Lqcd */
--	pos = cio_tell(cio);
--	for (i = 0; i < image->numcomps; i++) {
--		cio_seek(cio, pos);
--		j2k_read_qcx(j2k, i, len - 2);
--	}
--}
--
--static void j2k_write_qcc(opj_j2k_t *j2k, int compno) {
--	int lenp, len;
--
--	opj_cio_t *cio = j2k->cio;
--	
--	cio_write(cio, J2K_MS_QCC, 2);	/* QCC */
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);
--	cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2);	/* Cqcc */
--	j2k_write_qcx(j2k, compno);
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);			/* Lqcc */
--	cio_seek(cio, lenp + len);
--}
--
--static void j2k_read_qcc(opj_j2k_t *j2k) {
--	int len, compno;
--	int numcomp = j2k->image->numcomps;
--	opj_cio_t *cio = j2k->cio;
--
--	len = cio_read(cio, 2);	/* Lqcc */
--	compno = cio_read(cio, numcomp <= 256 ? 1 : 2);	/* Cqcc */
++
 +                                if(p_cstr_ind->tile_index[it_tile].tp_index){
 +                                        opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
 +                                        p_cstr_ind->tile_index[it_tile].tp_index = NULL;
 +                                }
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--
--		static int backup_compno = 0;
--
--		/* compno is negative or larger than the number of components!!! */
--		if ((compno < 0) || (compno >= numcomp)) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
--				compno, numcomp);
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			compno = backup_compno % numcomp;
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
--				"- setting component number to %d\n",
--				compno);
--		}
++
 +                                if(p_cstr_ind->tile_index[it_tile].marker){
 +                                        opj_free(p_cstr_ind->tile_index[it_tile].marker);
 +                                        p_cstr_ind->tile_index[it_tile].marker = NULL;
- 
--		/* keep your private count of tiles */
--		backup_compno++;
--	};
--#endif /* USE_JPWL */
++
 +                                }
 +                        }
- 
--	j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
--}
--
--static void j2k_write_poc(opj_j2k_t *j2k) {
--	int len, numpchgs, i;
--
--	int numcomps = j2k->image->numcomps;
--	
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
--	opj_tccp_t *tccp = &tcp->tccps[0];
--	opj_cio_t *cio = j2k->cio;
--
--	numpchgs = 1 + tcp->numpocs;
--	cio_write(cio, J2K_MS_POC, 2);	/* POC  */
--	len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;
--	cio_write(cio, len, 2);		/* Lpoc */
--	for (i = 0; i < numpchgs; i++) {
--		opj_poc_t *poc = &tcp->pocs[i];
--		cio_write(cio, poc->resno0, 1);	/* RSpoc_i */
--		cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));	/* CSpoc_i */
--		cio_write(cio, poc->layno1, 2);	/* LYEpoc_i */
--		poc->layno1 = int_min(poc->layno1, tcp->numlayers);
--		cio_write(cio, poc->resno1, 1);	/* REpoc_i */
--		poc->resno1 = int_min(poc->resno1, tccp->numresolutions);
--		cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));	/* CEpoc_i */
--		poc->compno1 = int_min(poc->compno1, numcomps);
--		cio_write(cio, poc->prg, 1);	/* Ppoc_i */
--	}
--}
--
--static void j2k_read_poc(opj_j2k_t *j2k) {
--	int len, numpchgs, i, old_poc;
--
--	int numcomps = j2k->image->numcomps;
--	
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_cio_t *cio = j2k->cio;
--	
--	old_poc = tcp->POC ? tcp->numpocs + 1 : 0;
--	tcp->POC = 1;
--	len = cio_read(cio, 2);		/* Lpoc */
--	numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
--	
--	for (i = old_poc; i < numpchgs + old_poc; i++) {
--		opj_poc_t *poc;
--		poc = &tcp->pocs[i];
--		poc->resno0 = cio_read(cio, 1);	/* RSpoc_i */
--		poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);	/* CSpoc_i */
--		poc->layno1 = cio_read(cio, 2);    /* LYEpoc_i */
--		poc->resno1 = cio_read(cio, 1);    /* REpoc_i */
--		poc->compno1 = int_min(
--			cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);	/* CEpoc_i */
--		poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);	/* Ppoc_i */
--	}
--	
--	tcp->numpocs = numpchgs + old_poc - 1;
--}
--
--static void j2k_read_crg(opj_j2k_t *j2k) {
--	int len, i, Xcrg_i, Ycrg_i;
--	
--	opj_cio_t *cio = j2k->cio;
--	int numcomps = j2k->image->numcomps;
--	
--	len = cio_read(cio, 2);			/* Lcrg */
--	for (i = 0; i < numcomps; i++) {
--		Xcrg_i = cio_read(cio, 2);	/* Xcrg_i */
--		Ycrg_i = cio_read(cio, 2);	/* Ycrg_i */
--	}
--}
--
--static void j2k_read_tlm(opj_j2k_t *j2k) {
--	int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
--	long int Ttlm_i, Ptlm_i;
--
--	opj_cio_t *cio = j2k->cio;
--	
--	len = cio_read(cio, 2);		/* Ltlm */
--	Ztlm = cio_read(cio, 1);	/* Ztlm */
--	Stlm = cio_read(cio, 1);	/* Stlm */
--	ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
--	SP = (Stlm >> 6) & 0x01;
--	tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
--	for (i = 0; i < tile_tlm; i++) {
--		Ttlm_i = cio_read(cio, ST);	/* Ttlm_i */
--		Ptlm_i = cio_read(cio, SP ? 4 : 2);	/* Ptlm_i */
--	}
--}
--
--static void j2k_read_plm(opj_j2k_t *j2k) {
--	int len, i, Zplm, Nplm, add, packet_len = 0;
--	
--	opj_cio_t *cio = j2k->cio;
--
--	len = cio_read(cio, 2);		/* Lplm */
--	Zplm = cio_read(cio, 1);	/* Zplm */
--	len -= 3;
--	while (len > 0) {
--		Nplm = cio_read(cio, 4);		/* Nplm */
--		len -= 4;
--		for (i = Nplm; i > 0; i--) {
--			add = cio_read(cio, 1);
--			len--;
--			packet_len = (packet_len << 7) + add;	/* Iplm_ij */
--			if ((add & 0x80) == 0) {
--				/* New packet */
--				packet_len = 0;
--			}
--			if (len <= 0)
--				break;
--		}
--	}
--}
--
--static void j2k_read_plt(opj_j2k_t *j2k) {
--	int len, i, Zplt, packet_len = 0, add;
--	
--	opj_cio_t *cio = j2k->cio;
--	
--	len = cio_read(cio, 2);		/* Lplt */
--	Zplt = cio_read(cio, 1);	/* Zplt */
--	for (i = len - 3; i > 0; i--) {
--		add = cio_read(cio, 1);
--		packet_len = (packet_len << 7) + add;	/* Iplt_i */
--		if ((add & 0x80) == 0) {
--			/* New packet */
--			packet_len = 0;
--		}
--	}
--}
--
--static void j2k_read_ppm(opj_j2k_t *j2k) {
--	int len, Z_ppm, i, j;
--	int N_ppm;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_cio_t *cio = j2k->cio;
--	
--	len = cio_read(cio, 2);
--	cp->ppm = 1;
--	
--	Z_ppm = cio_read(cio, 1);	/* Z_ppm */
--	len -= 3;
--	while (len > 0) {
--		if (cp->ppm_previous == 0) {
--			N_ppm = cio_read(cio, 4);	/* N_ppm */
--			len -= 4;
--		} else {
--			N_ppm = cp->ppm_previous;
--		}
--		j = cp->ppm_store;
--		if (Z_ppm == 0) {	/* First PPM marker */
--			cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));
--			cp->ppm_data_first = cp->ppm_data;
--			cp->ppm_len = N_ppm;
--		} else {			/* NON-first PPM marker */
--			cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +	cp->ppm_store) * sizeof(unsigned char));
++
 +                        opj_free( p_cstr_ind->tile_index);
 +                        p_cstr_ind->tile_index = NULL;
 +                }
- 
--#ifdef USE_JPWL
--			/* this memory allocation check could be done even in non-JPWL cases */
--			if (cp->correct) {
--				if (!cp->ppm_data) {
--					opj_event_msg(j2k->cinfo, EVT_ERROR,
--						"JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n",
--						cio_tell(cio));
--					if (!JPWL_ASSUME || JPWL_ASSUME) {
--						opj_free(cp->ppm_data);
--						opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--						return;
--					}
--				}
--			}
--#endif
++
 +                opj_free(p_cstr_ind);
 +        }
 +}
- 
--			cp->ppm_data_first = cp->ppm_data;
--			cp->ppm_len = N_ppm + cp->ppm_store;
--		}
--		for (i = N_ppm; i > 0; i--) {	/* Read packet header */
--			cp->ppm_data[j] = cio_read(cio, 1);
--			j++;
--			len--;
--			if (len == 0)
--				break;			/* Case of non-finished packet header in present marker but finished in next one */
--		}
--		cp->ppm_previous = i - 1;
--		cp->ppm_store = j;
--	}
--}
--
--static void j2k_read_ppt(opj_j2k_t *j2k) {
--	int len, Z_ppt, i, j = 0;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = cp->tcps + j2k->curtileno;
--	opj_cio_t *cio = j2k->cio;
--
--	len = cio_read(cio, 2);
--	Z_ppt = cio_read(cio, 1);
--	tcp->ppt = 1;
--	if (Z_ppt == 0) {		/* First PPT marker */
--		tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));
--		tcp->ppt_data_first = tcp->ppt_data;
--		tcp->ppt_store = 0;
--		tcp->ppt_len = len - 3;
--	} else {			/* NON-first PPT marker */
--		tcp->ppt_data =	(unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
--		tcp->ppt_data_first = tcp->ppt_data;
--		tcp->ppt_len = len - 3 + tcp->ppt_store;
--	}
--	j = tcp->ppt_store;
--	for (i = len - 3; i > 0; i--) {
--		tcp->ppt_data[j] = cio_read(cio, 1);
--		j++;
--	}
--	tcp->ppt_store = j;
--}
--
--static void j2k_write_tlm(opj_j2k_t *j2k){
--	int lenp;
--	opj_cio_t *cio = j2k->cio;
--	j2k->tlm_start = cio_tell(cio);
--	cio_write(cio, J2K_MS_TLM, 2);/* TLM */
--	lenp = 4 + (5*j2k->totnum_tp);
--	cio_write(cio,lenp,2);				/* Ltlm */
--	cio_write(cio, 0,1);					/* Ztlm=0*/
--	cio_write(cio,80,1);					/* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
--	cio_skip(cio,5*j2k->totnum_tp);
--}
--
--static void j2k_write_sot(opj_j2k_t *j2k) {
--	int lenp, len;
--
--	opj_cio_t *cio = j2k->cio;
--
--	j2k->sot_start = cio_tell(cio);
--	cio_write(cio, J2K_MS_SOT, 2);		/* SOT */
--	lenp = cio_tell(cio);
--	cio_skip(cio, 2);					/* Lsot (further) */
--	cio_write(cio, j2k->curtileno, 2);	/* Isot */
--	cio_skip(cio, 4);					/* Psot (further in j2k_write_sod) */
--	cio_write(cio, j2k->cur_tp_num , 1);	/* TPsot */
--	cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1);		/* TNsot */
--	len = cio_tell(cio) - lenp;
--	cio_seek(cio, lenp);
--	cio_write(cio, len, 2);				/* Lsot */
--	cio_seek(cio, lenp + len);
--
--	/* UniPG>> */
--#ifdef USE_JPWL
--	/* update markers struct */
--	j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2);
--#endif /* USE_JPWL */
--	/* <<UniPG */
++
 +void opj_j2k_tcp_destroy (opj_tcp_t *p_tcp)
 +{
 +        if (p_tcp == 00) {
@@ -13169,16 +12047,9 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        opj_j2k_tcp_data_destroy(p_tcp);
- 
--	if( j2k->cstr_info && j2k->cur_tp_num==0){
--	  j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOT, lenp, len);
--	}
- }
- 
--static void j2k_read_sot(opj_j2k_t *j2k) {
--	int len, tileno, totlen, partno, numparts, i;
--	opj_tcp_t *tcp = NULL;
--	char status = 0;
++
++}
++
 +void opj_j2k_tcp_data_destroy (opj_tcp_t *p_tcp)
 +{
 +        if (p_tcp->m_data) {
@@ -13187,9 +12058,7 @@ index d34c75f..881cc72 100644
 +                p_tcp->m_data_size = 0;
 +        }
 +}
- 
--	opj_cp_t *cp = j2k->cp;
--	opj_cio_t *cio = j2k->cio;
++
 +void opj_j2k_cp_destroy (opj_cp_t *p_cp)
 +{
 +        OPJ_UINT32 l_nb_tiles;
@@ -13224,9 +12093,7 @@ index d34c75f..881cc72 100644
 +                p_cp->m_specific_param.m_enc.m_matrice = 00;
 +        }
 +}
- 
--	len = cio_read(cio, 2);
--	tileno = cio_read(cio, 2);
++
 +OPJ_BOOL opj_j2k_read_tile_header(      opj_j2k_t * p_j2k,
 +                                                                    OPJ_UINT32 * p_tile_index,
 +                                                                    OPJ_UINT32 * p_data_size,
@@ -13453,27 +12320,7 @@ index d34c75f..881cc72 100644
 +
 +        return OPJ_TRUE;
 +}
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--
--		static int backup_tileno = 0;
--
--		/* tileno is negative or larger than the number of tiles!!! */
--		if ((tileno < 0) || (tileno > (cp->tw * cp->th))) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"JPWL: bad tile number (%d out of a maximum of %d)\n",
--				tileno, (cp->tw * cp->th));
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			tileno = backup_tileno;
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
--				"- setting tile number to %d\n",
--				tileno);
--		}
++
 +OPJ_BOOL opj_j2k_decode_tile (  opj_j2k_t * p_j2k,
 +                                                        OPJ_UINT32 p_tile_index,
 +                                                        OPJ_BYTE * p_data,
@@ -13556,28 +12403,7 @@ index d34c75f..881cc72 100644
 +
 +        return OPJ_TRUE;
 +}
- 
--		/* keep your private count of tiles */
--		backup_tileno++;
--	};
--#endif /* USE_JPWL */
--	
--	if (cp->tileno_size == 0) {
--		cp->tileno[cp->tileno_size] = tileno;
--		cp->tileno_size++;
--	} else {
--		i = 0;
--		while (i < cp->tileno_size && status == 0) {
--			status = cp->tileno[i] == tileno ? 1 : 0;
--			i++;
--		}
--		if (status == 0) {
--			cp->tileno[cp->tileno_size] = tileno;
--			cp->tileno_size++;
--		}
--	}
--	
--	totlen = cio_read(cio, 4);
++
 +OPJ_BOOL opj_j2k_update_image_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image)
 +{
 +        OPJ_UINT32 i,j,k = 0;
@@ -13839,25 +12665,7 @@ index d34c75f..881cc72 100644
 +
 +        return OPJ_TRUE;
 +}
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--
--		/* totlen is negative or larger than the bytes left!!! */
--		if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
--				totlen, cio_numbytesleft(cio) + 8);
--			if (!JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--			/* we try to correct */
--			totlen = 0;
--			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
--				"- setting Psot to %d => assuming it is the last tile\n",
--				totlen);
--		}
++
 +OPJ_BOOL opj_j2k_set_decode_area(       opj_j2k_t *p_j2k,
 +                                                                    opj_image_t* p_image,
 +                                                                    OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
@@ -14013,9 +12821,7 @@ index d34c75f..881cc72 100644
 +
 +        return OPJ_TRUE;
 +}
- 
--	};
--#endif /* USE_JPWL */
++
 +opj_j2k_t* opj_j2k_create_decompress(void)
 +{
 +        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_malloc(sizeof(opj_j2k_t));
@@ -14023,216 +12829,10 @@ index d34c75f..881cc72 100644
 +                return 00;
 +        }
 +        memset(l_j2k,0,sizeof(opj_j2k_t));
- 
--	if (!totlen)
--		totlen = cio_numbytesleft(cio) + 8;
--	
--	partno = cio_read(cio, 1);
--	numparts = cio_read(cio, 1);
--  
--  if (partno >= numparts) {
--    opj_event_msg(j2k->cinfo, EVT_WARNING, "SOT marker inconsistency in tile %d: tile-part index greater (%d) than number of tile-parts (%d)\n", tileno, partno, numparts);
--    numparts = partno+1;
--  }
--	
--	j2k->curtileno = tileno;
--	j2k->cur_tp_num = partno;
--	j2k->eot = cio_getbp(cio) - 12 + totlen;
--	j2k->state = J2K_STATE_TPH;
--	tcp = &cp->tcps[j2k->curtileno];
--
--	/* Index */
--	if (j2k->cstr_info) {
--		if (tcp->first) {
--			if (tileno == 0) 
--				j2k->cstr_info->main_head_end = cio_tell(cio) - 13;
--			j2k->cstr_info->tile[tileno].tileno = tileno;
--			j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12;
--			j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1;				
--    } else {
--			j2k->cstr_info->tile[tileno].end_pos += totlen;
--		}
--    j2k->cstr_info->tile[tileno].num_tps = numparts;
--    if (numparts)
--      j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, numparts * sizeof(opj_tp_info_t));
--    else
--      j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, 10 * sizeof(opj_tp_info_t)); /* Fixme (10)*/
--		j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12;
--		j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = 
--			j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
--	}
--	
--	if (tcp->first == 1) {		
--		/* Initialization PPT */
--		opj_tccp_t *tmp = tcp->tccps;
--		memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t));
--		tcp->ppt = 0;
--		tcp->ppt_data = NULL;
--		tcp->ppt_data_first = NULL;
--		tcp->tccps = tmp;
--
--		for (i = 0; i < j2k->image->numcomps; i++) {
--			tcp->tccps[i] = j2k->default_tcp->tccps[i];
--		}
--		cp->tcps[j2k->curtileno].first = 0;
--	}
--}
--
--static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) {
--	int l, layno;
--	int totlen;
--	opj_tcp_t *tcp = NULL;
--	opj_codestream_info_t *cstr_info = NULL;
--	
--	opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;	/* cast is needed because of conflicts in header inclusions */
--	opj_cp_t *cp = j2k->cp;
--	opj_cio_t *cio = j2k->cio;
--
--	tcd->tp_num = j2k->tp_num ;
--	tcd->cur_tp_num = j2k->cur_tp_num;
--	
--	cio_write(cio, J2K_MS_SOD, 2);
--
--	if( j2k->cstr_info && j2k->cur_tp_num==0){
--	  j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOD, cio_tell(cio), 0);
--	}
--
--	if (j2k->curtileno == 0) {
--		j2k->sod_start = cio_tell(cio) + j2k->pos_correction;
--	}
--
--	/* INDEX >> */
--	cstr_info = j2k->cstr_info;
--	if (cstr_info) {
--		if (!j2k->cur_tp_num ) {
--			cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
--			j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno;
--		}
--		else{
--			if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio))
--				cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio);
--		}
--		/* UniPG>> */
--#ifdef USE_JPWL
--		/* update markers struct */
--		j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2);
--#endif /* USE_JPWL */
--		/* <<UniPG */
--	}
--	/* << INDEX */
--	
--	tcp = &cp->tcps[j2k->curtileno];
--	for (layno = 0; layno < tcp->numlayers; layno++) {
--		if (tcp->rates[layno]>(j2k->sod_start / (cp->th * cp->tw))) {
--			tcp->rates[layno]-=(j2k->sod_start / (cp->th * cp->tw));
--		} else if (tcp->rates[layno]) {
--			tcp->rates[layno]=1;
--		}
--	}
--	if(j2k->cur_tp_num == 0){
--		tcd->tcd_image->tiles->packno = 0;
--		if(cstr_info)
--			cstr_info->packno = 0;
--	}
--	
--	l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info);
--	
--	/* Writing Psot in SOT marker */
--	totlen = cio_tell(cio) + l - j2k->sot_start;
--	cio_seek(cio, j2k->sot_start + 6);
--	cio_write(cio, totlen, 4);
--	cio_seek(cio, j2k->sot_start + totlen);
--	/* Writing Ttlm and Ptlm in TLM marker */
--	if(cp->cinema){
--		cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num));
--		cio_write(cio, j2k->curtileno, 1);
--		cio_write(cio, totlen, 4);
--	}
--	cio_seek(cio, j2k->sot_start + totlen);
--}
--
--static void j2k_read_sod(opj_j2k_t *j2k) {
--	int len, truncate = 0, i;
--	unsigned char *data = NULL, *data_ptr = NULL;
--
--	opj_cio_t *cio = j2k->cio;
--	int curtileno = j2k->curtileno;
--
--	/* Index */
--	if (j2k->cstr_info) {
--		j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
--			cio_tell(cio) + j2k->pos_correction - 1;
--		if (j2k->cur_tp_num == 0)
--			j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
--		j2k->cstr_info->packno = 0;
--	}
--	
--	len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);
--
--	if (len == cio_numbytesleft(cio) + 1) {
--		truncate = 1;		/* Case of a truncate codestream */
--	}	
--
--	data = j2k->tile_data[curtileno];
--	data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
--
--	data_ptr = data + j2k->tile_len[curtileno];
--	for (i = 0; i < len; i++) {
--		data_ptr[i] = cio_read(cio, 1);
--	}
--
--	j2k->tile_len[curtileno] += len;
--	j2k->tile_data[curtileno] = data;
--	
--	if (!truncate) {
--		j2k->state = J2K_STATE_TPHSOT;
--	} else {
--		j2k->state = J2K_STATE_NEOC;	/* RAJOUTE !! */
--	}
--	j2k->cur_tp_num++;
--}
--
--static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) {
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = &cp->tcps[tileno];
--	opj_cio_t *cio = j2k->cio;
--	int numcomps = j2k->image->numcomps;
--	
--	cio_write(cio, J2K_MS_RGN, 2);						/* RGN  */
--	cio_write(cio, numcomps <= 256 ? 5 : 6, 2);			/* Lrgn */
--	cio_write(cio, compno, numcomps <= 256 ? 1 : 2);	/* Crgn */
--	cio_write(cio, 0, 1);								/* Srgn */
--	cio_write(cio, tcp->tccps[compno].roishift, 1);		/* SPrgn */
--}
--
--static void j2k_read_rgn(opj_j2k_t *j2k) {
--	int len, compno, roisty;
--
--	opj_cp_t *cp = j2k->cp;
--	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
--	opj_cio_t *cio = j2k->cio;
--	int numcomps = j2k->image->numcomps;
--
--	len = cio_read(cio, 2);										/* Lrgn */
--	compno = cio_read(cio, numcomps <= 256 ? 1 : 2);			/* Crgn */
--	roisty = cio_read(cio, 1);									/* Srgn */
++
 +        l_j2k->m_is_decoder = 1;
 +        l_j2k->m_cp.m_is_decoder = 1;
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--		/* totlen is negative or larger than the bytes left!!! */
--		if (compno >= numcomps) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"JPWL: bad component number in RGN (%d when there are only %d)\n",
--				compno, numcomps);
--			if (!JPWL_ASSUME || JPWL_ASSUME) {
--				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
--				return;
--			}
--		}
--	};
--#endif /* USE_JPWL */
++
 +        l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_malloc(sizeof(opj_tcp_t));
 +        if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
 +                opj_j2k_destroy(l_j2k);
@@ -14249,8 +12849,7 @@ index d34c75f..881cc72 100644
 +        l_j2k->m_specific_param.m_decoder.m_header_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE;
 +
 +        l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
- 
--	tcp->tccps[compno].roishift = cio_read(cio, 1);				/* SPrgn */
++
 +        l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
 +
 +        /* codestream index creation */
@@ -14280,25 +12879,15 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        return l_j2k;
- }
- 
--static void j2k_write_eoc(opj_j2k_t *j2k) {
--	opj_cio_t *cio = j2k->cio;
--	/* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */
--	cio_write(cio, J2K_MS_EOC, 2);
++}
++
 +opj_codestream_index_t* opj_j2k_create_cstr_index(void)
 +{
 +        opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
 +                        opj_calloc(1,sizeof(opj_codestream_index_t));
 +        if (!cstr_index)
 +                return NULL;
- 
--/* UniPG>> */
--#ifdef USE_JPWL
--	/* update markers struct */
--	j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2);
--#endif /* USE_JPWL */
--/* <<UniPG */
++
 +        cstr_index->maxmarknum = 100;
 +        cstr_index->marknum = 0;
 +        cstr_index->marker = (opj_marker_info_t*)
@@ -14309,74 +12898,8 @@ index d34c75f..881cc72 100644
 +        cstr_index->tile_index = NULL;
 +
 +        return cstr_index;
- }
- 
--static void j2k_read_eoc(opj_j2k_t *j2k) {
--	int i, tileno;
--	opj_bool success;
--
--	/* if packets should be decoded */
--	if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
--		opj_tcd_t *tcd = tcd_create(j2k->cinfo);
--		tcd_malloc_decode(tcd, j2k->image, j2k->cp);
--		for (i = 0; i < j2k->cp->tileno_size; i++) {
--			tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
--			tileno = j2k->cp->tileno[i];
--			success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
--			opj_free(j2k->tile_data[tileno]);
--			j2k->tile_data[tileno] = NULL;
--			tcd_free_decode_tile(tcd, i);
--			if (success == OPJ_FALSE) {
--				j2k->state |= J2K_STATE_ERR;
--				break;
--			}
--		}
--		tcd_free_decode(tcd);
--		tcd_destroy(tcd);
--	}
--	/* if packets should not be decoded  */
--	else {
--		for (i = 0; i < j2k->cp->tileno_size; i++) {
--			tileno = j2k->cp->tileno[i];
--			opj_free(j2k->tile_data[tileno]);
--			j2k->tile_data[tileno] = NULL;
--		}
--	}	
--	if (j2k->state & J2K_STATE_ERR)
--		j2k->state = J2K_STATE_MT + J2K_STATE_ERR;
--	else
--		j2k->state = J2K_STATE_MT; 
--}
--
--typedef struct opj_dec_mstabent {
--	/** marker value */
--	int id;
--	/** value of the state when the marker can appear */
--	int states;
--	/** action linked to the marker */
--	void (*handler) (opj_j2k_t *j2k);
--} opj_dec_mstabent_t;
--
--opj_dec_mstabent_t j2k_dec_mstab[] = {
--  {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
--  {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot},
--  {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
--  {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
--  {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
--  {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod},
--  {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc},
--  {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn},
--  {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd},
--  {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc},
--  {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc},
--  {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
--  {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
--  {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
--  {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
--  {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
--  {J2K_MS_SOP, 0, 0},
--  {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
--  {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com},
++}
++
 +OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size (       opj_j2k_t *p_j2k,
 +                                                                                OPJ_UINT32 p_tile_no,
 +                                                                                OPJ_UINT32 p_comp_no )
@@ -14403,17 +12926,7 @@ index d34c75f..881cc72 100644
 +                return 5;
 +        }
 +}
- 
--#ifdef USE_JPWL
--  {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
--  {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
--  {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
--  {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
--#endif /* USE_JPWL */
--#ifdef USE_JPSEC
--  {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec},
--  {J2K_MS_INSEC, 0, j2k_read_insec},
--#endif /* USE_JPSEC */
++
 +OPJ_BOOL opj_j2k_write_SPCod_SPCoc(     opj_j2k_t *p_j2k,
 +                                                                    OPJ_UINT32 p_tile_no,
 +                                                                    OPJ_UINT32 p_comp_no,
@@ -14425,88 +12938,32 @@ index d34c75f..881cc72 100644
 +        opj_cp_t *l_cp = 00;
 +        opj_tcp_t *l_tcp = 00;
 +        opj_tccp_t *l_tccp = 00;
- 
--  {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk}
--};
++
 +        /* preconditions */
 +        assert(p_j2k != 00);
 +        assert(p_header_size != 00);
 +        assert(p_manager != 00);
 +        assert(p_data != 00);
- 
--static void j2k_read_unk(opj_j2k_t *j2k) {
--	opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n");
++
 +        l_cp = &(p_j2k->m_cp);
 +        l_tcp = &l_cp->tcps[p_tile_no];
 +        l_tccp = &l_tcp->tccps[p_comp_no];
- 
--#ifdef USE_JPWL
--	if (j2k->cp->correct) {
--		int m = 0, id, i;
--		int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id;
--		cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
--		id = cio_read(j2k->cio, 2);
--		opj_event_msg(j2k->cinfo, EVT_ERROR,
--			"JPWL: really don't know this marker %x\n",
--			id);
--		if (!JPWL_ASSUME) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"- possible synch loss due to uncorrectable codestream errors => giving up\n");
--			return;
--		}
--		/* OK, activate this at your own risk!!! */
--		/* we look for the marker at the minimum hamming distance from this */
--		while (j2k_dec_mstab[m].id) {
--			
--			/* 1's where they differ */
--			tmp_id = j2k_dec_mstab[m].id ^ id;
--
--			/* compute the hamming distance between our id and the current */
--			cur_dist = 0;
--			for (i = 0; i < 16; i++) {
--				if ((tmp_id >> i) & 0x0001) {
--					cur_dist++;
--				}
--			}
--
--			/* if current distance is smaller, set the minimum */
--			if (cur_dist < min_dist) {
--				min_dist = cur_dist;
--				min_id = j2k_dec_mstab[m].id;
--			}
--			
--			/* jump to the next marker */
--			m++;
--		}
++
 +        /* preconditions again */
 +        assert(p_tile_no < (l_cp->tw * l_cp->th));
 +        assert(p_comp_no <(p_j2k->m_private_image->numcomps));
- 
--		/* do we substitute the marker? */
--		if (min_dist < JPWL_MAXIMUM_HAMMING) {
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"- marker %x is at distance %d from the read %x\n",
--				min_id, min_dist, id);
--			opj_event_msg(j2k->cinfo, EVT_ERROR,
--				"- trying to substitute in place and crossing fingers!\n");
--			cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
--			cio_write(j2k->cio, min_id, 2);
++
 +        if (*p_header_size < 5) {
 +                opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
 +                return OPJ_FALSE;
 +        }
- 
--			/* rewind */
--			cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
++
 +        opj_write_bytes(p_data,l_tccp->numresolutions - 1, 1);  /* SPcoc (D) */
 +        ++p_data;
- 
--		}
++
 +        opj_write_bytes(p_data,l_tccp->cblkw - 2, 1);                   /* SPcoc (E) */
 +        ++p_data;
- 
--	};
--#endif /* USE_JPWL */
++
 +        opj_write_bytes(p_data,l_tccp->cblkh - 2, 1);                   /* SPcoc (F) */
 +        ++p_data;
 +
@@ -14517,7 +12974,7 @@ index d34c75f..881cc72 100644
 +        ++p_data;
 +
 +        *p_header_size = *p_header_size - 5;
- 
++
 +        if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
 +
 +                if (*p_header_size < l_tccp->numresolutions) {
@@ -14534,20 +12991,8 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        return OPJ_TRUE;
- }
- 
--/**
--Read the lookup table containing all the marker, status and action
-- at param id Marker value
--*/
--static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
--	opj_dec_mstabent_t *e;
--	for (e = j2k_dec_mstab; e->id != 0; e++) {
--		if (e->id == id) {
--			break;
--		}
--	}
--	return e;
++}
++
 +OPJ_BOOL opj_j2k_read_SPCod_SPCoc(  opj_j2k_t *p_j2k,
 +                                                                OPJ_UINT32 compno,
 +                                                                OPJ_BYTE * p_header_data,
@@ -14658,11 +13103,8 @@ index d34c75f..881cc72 100644
 +#endif
 +
 +        return OPJ_TRUE;
- }
- 
--/* ----------------------------------------------------------------------- */
--/* J2K / JPT decoder interface                                             */
--/* ----------------------------------------------------------------------- */
++}
++
 +void opj_j2k_copy_tile_component_parameters( opj_j2k_t *p_j2k )
 +{
 +        /* loop */
@@ -14695,101 +13137,38 @@ index d34c75f..881cc72 100644
 +                ++l_copied_tccp;
 +        }
 +}
- 
--opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) {
--	opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
--	if(!j2k)
--		return NULL;
++
 +OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size ( opj_j2k_t *p_j2k,
 +                                                                        OPJ_UINT32 p_tile_no,
 +                                                                        OPJ_UINT32 p_comp_no )
 +{
 +        OPJ_UINT32 l_num_bands;
- 
--	j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t));
--	if(!j2k->default_tcp) {
--		opj_free(j2k);
--		return NULL;
--	}
++
 +        opj_cp_t *l_cp = 00;
 +        opj_tcp_t *l_tcp = 00;
 +        opj_tccp_t *l_tccp = 00;
- 
--	j2k->cinfo = cinfo;
--	j2k->tile_data = NULL;
++
 +        /* preconditions */
 +        assert(p_j2k != 00);
- 
--	return j2k;
--}
++
 +        l_cp = &(p_j2k->m_cp);
 +        l_tcp = &l_cp->tcps[p_tile_no];
 +        l_tccp = &l_tcp->tccps[p_comp_no];
- 
--void j2k_destroy_decompress(opj_j2k_t *j2k) {
--	int i = 0;
++
 +        /* preconditions again */
 +        assert(p_tile_no < l_cp->tw * l_cp->th);
 +        assert(p_comp_no < p_j2k->m_private_image->numcomps);
- 
--	if(j2k->tile_len != NULL) {
--		opj_free(j2k->tile_len);
--	}
--	if(j2k->tile_data != NULL) {
--		opj_free(j2k->tile_data);
--	}
--	if(j2k->default_tcp != NULL) {
--		opj_tcp_t *default_tcp = j2k->default_tcp;
--		if(default_tcp->ppt_data_first != NULL) {
--			opj_free(default_tcp->ppt_data_first);
--		}
--		if(j2k->default_tcp->tccps != NULL) {
--			opj_free(j2k->default_tcp->tccps);
--		}
--		opj_free(j2k->default_tcp);
--	}
--	if(j2k->cp != NULL) {
--		opj_cp_t *cp = j2k->cp;
--		if(cp->tcps != NULL) {
--			for(i = 0; i < cp->tw * cp->th; i++) {
--				if(cp->tcps[i].ppt_data_first != NULL) {
--					opj_free(cp->tcps[i].ppt_data_first);
--				}
--				if(cp->tcps[i].tccps != NULL) {
--					opj_free(cp->tcps[i].tccps);
--				}
--			}
--			opj_free(cp->tcps);
--		}
--		if(cp->ppm_data_first != NULL) {
--			opj_free(cp->ppm_data_first);
--		}
--		if(cp->tileno != NULL) {
--			opj_free(cp->tileno);  
--		}
--		if(cp->comment != NULL) {
--			opj_free(cp->comment);
--		}
++
 +        l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2);
- 
--		opj_free(cp);
--	}
--	opj_free(j2k);
++
 +        if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT)  {
 +                return 1 + l_num_bands;
 +        }
 +        else {
 +                return 1 + 2*l_num_bands;
 +        }
- }
- 
--void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) {
--	if(j2k && parameters) {
--		/* create and initialize the coding parameters structure */
--		opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
--		cp->reduce = parameters->cp_reduce;	
--		cp->layer = parameters->cp_layer;
--		cp->limit_decoding = parameters->cp_limit_decoding;
++}
++
 +OPJ_BOOL opj_j2k_write_SQcd_SQcc(       opj_j2k_t *p_j2k,
 +                                                                OPJ_UINT32 p_tile_no,
 +                                                                OPJ_UINT32 p_comp_no,
@@ -14921,11 +13300,8 @@ index d34c75f..881cc72 100644
 +                        /*return OPJ_FALSE;*/
 +                }
 +        }
- 
- #ifdef USE_JPWL
--		cp->correct = parameters->jpwl_correct;
--		cp->exp_comps = parameters->jpwl_exp_comps;
--		cp->max_tiles = parameters->jpwl_max_tiles;
++
++#ifdef USE_JPWL
 +        if (l_cp->correct) {
 +
 +                /* if JPWL is on, we check whether there are too many subbands */
@@ -14945,8 +13321,8 @@ index d34c75f..881cc72 100644
 +                };
 +
 +        };
- #endif /* USE_JPWL */
- 
++#endif /* USE_JPWL */
++
 +        if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
 +                for     (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
 +                        opj_read_bytes(l_current_ptr, &l_tmp ,1);                       /* SPqcx_i */
@@ -15011,10 +13387,7 @@ index d34c75f..881cc72 100644
 +                ++l_copied_tccp;
 +        }
 +}
- 
--		/* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */
--		j2k->cp = cp;
--	}
++
 +static void opj_j2k_dump_tile_info( opj_tcp_t * l_default_tile,OPJ_INT32 numcomps,FILE* out_stream)
 +{
 +        if (l_default_tile)
@@ -15065,10 +13438,8 @@ index d34c75f..881cc72 100644
 +                } /*end of component of default tile*/
 +                fprintf(out_stream, "\t }\n"); /*end of default tile*/
 +            }
- }
- 
--opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
--	opj_image_t *image = NULL;
++}
++
 +void j2k_dump (opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
 +{
 +        /* Check if the flag is compatible with j2k file*/
@@ -15112,14 +13483,9 @@ index d34c75f..881cc72 100644
 +        if (flag & OPJ_J2K_TH_IND){
 +
 +        }
- 
--	opj_common_ptr cinfo = j2k->cinfo;	
++
 +}
- 
--	j2k->cio = cio;
--	j2k->cstr_info = cstr_info;
--	if (cstr_info)
--		memset(cstr_info, 0, sizeof(opj_codestream_info_t));
++
 +void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
 +{
 +        opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
@@ -15185,88 +13551,22 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        fprintf(out_stream,"}\n");
- 
--	/* create an empty image */
--	image = opj_image_create0();
--	j2k->image = image;
++
 +}
- 
--	j2k->state = J2K_STATE_MHSOC;
- 
--	for (;;) {
--		opj_dec_mstabent_t *e;
--		int id = cio_read(cio, 2);
++
++
 +void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
 +{
- 
--#ifdef USE_JPWL
--		/* we try to honor JPWL correction power */
--		if (j2k->cp->correct) {
--
--			int orig_pos = cio_tell(cio);
--			opj_bool status;
--
--			/* call the corrector */
--			status = jpwl_correct(j2k);
--
--			/* go back to where you were */
--			cio_seek(cio, orig_pos - 2);
--
--			/* re-read the marker */
--			id = cio_read(cio, 2);
--
--			/* check whether it begins with ff */
--			if (id >> 8 != 0xff) {
--				opj_event_msg(cinfo, EVT_ERROR,
--					"JPWL: possible bad marker %x at %d\n",
--					id, cio_tell(cio) - 2);
--				if (!JPWL_ASSUME) {
--					opj_image_destroy(image);
--					opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n");
--					return 0;
--				}
--				/* we try to correct */
--				id = id | 0xff00;
--				cio_seek(cio, cio_tell(cio) - 2);
--				cio_write(cio, id, 2);
--				opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n"
--					"- setting marker to %x\n",
--					id);
--			}
++
 +        fprintf(out_stream, "Codestream info from main header: {\n");
- 
--		}
--#endif /* USE_JPWL */
++
 +        fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
 +        fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
 +        fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
 +        opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
 +        fprintf(out_stream, "}\n");
 +}
- 
--		if (id >> 8 != 0xff) {
--			opj_image_destroy(image);
--			opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
--			return 0;
--		}
--		e = j2k_dec_mstab_lookup(id);
--		/* Check if the marker is known*/
--		if (!(j2k->state & e->states)) {
--			opj_image_destroy(image);
--			opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
--			return 0;
--		}
--		/* Check if the decoding is limited to the main header*/
--		if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) {
--			opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n");
--			return image;
--		}		
--
--		if (e->handler) {
--			(*e->handler)(j2k);
--		}
--		if (j2k->state & J2K_STATE_ERR) 
--			return NULL;	
++
 +void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag, FILE* out_stream)
 +{
 +        char tab[2];
@@ -15295,12 +13595,7 @@ index d34c75f..881cc72 100644
 +
 +        fprintf(out_stream, "}\n");
 +}
- 
--		if (j2k->state == J2K_STATE_MT) {
--			break;
--		}
--		if (j2k->state == J2K_STATE_NEOC) {
--			break;
++
 +void j2k_dump_image_comp_header(opj_image_comp_t* comp_header, OPJ_BOOL dev_dump_flag, FILE* out_stream)
 +{
 +        char tab[3];
@@ -15352,16 +13647,8 @@ index d34c75f..881cc72 100644
 +		{
 +			opj_destroy_cstr_info(&cstr_info);
 +			return NULL;
- 		}
--	}
--	if (j2k->state == J2K_STATE_NEOC) {
--		j2k_read_eoc(j2k);
--	}
- 
--	if (j2k->state != J2K_STATE_MT) {
--		opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
--	}
--	return image;
++		}
++
 +        for (compno = 0; compno < numcomps; compno++) {
 +                opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
 +                opj_tccp_info_t *l_tccp_info = &(cstr_info->m_default_tile_info.tccp_info[compno]);
@@ -15612,89 +13899,12 @@ index d34c75f..881cc72 100644
 +
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_decode_tiles);
 +        /* DEVELOPER CORNER, add your custom procedures */
-+
- }
  
- /*
--* Read a JPT-stream and decode file
--*
--*/
--opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio,  opj_codestream_info_t *cstr_info) {
--	opj_image_t *image = NULL;
--	opj_jpt_msg_header_t header;
--	int position;
--	opj_common_ptr cinfo = j2k->cinfo;
--
--	OPJ_ARG_NOT_USED(cstr_info);
--
--	j2k->cio = cio;
--
--	/* create an empty image */
--	image = opj_image_create0();
--	j2k->image = image;
--
--	j2k->state = J2K_STATE_MHSOC;
--	
--	/* Initialize the header */
--	jpt_init_msg_header(&header);
--	/* Read the first header of the message */
--	jpt_read_msg_header(cinfo, cio, &header);
--	
--	position = cio_tell(cio);
--	if (header.Class_Id != 6) {	/* 6 : Main header data-bin message */
--		opj_image_destroy(image);
--		opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id);
--		return 0;
--	}
--	
--	for (;;) {
--		opj_dec_mstabent_t *e = NULL;
--		int id;
--		
--		if (!cio_numbytesleft(cio)) {
--			j2k_read_eoc(j2k);
--			return image;
--		}
--		/* data-bin read -> need to read a new header */
--		if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) {
--			jpt_read_msg_header(cinfo, cio, &header);
--			position = cio_tell(cio);
--			if (header.Class_Id != 4) {	/* 4 : Tile data-bin message */
--				opj_image_destroy(image);
--				opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n");
--				return 0;
--			}
--		}
--		
--		id = cio_read(cio, 2);
--		if (id >> 8 != 0xff) {
--			opj_image_destroy(image);
--			opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
--			return 0;
--		}
--		e = j2k_dec_mstab_lookup(id);
--		if (!(j2k->state & e->states)) {
--			opj_image_destroy(image);
--			opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
--			return 0;
--		}
--		if (e->handler) {
--			(*e->handler)(j2k);
--		}
--		if (j2k->state == J2K_STATE_MT) {
--			break;
--		}
--		if (j2k->state == J2K_STATE_NEOC) {
--			break;
--		}
--	}
--	if (j2k->state == J2K_STATE_NEOC) {
--		j2k_read_eoc(j2k);
--	}
--	
--	if (j2k->state != J2K_STATE_MT) {
--		opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
--	}
+-/*@}*/
++}
+ 
+-/*@}*/
++/*
 + * Read and decode one tile.
 + */
 +static OPJ_BOOL opj_j2k_decode_one_tile (       opj_j2k_t *p_j2k,
@@ -15715,7 +13925,12 @@ index d34c75f..881cc72 100644
 +                return OPJ_FALSE;
 +        }
 +        l_max_data_size = 1000;
-+
+ 
+-/* ----------------------------------------------------------------------- */
+-typedef struct j2k_prog_order{
+-	OPJ_PROG_ORDER enum_prog;
+-	char str_prog[5];
+-}j2k_prog_order_t;
 +        /*Allocate and initialize some elements of codestrem index if not already done*/
 +        if( !p_j2k->cstr_index->tile_index)
 +        {
@@ -15806,14 +14021,94 @@ index d34c75f..881cc72 100644
 +                else {
 +                        opj_event_msg(p_manager, EVT_WARNING, "Tile read, decode and updated is not the desired (%d vs %d).\n", l_current_tile_no, l_tile_no_to_dec);
 +                }
-+
+ 
+-j2k_prog_order_t j2k_prog_order_list[] = {
+-	{CPRL, "CPRL"},
+-	{LRCP, "LRCP"},
+-	{PCRL, "PCRL"},
+-	{RLCP, "RLCP"},
+-	{RPCL, "RPCL"},
+-	{(OPJ_PROG_ORDER)-1, ""}
+-};
 +        }
-+
+ 
+-char *j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
+-	j2k_prog_order_t *po;
+-	for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
+-		if(po->enum_prog == prg_order){
+-			break;
+-		}
+-	}
+-	return po->str_prog;
 +        opj_free(l_current_data);
 +
 +        return OPJ_TRUE;
-+}
-+
+ }
+ 
+-/* ----------------------------------------------------------------------- */
+-static int j2k_get_num_tp(opj_cp_t *cp,int pino,int tileno){
+-	char *prog;
+-	int i;
+-	int tpnum=1,tpend=0;
+-	opj_tcp_t *tcp = &cp->tcps[tileno];
+-	prog = j2k_convert_progression_order(tcp->prg);
+-	
+-	if(cp->tp_on == 1){
+-		for(i=0;i<4;i++){
+-			if(tpend!=1){
+-				if( cp->tp_flag == prog[i] ){
+-					tpend=1;cp->tp_pos=i;
+-				}
+-				switch(prog[i]){
+-				case 'C':
+-					tpnum= tpnum * tcp->pocs[pino].compE;
+-					break;
+-				case 'R':
+-					tpnum= tpnum * tcp->pocs[pino].resE;
+-					break;
+-				case 'P':
+-					tpnum= tpnum * tcp->pocs[pino].prcE;
+-					break;
+-				case 'L':
+-					tpnum= tpnum * tcp->pocs[pino].layE;
+-					break;
+-				}
+-			}
+-		}
+-	}else{
+-		tpnum=1;
+-	}
+-	return tpnum;
+-}
+-
+-/**	mem allocation for TLM marker*/
+-int j2k_calculate_tp(opj_cp_t *cp,int img_numcomp,opj_image_t *image,opj_j2k_t *j2k ){
+-	int pino,tileno,totnum_tp=0;
+-
+-	OPJ_ARG_NOT_USED(img_numcomp);
+-
+-	j2k->cur_totnum_tp = (int *) opj_malloc(cp->tw * cp->th * sizeof(int));
+-	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+-		int cur_totnum_tp = 0;
+-		opj_tcp_t *tcp = &cp->tcps[tileno];
+-		for(pino = 0; pino <= tcp->numpocs; pino++) {
+-			int tp_num=0;
+-			opj_pi_iterator_t *pi = pi_initialise_encode(image, cp, tileno,FINAL_PASS);
+-			if(!pi) { return -1;}
+-			tp_num = j2k_get_num_tp(cp,pino,tileno);
+-			totnum_tp = totnum_tp + tp_num;
+-			cur_totnum_tp = cur_totnum_tp + tp_num;
+-			pi_destroy(pi, cp, tileno);
+-		}
+-		j2k->cur_totnum_tp[tileno] = cur_totnum_tp;
+-		/* INDEX >> */
+-		if (j2k->cstr_info) {
+-			j2k->cstr_info->tile[tileno].num_tps = cur_totnum_tp;
+-			j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
+-		}
+-		/* << INDEX */
+-	}
+-	return totnum_tp;
 +/**
 + * Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
 + */
@@ -15824,29 +14119,36 @@ index d34c75f..881cc72 100644
 +
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_decode_one_tile);
 +        /* DEVELOPER CORNER, add your custom procedures */
- 
--	return image;
++
  }
  
--/* ----------------------------------------------------------------------- */
--/* J2K encoder interface                                                       */
--/* ----------------------------------------------------------------------- */
+-static void j2k_write_soc(opj_j2k_t *j2k) {
+-	opj_cio_t *cio = j2k->cio;
+-	cio_write(cio, J2K_MS_SOC, 2);
 +OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
 +                                                opj_stream_private_t * p_stream,
 +                                                opj_image_t * p_image,
 +                                                opj_event_mgr_t * p_manager)
 +{
 +        OPJ_UINT32 compno;
-+
+ 
+-	if(j2k->cstr_info)
+-	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio), 0);
 +        if (!p_image)
 +                return OPJ_FALSE;
-+
+ 
+-/* UniPG>> */
+-#ifdef USE_JPWL
 +        p_j2k->m_output_image = opj_image_create0();
 +        if (! (p_j2k->m_output_image)) {
 +                return OPJ_FALSE;
 +        }
 +        opj_copy_image_header(p_image, p_j2k->m_output_image);
-+
+ 
+-	/* update markers struct */
+-	j2k_add_marker(j2k->cstr_info, J2K_MS_SOC, cio_tell(cio) - 2, 2);
+-#endif /* USE_JPWL */
+-/* <<UniPG */
 +        /* customization of the decoding */
 +        opj_j2k_setup_decoding(p_j2k);
 +
@@ -15872,110 +14174,779 @@ index d34c75f..881cc72 100644
 +        }
 +
 +        return OPJ_TRUE;
-+}
+ }
  
--opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) {
--	opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
--	if(j2k) {
--		j2k->cinfo = cinfo;
+-static void j2k_read_soc(opj_j2k_t *j2k) {	
+-	j2k->state = J2K_STATE_MHSIZ;
+-	/* Index */
+-	if (j2k->cstr_info) {
+-		j2k->cstr_info->main_head_start = cio_tell(j2k->cio) - 2;
+-		j2k->cstr_info->codestream_size = cio_numbytesleft(j2k->cio) + 2 - j2k->cstr_info->main_head_start;
+-	}
+-}
+-
+-static void j2k_write_siz(opj_j2k_t *j2k) {
+-	int i;
+-	int lenp, len;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	opj_image_t *image = j2k->image;
+-	opj_cp_t *cp = j2k->cp;
+-
+-	cio_write(cio, J2K_MS_SIZ, 2);	/* SIZ */
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);
+-	cio_write(cio, cp->rsiz, 2);			/* Rsiz (capabilities) */
+-	cio_write(cio, image->x1, 4);	/* Xsiz */
+-	cio_write(cio, image->y1, 4);	/* Ysiz */
+-	cio_write(cio, image->x0, 4);	/* X0siz */
+-	cio_write(cio, image->y0, 4);	/* Y0siz */
+-	cio_write(cio, cp->tdx, 4);		/* XTsiz */
+-	cio_write(cio, cp->tdy, 4);		/* YTsiz */
+-	cio_write(cio, cp->tx0, 4);		/* XT0siz */
+-	cio_write(cio, cp->ty0, 4);		/* YT0siz */
+-	cio_write(cio, image->numcomps, 2);	/* Csiz */
+-	for (i = 0; i < image->numcomps; i++) {
+-		cio_write(cio, image->comps[i].prec - 1 + (image->comps[i].sgnd << 7), 1);	/* Ssiz_i */
+-		cio_write(cio, image->comps[i].dx, 1);	/* XRsiz_i */
+-		cio_write(cio, image->comps[i].dy, 1);	/* YRsiz_i */
+-	}
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);		/* Lsiz */
+-	cio_seek(cio, lenp + len);
+-	
+-	if(j2k->cstr_info)
+-	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_SIZ, lenp, len);
+-}
+-
+-static void j2k_read_siz(opj_j2k_t *j2k) {
+-	int len, i;
+-  int n_comps;
+-	
+-	opj_cio_t *cio = j2k->cio;
+-	opj_image_t *image = j2k->image;
+-	opj_cp_t *cp = j2k->cp;
+-	
+-	len = cio_read(cio, 2);			/* Lsiz */
+-	cio_read(cio, 2);				/* Rsiz (capabilities) */
+-	image->x1 = cio_read(cio, 4);	/* Xsiz */
+-	image->y1 = cio_read(cio, 4);	/* Ysiz */
+-	image->x0 = cio_read(cio, 4);	/* X0siz */
+-	image->y0 = cio_read(cio, 4);	/* Y0siz */
+-	cp->tdx = cio_read(cio, 4);		/* XTsiz */
+-	cp->tdy = cio_read(cio, 4);		/* YTsiz */
+-	cp->tx0 = cio_read(cio, 4);		/* XT0siz */
+-	cp->ty0 = cio_read(cio, 4);		/* YT0siz */
+-	
+-	if ((image->x0<0)||(image->x1<0)||(image->y0<0)||(image->y1<0)) {
+-		opj_event_msg(j2k->cinfo, EVT_ERROR,
+-									"invalid image size (x0:%d, x1:%d, y0:%d, y1:%d)\n",
+-									image->x0,image->x1,image->y0,image->y1);
+-		return;
+-	}
+-	
+-  n_comps = (len - 36 - 2 ) / 3;
+-  assert( (len - 36 - 2 ) % 3 == 0 );
+-	image->numcomps = cio_read(cio, 2);	/* Csiz */
+-  assert( n_comps == image->numcomps );
+-  (void)n_comps;
+-
+-  /* testcase 4035.pdf.SIGSEGV.d8b.3375 */
+-  if (image->x0 > image->x1 || image->y0 > image->y1) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: negative image size (%d x %d)\n", image->x1 - image->x0, image->y1 - image->y0);
+-    return;
+-  }
+-  /* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
+-  if (!(cp->tdx * cp->tdy)) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
+-    return;
+-  }
+-
+-  /* testcase 1610.pdf.SIGSEGV.59c.681 */
+-  if (((int64)image->x1) * ((int64)image->y1) != (image->x1 * image->y1)) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", image->x1, image->y1);
+-    return;
+-  }
++OPJ_BOOL opj_j2k_get_tile(      opj_j2k_t *p_j2k,
++                                                    opj_stream_private_t *p_stream,
++                                                    opj_image_t* p_image,
++                                                    opj_event_mgr_t * p_manager,
++                                                    OPJ_UINT32 tile_index )
++{
++        OPJ_UINT32 compno;
++        OPJ_UINT32 l_tile_x, l_tile_y;
++        opj_image_comp_t* l_img_comp;
++
++        if (!p_image) {
++                opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
++                return OPJ_FALSE;
++        }
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-		/* if JPWL is on, we check whether TX errors have damaged
+-		  too much the SIZ parameters */
+-		if (!(image->x1 * image->y1)) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"JPWL: bad image size (%d x %d)\n",
+-				image->x1, image->y1);
+-			if (!JPWL_ASSUME || JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-		}
+-		if (image->numcomps != ((len - 38) / 3)) {
+-			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+-				"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
+-				image->numcomps, ((len - 38) / 3));
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n");
+-			if (image->numcomps < ((len - 38) / 3)) {
+-				len = 38 + 3 * image->numcomps;
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
+-					len);				
+-			} else {
+-				image->numcomps = ((len - 38) / 3);
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
+-					image->numcomps);				
+-			}
+-		}
++        if ( /*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th) ){
++                opj_event_msg(p_manager, EVT_ERROR, "Tile index provided by the user is incorrect %d (max = %d) \n", tile_index, (p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
++                return OPJ_FALSE;
++        }
+ 
+-		/* update components number in the jpwl_exp_comps filed */
+-		cp->exp_comps = image->numcomps;
+-	}
+-#else
+-  (void)len;
+-#endif /* USE_JPWL */
++        /* Compute the dimension of the desired tile*/
++        l_tile_x = tile_index % p_j2k->m_cp.tw;
++        l_tile_y = tile_index / p_j2k->m_cp.tw;
++
++        p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
++        if (p_image->x0 < p_j2k->m_private_image->x0)
++                p_image->x0 = p_j2k->m_private_image->x0;
++        p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
++        if (p_image->x1 > p_j2k->m_private_image->x1)
++                p_image->x1 = p_j2k->m_private_image->x1;
++
++        p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
++        if (p_image->y0 < p_j2k->m_private_image->y0)
++                p_image->y0 = p_j2k->m_private_image->y0;
++        p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
++        if (p_image->y1 > p_j2k->m_private_image->y1)
++                p_image->y1 = p_j2k->m_private_image->y1;
++
++        l_img_comp = p_image->comps;
++        for (compno=0; compno < p_image->numcomps; ++compno)
++        {
++                OPJ_INT32 l_comp_x1, l_comp_y1;
+ 
+-  /* prevent division by zero */
+-  if (!(cp->tdx * cp->tdy)) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "invalid tile size (tdx: %d, tdy: %d)\n", cp->tdx, cp->tdy);
+-    return;
+-  }
+-
+-	image->comps = (opj_image_comp_t*) opj_calloc(image->numcomps, sizeof(opj_image_comp_t));
+-	for (i = 0; i < image->numcomps; i++) {
+-		int tmp;
+-		tmp = cio_read(cio, 1);		/* Ssiz_i */
+-		image->comps[i].prec = (tmp & 0x7f) + 1;
+-		image->comps[i].sgnd = tmp >> 7;
+-		image->comps[i].dx = cio_read(cio, 1);	/* XRsiz_i */
+-		image->comps[i].dy = cio_read(cio, 1);	/* YRsiz_i */
+-		
+-#ifdef USE_JPWL
+-		if (j2k->cp->correct) {
+-		/* if JPWL is on, we check whether TX errors have damaged
+-			too much the SIZ parameters, again */
+-			if (!(image->comps[i].dx * image->comps[i].dy)) {
+-				opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+-					"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
+-					i, i, image->comps[i].dx, image->comps[i].dy);
+-				if (!JPWL_ASSUME) {
+-					opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-					return;
+-				}
+-				/* we try to correct */
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
+-				if (!image->comps[i].dx) {
+-					image->comps[i].dx = 1;
+-					opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
+-						i, image->comps[i].dx);
+-				}
+-				if (!image->comps[i].dy) {
+-					image->comps[i].dy = 1;
+-					opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
+-						i, image->comps[i].dy);
+-				}
+-			}
+-			
+-		}
+-#endif /* USE_JPWL */
++                l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
+ 
+-    /* prevent division by zero */
+-    if (!(image->comps[i].dx * image->comps[i].dy)) {
+-      opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: invalid component size (dx: %d, dy: %d)\n", image->comps[i].dx, image->comps[i].dy);
+-      return;
+-    }
++                l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx);
++                l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy);
++                l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
++                l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
+ 
+-		image->comps[i].resno_decoded = 0;	/* number of resolution decoded */
+-		image->comps[i].factor = cp->reduce; /* reducing factor per component */
+-	}
+-	
+-	cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
+-	cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
++                l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor));
++                l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor));
+ 
+-  /* gdal_fuzzer_check_number_of_tiles.jp2 */
+-  if (cp->tw == 0 || cp->th == 0 || cp->tw > 65535 / cp->th) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, 
+-                            "Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
+-                            cp->tw, cp->th);
+-    return;
+-  }
++                l_img_comp++;
++        }
+ 
++        /* Destroy the previous output image*/
++        if (p_j2k->m_output_image)
++                opj_image_destroy(p_j2k->m_output_image);
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-		/* if JPWL is on, we check whether TX errors have damaged
+-		  too much the SIZ parameters */
+-		if ((cp->tw < 1) || (cp->th < 1) || (cp->tw > cp->max_tiles) || (cp->th > cp->max_tiles)) {
+-			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+-				"JPWL: bad number of tiles (%d x %d)\n",
+-				cp->tw, cp->th);
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n");
+-			if (cp->tw < 1) {
+-				cp->tw= 1;
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
+-					cp->tw);
+-			}
+-			if (cp->tw > cp->max_tiles) {
+-				cp->tw= 1;
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large x, increase expectance of %d\n"
+-					"- setting %d tiles in x => HYPOTHESIS!!!\n",
+-					cp->max_tiles, cp->tw);
+-			}
+-			if (cp->th < 1) {
+-				cp->th= 1;
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
+-					cp->th);
+-			}
+-			if (cp->th > cp->max_tiles) {
+-				cp->th= 1;
+-				opj_event_msg(j2k->cinfo, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
+-					"- setting %d tiles in y => HYPOTHESIS!!!\n",
+-					cp->max_tiles, cp->th);
+-			}
+-		}
+-	}
+-#endif /* USE_JPWL */
++        /* Create the ouput image from the information previously computed*/
++        p_j2k->m_output_image = opj_image_create0();
++        if (! (p_j2k->m_output_image)) {
++                return OPJ_FALSE;
++        }
++        opj_copy_image_header(p_image, p_j2k->m_output_image);
+ 
+-	cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
+-    if (cp->tcps == NULL)
+-    {
+-        opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
+-        return;
+-    }
+-	cp->tileno = (int*) opj_malloc(cp->tw * cp->th * sizeof(int));
+-    if (cp->tileno == NULL)
+-    {
+-        opj_event_msg(j2k->cinfo, EVT_ERROR, "Out of memory\n");
+-        return;
+-    }
+-	cp->tileno_size = 0;
+-	
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-		if (!cp->tcps) {
+-			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+-				"JPWL: could not alloc tcps field of cp\n");
+-			if (!JPWL_ASSUME || JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-		}
+-	}
+-#endif /* USE_JPWL */
++        p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
+ 
+-	for (i = 0; i < cp->tw * cp->th; i++) {
+-		cp->tcps[i].POC = 0;
+-		cp->tcps[i].numpocs = 0;
+-		cp->tcps[i].first = 1;
+-	}
+-	
+-	/* Initialization for PPM marker */
+-	cp->ppm = 0;
+-	cp->ppm_data = NULL;
+-	cp->ppm_data_first = NULL;
+-	cp->ppm_previous = 0;
+-	cp->ppm_store = 0;
+-
+-	j2k->default_tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
+-	for (i = 0; i < cp->tw * cp->th; i++) {
+-		cp->tcps[i].tccps = (opj_tccp_t*) opj_malloc(image->numcomps * sizeof(opj_tccp_t));
+-	}	
+-	j2k->tile_data = (unsigned char**) opj_calloc(cp->tw * cp->th, sizeof(unsigned char*));
+-	j2k->tile_len = (int*) opj_calloc(cp->tw * cp->th, sizeof(int));
+-	j2k->state = J2K_STATE_MH;
+-
+-	/* Index */
+-	if (j2k->cstr_info) {
+-		opj_codestream_info_t *cstr_info = j2k->cstr_info;
+-		cstr_info->image_w = image->x1 - image->x0;
+-		cstr_info->image_h = image->y1 - image->y0;
+-		cstr_info->numcomps = image->numcomps;
+-		cstr_info->tw = cp->tw;
+-		cstr_info->th = cp->th;
+-		cstr_info->tile_x = cp->tdx;	
+-		cstr_info->tile_y = cp->tdy;	
+-		cstr_info->tile_Ox = cp->tx0;	
+-		cstr_info->tile_Oy = cp->ty0;			
+-		cstr_info->tile = (opj_tile_info_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tile_info_t));		
+-	}
+-}
+-
+-static void j2k_write_com(opj_j2k_t *j2k) {
+-	unsigned int i;
+-	int lenp, len;
+-
+-	if(j2k->cp->comment) {
+-		opj_cio_t *cio = j2k->cio;
+-		char *comment = j2k->cp->comment;
+-
+-		cio_write(cio, J2K_MS_COM, 2);
+-		lenp = cio_tell(cio);
+-		cio_skip(cio, 2);
+-		cio_write(cio, 1, 2);		/* General use (IS 8859-15:1999 (Latin) values) */
+-		for (i = 0; i < strlen(comment); i++) {
+-			cio_write(cio, comment[i], 1);
+-		}
+-		len = cio_tell(cio) - lenp;
+-		cio_seek(cio, lenp);
+-		cio_write(cio, len, 2);
+-		cio_seek(cio, lenp + len);
+-
+-		
+-		if(j2k->cstr_info)
+-		  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COM, lenp, len);
+-
+-	}
+-}
+-
+-static void j2k_read_com(opj_j2k_t *j2k) {
+-	int len;
+-	
+-	opj_cio_t *cio = j2k->cio;
+-
+-	len = cio_read(cio, 2);
+-	cio_skip(cio, len - 2);  
+-}
+-
+-static void j2k_write_cox(opj_j2k_t *j2k, int compno) {
+-	int i;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+-	opj_tccp_t *tccp = &tcp->tccps[compno];
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, tccp->numresolutions - 1, 1);	/* SPcox (D) */
+-	cio_write(cio, tccp->cblkw - 2, 1);				/* SPcox (E) */
+-	cio_write(cio, tccp->cblkh - 2, 1);				/* SPcox (F) */
+-	cio_write(cio, tccp->cblksty, 1);				/* SPcox (G) */
+-	cio_write(cio, tccp->qmfbid, 1);				/* SPcox (H) */
+-	
+-	if (tccp->csty & J2K_CCP_CSTY_PRT) {
+-		for (i = 0; i < tccp->numresolutions; i++) {
+-			cio_write(cio, tccp->prcw[i] + (tccp->prch[i] << 4), 1);	/* SPcox (I_i) */
+-		}
+-	}
+-}
+-
+-static void j2k_read_cox(opj_j2k_t *j2k, int compno) {
+-	int i;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_tccp_t *tccp = &tcp->tccps[compno];
+-	opj_cio_t *cio = j2k->cio;
+-
+-	tccp->numresolutions = cio_read(cio, 1) + 1;	/* SPcox (D) */
+-
+-	/* If user wants to remove more resolutions than the codestream contains, return error*/
+-	if (cp->reduce >= tccp->numresolutions) {
+-		opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
+-					"of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
+-		j2k->state |= J2K_STATE_ERR;
 -	}
--	return j2k;
-+OPJ_BOOL opj_j2k_get_tile(      opj_j2k_t *p_j2k,
-+                                                    opj_stream_private_t *p_stream,
-+                                                    opj_image_t* p_image,
-+                                                    opj_event_mgr_t * p_manager,
-+                                                    OPJ_UINT32 tile_index )
-+{
-+        OPJ_UINT32 compno;
-+        OPJ_UINT32 l_tile_x, l_tile_y;
-+        opj_image_comp_t* l_img_comp;
-+
-+        if (!p_image) {
-+                opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
-+                return OPJ_FALSE;
-+        }
-+
-+        if ( /*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th) ){
-+                opj_event_msg(p_manager, EVT_ERROR, "Tile index provided by the user is incorrect %d (max = %d) \n", tile_index, (p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
-+                return OPJ_FALSE;
-+        }
-+
-+        /* Compute the dimension of the desired tile*/
-+        l_tile_x = tile_index % p_j2k->m_cp.tw;
-+        l_tile_y = tile_index / p_j2k->m_cp.tw;
-+
-+        p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
-+        if (p_image->x0 < p_j2k->m_private_image->x0)
-+                p_image->x0 = p_j2k->m_private_image->x0;
-+        p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
-+        if (p_image->x1 > p_j2k->m_private_image->x1)
-+                p_image->x1 = p_j2k->m_private_image->x1;
-+
-+        p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
-+        if (p_image->y0 < p_j2k->m_private_image->y0)
-+                p_image->y0 = p_j2k->m_private_image->y0;
-+        p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
-+        if (p_image->y1 > p_j2k->m_private_image->y1)
-+                p_image->y1 = p_j2k->m_private_image->y1;
-+
-+        l_img_comp = p_image->comps;
-+        for (compno=0; compno < p_image->numcomps; ++compno)
-+        {
-+                OPJ_INT32 l_comp_x1, l_comp_y1;
-+
-+                l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
-+
-+                l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx);
-+                l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy);
-+                l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
-+                l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
-+
-+                l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor));
-+                l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor));
-+
-+                l_img_comp++;
-+        }
-+
-+        /* Destroy the previous output image*/
-+        if (p_j2k->m_output_image)
-+                opj_image_destroy(p_j2k->m_output_image);
-+
-+        /* Create the ouput image from the information previously computed*/
-+        p_j2k->m_output_image = opj_image_create0();
-+        if (! (p_j2k->m_output_image)) {
-+                return OPJ_FALSE;
-+        }
-+        opj_copy_image_header(p_image, p_j2k->m_output_image);
-+
-+        p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
-+
+-  if( tccp->numresolutions > J2K_MAXRLVLS ) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions is too big: %d vs max= %d. Truncating.\n\n",
+-      compno, tccp->numresolutions, J2K_MAXRLVLS);
+-		j2k->state |= J2K_STATE_ERR;
+-    tccp->numresolutions = J2K_MAXRLVLS;
+- }
+-
+-	tccp->cblkw = cio_read(cio, 1) + 2;	/* SPcox (E) */
+-	tccp->cblkh = cio_read(cio, 1) + 2;	/* SPcox (F) */
+-	tccp->cblksty = cio_read(cio, 1);	/* SPcox (G) */
+-	tccp->qmfbid = cio_read(cio, 1);	/* SPcox (H) */
+-	if (tccp->csty & J2K_CP_CSTY_PRT) {
+-		for (i = 0; i < tccp->numresolutions; i++) {
+-			int tmp = cio_read(cio, 1);	/* SPcox (I_i) */
+-			tccp->prcw[i] = tmp & 0xf;
+-			tccp->prch[i] = tmp >> 4;
+-		}
+-	}
+-
+-	/* INDEX >> */
+-	if(j2k->cstr_info && compno == 0) {
+-		for (i = 0; i < tccp->numresolutions; i++) {
+-			if (tccp->csty & J2K_CP_CSTY_PRT) {
+-				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = tccp->prcw[i];
+-				j2k->cstr_info->tile[j2k->curtileno].pdy[i] = tccp->prch[i];
+-			}
+-			else {
+-				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
+-				j2k->cstr_info->tile[j2k->curtileno].pdx[i] = 15;
+-			}
+-		}
+-	}
+-	/* << INDEX */
+-}
+-
+-static void j2k_write_cod(opj_j2k_t *j2k) {
+-	opj_cp_t *cp = NULL;
+-	opj_tcp_t *tcp = NULL;
+-	int lenp, len;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, J2K_MS_COD, 2);	/* COD */
+-	
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);
+-	
+-	cp = j2k->cp;
+-	tcp = &cp->tcps[j2k->curtileno];
+-
+-	cio_write(cio, tcp->csty, 1);		/* Scod */
+-	cio_write(cio, tcp->prg, 1);		/* SGcod (A) */
+-	cio_write(cio, tcp->numlayers, 2);	/* SGcod (B) */
+-	cio_write(cio, tcp->mct, 1);		/* SGcod (C) */
+-	
+-	j2k_write_cox(j2k, 0);
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);		/* Lcod */
+-	cio_seek(cio, lenp + len);
+-
+-	if(j2k->cstr_info)
+-	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_COD, lenp, len);
+-
+-}
+-
+-static void j2k_read_cod(opj_j2k_t *j2k) {
+-	int len, i, pos;
+-	
+-	opj_cio_t *cio = j2k->cio;
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_image_t *image = j2k->image;
+-	
+-	len = cio_read(cio, 2);				/* Lcod */
+-  (void)len;
+-	tcp->csty = cio_read(cio, 1);		/* Scod */
+-	tcp->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);		/* SGcod (A) */
+-	tcp->numlayers = cio_read(cio, 2);	/* SGcod (B) */
+-	tcp->mct = cio_read(cio, 1);		/* SGcod (C) */
+-	
+-	pos = cio_tell(cio);
+-	for (i = 0; i < image->numcomps; i++) {
+-		tcp->tccps[i].csty = tcp->csty & J2K_CP_CSTY_PRT;
+-		cio_seek(cio, pos);
+-		j2k_read_cox(j2k, i);
+-	}
+-
+-	/* Index */
+-	if (j2k->cstr_info) {
+-		opj_codestream_info_t *cstr_info = j2k->cstr_info;
+-		cstr_info->prog = tcp->prg;
+-		cstr_info->numlayers = tcp->numlayers;
+-		cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
+-		for (i = 0; i < image->numcomps; i++) {
+-			cstr_info->numdecompos[i] = tcp->tccps[i].numresolutions - 1;
+-		}
+-	}
+-}
+-
+-static void j2k_write_coc(opj_j2k_t *j2k, int compno) {
+-	int lenp, len;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+-	opj_image_t *image = j2k->image;
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, J2K_MS_COC, 2);	/* COC */
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);
+-	cio_write(cio, compno, image->numcomps <= 256 ? 1 : 2);	/* Ccoc */
+-	cio_write(cio, tcp->tccps[compno].csty, 1);	/* Scoc */
+-	j2k_write_cox(j2k, compno);
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);			/* Lcoc */
+-	cio_seek(cio, lenp + len);
+-}
+-
+-static void j2k_read_coc(opj_j2k_t *j2k) {
+-	int len, compno;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_image_t *image = j2k->image;
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	len = cio_read(cio, 2);		/* Lcoc */
+-  (void)len;
+-	compno = cio_read(cio, image->numcomps <= 256 ? 1 : 2);	/* Ccoc */
+-  if (compno >= image->numcomps) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR,
+-      "bad component number in COC (%d out of a maximum of %d)\n",
+-      compno, image->numcomps);
+-    return;
+-  }
+-	tcp->tccps[compno].csty = cio_read(cio, 1);	/* Scoc */
+-	j2k_read_cox(j2k, compno);
+-}
+-
+-static void j2k_write_qcx(opj_j2k_t *j2k, int compno) {
+-	int bandno, numbands;
+-	int expn, mant;
+-	
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+-	opj_tccp_t *tccp = &tcp->tccps[compno];
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, tccp->qntsty + (tccp->numgbits << 5), 1);	/* Sqcx */
+-	numbands = tccp->qntsty == J2K_CCP_QNTSTY_SIQNT ? 1 : tccp->numresolutions * 3 - 2;
+-	
+-	for (bandno = 0; bandno < numbands; bandno++) {
+-		expn = tccp->stepsizes[bandno].expn;
+-		mant = tccp->stepsizes[bandno].mant;
+-		
+-		if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
+-			cio_write(cio, expn << 3, 1);	/* SPqcx_i */
+-		} else {
+-			cio_write(cio, (expn << 11) + mant, 2);	/* SPqcx_i */
+-		}
+-	}
+-}
 +        /* customization of the decoding */
 +        opj_j2k_setup_decoding_tile(p_j2k);
-+
+ 
+-static void j2k_read_qcx(opj_j2k_t *j2k, int compno, int len) {
+-	int tmp;
+-	int bandno, numbands;
 +        /* Decode the codestream */
 +        if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
 +                opj_image_destroy(p_j2k->m_private_image);
 +                p_j2k->m_private_image = NULL;
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_tccp_t *tccp = &tcp->tccps[compno];
+-	opj_cio_t *cio = j2k->cio;
 +        /* Move data and copy one information from codec to output image*/
 +        for (compno = 0; compno < p_image->numcomps; compno++) {
 +                p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded;
-+
+ 
+-	tmp = cio_read(cio, 1);		/* Sqcx */
+-	tccp->qntsty = tmp & 0x1f;
+-	tccp->numgbits = tmp >> 5;
+-	numbands = (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 
+-		1 : ((tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? len - 1 : (len - 1) / 2);
 +                if (p_image->comps[compno].data)
 +                        opj_free(p_image->comps[compno].data);
-+
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-
+-		/* if JPWL is on, we check whether there are too many subbands */
+-		if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
+-			opj_event_msg(j2k->cinfo, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
+-				"JPWL: bad number of subbands in Sqcx (%d)\n",
+-				numbands);
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			numbands = 1;
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust them\n"
+-				"- setting number of bands to %d => HYPOTHESIS!!!\n",
+-				numbands);
+-		};
+-
+-	};
+-
+-#else
+-	/* We check whether there are too many subbands */
+-	if ((numbands < 0) || (numbands >= J2K_MAXBANDS)) {
+-		opj_event_msg(j2k->cinfo, EVT_WARNING ,
+-					"bad number of subbands in Sqcx (%d) regarding to J2K_MAXBANDS (%d) \n"
+-				    "- limiting number of bands to J2K_MAXBANDS and try to move to the next markers\n", numbands, J2K_MAXBANDS);
+-    /* edf_c2_1013627.jp2 */
+-    numbands = 1;
+-	}
 +                p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
-+
+ 
+-#endif /* USE_JPWL */
 +                p_j2k->m_output_image->comps[compno].data = NULL;
 +        }
-+
+ 
+-	for (bandno = 0; bandno < numbands; bandno++) {
+-		int expn, mant;
+-		if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
+-			expn = cio_read(cio, 1) >> 3;	/* SPqcx_i */
+-			mant = 0;
+-		} else {
+-			tmp = cio_read(cio, 2);	/* SPqcx_i */
+-			expn = tmp >> 11;
+-			mant = tmp & 0x7ff;
+-		}
+-		if (bandno < J2K_MAXBANDS){
+-			tccp->stepsizes[bandno].expn = expn;
+-			tccp->stepsizes[bandno].mant = mant;
+-		}
+-	}
+-	
+-	/* Add Antonin : if scalar_derived -> compute other stepsizes */
+-	if (tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
+-		for (bandno = 1; bandno < J2K_MAXBANDS; bandno++) {
+-			tccp->stepsizes[bandno].expn = 
+-				((tccp->stepsizes[0].expn) - ((bandno - 1) / 3) > 0) ? 
+-					(tccp->stepsizes[0].expn) - ((bandno - 1) / 3) : 0;
+-			tccp->stepsizes[bandno].mant = tccp->stepsizes[0].mant;
+-		}
+-	}
+-	/* ddA */
+-}
+-
+-static void j2k_write_qcd(opj_j2k_t *j2k) {
+-	int lenp, len;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, J2K_MS_QCD, 2);	/* QCD */
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);
+-	j2k_write_qcx(j2k, 0);
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);			/* Lqcd */
+-	cio_seek(cio, lenp + len);
+-
+-	if(j2k->cstr_info)
+-	  j2k_add_mhmarker(j2k->cstr_info, J2K_MS_QCD, lenp, len);
+-}
+-
+-static void j2k_read_qcd(opj_j2k_t *j2k) {
+-	int len, i, pos;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	opj_image_t *image = j2k->image;
+-	
+-	len = cio_read(cio, 2);		/* Lqcd */
+-	pos = cio_tell(cio);
+-	for (i = 0; i < image->numcomps; i++) {
+-		cio_seek(cio, pos);
+-		j2k_read_qcx(j2k, i, len - 2);
+-	}
+-}
+-
+-static void j2k_write_qcc(opj_j2k_t *j2k, int compno) {
+-	int lenp, len;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	cio_write(cio, J2K_MS_QCC, 2);	/* QCC */
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);
+-	cio_write(cio, compno, j2k->image->numcomps <= 256 ? 1 : 2);	/* Cqcc */
+-	j2k_write_qcx(j2k, compno);
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);			/* Lqcc */
+-	cio_seek(cio, lenp + len);
+-}
+-
+-static void j2k_read_qcc(opj_j2k_t *j2k) {
+-	int len, compno;
+-	int numcomp = j2k->image->numcomps;
+-	opj_cio_t *cio = j2k->cio;
+-
+-	len = cio_read(cio, 2);	/* Lqcc */
+-	compno = cio_read(cio, numcomp <= 256 ? 1 : 2);	/* Cqcc */
 +        return OPJ_TRUE;
- }
++}
  
--void j2k_destroy_compress(opj_j2k_t *j2k) {
--	int tileno;
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-
+-		static int backup_compno = 0;
+-
+-		/* compno is negative or larger than the number of components!!! */
+-		if ((compno < 0) || (compno >= numcomp)) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
+-				compno, numcomp);
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			compno = backup_compno % numcomp;
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+-				"- setting component number to %d\n",
+-				compno);
+-		}
 +OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
 +                                               OPJ_UINT32 res_factor,
 +                                               opj_event_mgr_t * p_manager)
@@ -16001,13 +14972,74 @@ index d34c75f..881cc72 100644
 +                        }
 +                }
 +        }
-+
+ 
+-		/* keep your private count of tiles */
+-		backup_compno++;
+-	}
+-#endif /* USE_JPWL */
 +        return OPJ_FALSE;
 +}
  
--	if(!j2k) return;
--	if(j2k->cp != NULL) {
--		opj_cp_t *cp = j2k->cp;
+-  if ((compno < 0) || (compno >= numcomp)) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR,
+-      "bad component number in QCC (%d out of a maximum of %d)\n",
+-      compno, j2k->image->numcomps);
+-    return;
+-  }
+-
+-	j2k_read_qcx(j2k, compno, len - 2 - (numcomp <= 256 ? 1 : 2));
+-}
+-
+-static void j2k_write_poc(opj_j2k_t *j2k) {
+-	int len, numpchgs, i;
+-
+-	int numcomps = j2k->image->numcomps;
+-	
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = &cp->tcps[j2k->curtileno];
+-	opj_tccp_t *tccp = &tcp->tccps[0];
+-	opj_cio_t *cio = j2k->cio;
+-
+-	numpchgs = 1 + tcp->numpocs;
+-	cio_write(cio, J2K_MS_POC, 2);	/* POC  */
+-	len = 2 + (5 + 2 * (numcomps <= 256 ? 1 : 2)) * numpchgs;
+-	cio_write(cio, len, 2);		/* Lpoc */
+-	for (i = 0; i < numpchgs; i++) {
+-		opj_poc_t *poc = &tcp->pocs[i];
+-		cio_write(cio, poc->resno0, 1);	/* RSpoc_i */
+-		cio_write(cio, poc->compno0, (numcomps <= 256 ? 1 : 2));	/* CSpoc_i */
+-		cio_write(cio, poc->layno1, 2);	/* LYEpoc_i */
+-		poc->layno1 = int_min(poc->layno1, tcp->numlayers);
+-		cio_write(cio, poc->resno1, 1);	/* REpoc_i */
+-		poc->resno1 = int_min(poc->resno1, tccp->numresolutions);
+-		cio_write(cio, poc->compno1, (numcomps <= 256 ? 1 : 2));	/* CEpoc_i */
+-		poc->compno1 = int_min(poc->compno1, numcomps);
+-		cio_write(cio, poc->prg, 1);	/* Ppoc_i */
+-	}
+-}
+-
+-static void j2k_read_poc(opj_j2k_t *j2k) {
+-	int len, numpchgs, i, old_poc;
+-
+-	int numcomps = j2k->image->numcomps;
+-	
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	old_poc = tcp->POC ? tcp->numpocs + 1 : 0;
+-	tcp->POC = 1;
+-	len = cio_read(cio, 2);		/* Lpoc */
+-	numpchgs = (len - 2) / (5 + 2 * (numcomps <= 256 ? 1 : 2));
+-	
+-  if( numpchgs >= 32 )
+-    {
+-    /* edf_c2_1103421.jp2 */
+-    opj_event_msg(j2k->cinfo, EVT_ERROR,
+-      "bad number of POCS (%d out of a maximum of %d)\n",
+-      numpchgs, 32);
+-    numpchgs = 0;
+-    }
 +OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
 +                        opj_stream_private_t *p_stream,
 +                        opj_event_mgr_t * p_manager )
@@ -16054,99 +15086,148 @@ index d34c75f..881cc72 100644
 +                        return OPJ_FALSE;
 +                }
 +        }
-+
-+        opj_free(l_current_data);
-+        return OPJ_TRUE;
-+}
  
--		if(cp->comment) {
--			opj_free(cp->comment);
--		}
--		if(cp->matrice) {
--			opj_free(cp->matrice);
--		}
--		for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
--			opj_free(cp->tcps[tileno].tccps);
--		}
--		opj_free(cp->tcps);
--		opj_free(cp);
+-	for (i = old_poc; i < numpchgs + old_poc; i++) {
+-		opj_poc_t *poc;
+-		poc = &tcp->pocs[i];
+-		poc->resno0 = cio_read(cio, 1);	/* RSpoc_i */
+-		poc->compno0 = cio_read(cio, numcomps <= 256 ? 1 : 2);	/* CSpoc_i */
+-		poc->layno1 = cio_read(cio, 2);    /* LYEpoc_i */
+-		poc->resno1 = cio_read(cio, 1);    /* REpoc_i */
+-		poc->compno1 = int_min(
+-			cio_read(cio, numcomps <= 256 ? 1 : 2), (unsigned int) numcomps);	/* CEpoc_i */
+-		poc->prg = (OPJ_PROG_ORDER)cio_read(cio, 1);	/* Ppoc_i */
 -	}
--
--	opj_free(j2k);
+-	
+-	tcp->numpocs = numpchgs + old_poc - 1;
 -}
 -
--void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) {
--	int i, j, tileno, numpocs_tile;
--	opj_cp_t *cp = NULL;
--
--	if(!j2k || !parameters || ! image) {
--		return;
--	}
--
--	/* create and initialize the coding parameters structure */
--	cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
--
--	/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
--	j2k->cp = cp;
--
--	/* set default values for cp */
--	cp->tw = 1;
--	cp->th = 1;
--
--	/* 
--	copy user encoding parameters 
--	*/
--	cp->cinema = parameters->cp_cinema;
--	cp->max_comp_size =	parameters->max_comp_size;
--	cp->rsiz   = parameters->cp_rsiz;
--	cp->disto_alloc = parameters->cp_disto_alloc;
--	cp->fixed_alloc = parameters->cp_fixed_alloc;
--	cp->fixed_quality = parameters->cp_fixed_quality;
--
--	/* mod fixed_quality */
--	if(parameters->cp_matrice) {
--		size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int);
--		cp->matrice = (int *) opj_malloc(array_size);
--		memcpy(cp->matrice, parameters->cp_matrice, array_size);
+-static void j2k_read_crg(opj_j2k_t *j2k) {
+-	int len, i, Xcrg_i, Ycrg_i;
+-	
+-	opj_cio_t *cio = j2k->cio;
+-	int numcomps = j2k->image->numcomps;
+-	
+-	len = cio_read(cio, 2);			/* Lcrg */
+-  (void)len;
+-	for (i = 0; i < numcomps; i++) {
+-		Xcrg_i = cio_read(cio, 2);	/* Xcrg_i */
+-    (void)Xcrg_i;
+-		Ycrg_i = cio_read(cio, 2);	/* Ycrg_i */
+-    (void)Ycrg_i;
 -	}
+-}
 -
--	/* tiles */
--	cp->tdx = parameters->cp_tdx;
--	cp->tdy = parameters->cp_tdy;
--
--	/* tile offset */
--	cp->tx0 = parameters->cp_tx0;
--	cp->ty0 = parameters->cp_ty0;
+-static void j2k_read_tlm(opj_j2k_t *j2k) {
+-	int len, Ztlm, Stlm, ST, SP, tile_tlm, i;
+-	long int Ttlm_i, Ptlm_i;
 -
--	/* comment string */
--	if(parameters->cp_comment) {
--		cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);
--		if(cp->comment) {
--			strcpy(cp->comment, parameters->cp_comment);
--		}
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	len = cio_read(cio, 2);		/* Ltlm */
+-	Ztlm = cio_read(cio, 1);	/* Ztlm */
+-  (void)Ztlm;
+-	Stlm = cio_read(cio, 1);	/* Stlm */
+-	ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
+-	SP = (Stlm >> 6) & 0x01;
+-	tile_tlm = (len - 4) / ((SP + 1) * 2 + ST);
+-	for (i = 0; i < tile_tlm; i++) {
+-		Ttlm_i = cio_read(cio, ST);	/* Ttlm_i */
+-    (void)Ttlm_i;
+-		Ptlm_i = cio_read(cio, SP ? 4 : 2);	/* Ptlm_i */
+-    (void)Ptlm_i;
 -	}
+-}
 -
--	/*
--	calculate other encoding parameters
--	*/
+-static void j2k_read_plm(opj_j2k_t *j2k) {
+-	int len, i, Zplm, Nplm, add, packet_len = 0;
+-	
+-	opj_cio_t *cio = j2k->cio;
 -
--	if (parameters->tile_size_on) {
--		cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
--		cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
--	} else {
--		cp->tdx = image->x1 - cp->tx0;
--		cp->tdy = image->y1 - cp->ty0;
+-	len = cio_read(cio, 2);		/* Lplm */
+-	Zplm = cio_read(cio, 1);	/* Zplm */
+-  (void)Zplm;
+-	len -= 3;
+-	while (len > 0) {
+-		Nplm = cio_read(cio, 4);		/* Nplm */
+-		len -= 4;
+-		for (i = Nplm; i > 0; i--) {
+-			add = cio_read(cio, 1);
+-			len--;
+-			packet_len = (packet_len << 7) + add;	/* Iplm_ij */
+-			if ((add & 0x80) == 0) {
+-				/* New packet */
+-				packet_len = 0;
+-			}
+-			if (len <= 0)
+-				break;
+-		}
 -	}
+-}
 -
--	if(parameters->tp_on){
--		cp->tp_flag = parameters->tp_flag;
--		cp->tp_on = 1;
--	}
+-static void j2k_read_plt(opj_j2k_t *j2k) {
+-	int len, i, Zplt, packet_len = 0, add;
 -	
--	cp->img_size = 0;
--	for(i=0;i<image->numcomps ;i++){
--	cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec);
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	len = cio_read(cio, 2);		/* Lplt */
+-	Zplt = cio_read(cio, 1);	/* Zplt */
+-  (void)Zplt;
+-	for (i = len - 3; i > 0; i--) {
+-		add = cio_read(cio, 1);
+-		packet_len = (packet_len << 7) + add;	/* Iplt_i */
+-		if ((add & 0x80) == 0) {
+-			/* New packet */
+-			packet_len = 0;
+-		}
 -	}
+-}
+-
+-static void j2k_read_ppm(opj_j2k_t *j2k) {
+-	int len, Z_ppm, i, j;
+-	int N_ppm;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_cio_t *cio = j2k->cio;
+-	
+-	len = cio_read(cio, 2);
+-	cp->ppm = 1;
+-	
+-	Z_ppm = cio_read(cio, 1);	/* Z_ppm */
+-	len -= 3;
+-	while (len > 0) {
+-		if (cp->ppm_previous == 0) {
+-			N_ppm = cio_read(cio, 4);	/* N_ppm */
+-			len -= 4;
+-		} else {
+-			N_ppm = cp->ppm_previous;
+-		}
+-		j = cp->ppm_store;
+-		if (Z_ppm == 0) {	/* First PPM marker */
+-			cp->ppm_data = (unsigned char *) opj_malloc(N_ppm * sizeof(unsigned char));
+-			cp->ppm_data_first = cp->ppm_data;
+-			cp->ppm_len = N_ppm;
+-		} else {			/* NON-first PPM marker */
+-			cp->ppm_data = (unsigned char *) opj_realloc(cp->ppm_data, (N_ppm +	cp->ppm_store) * sizeof(unsigned char));
++        opj_free(l_current_data);
++        return OPJ_TRUE;
++}
+ 
+-#ifdef USE_JPWL
+-			/* this memory allocation check could be done even in non-JPWL cases */
+-			if (cp->correct) {
+-				if (!cp->ppm_data) {
+-					opj_event_msg(j2k->cinfo, EVT_ERROR,
+-						"JPWL: failed memory allocation during PPM marker parsing (pos. %x)\n",
+-						cio_tell(cio));
+-					if (!JPWL_ASSUME || JPWL_ASSUME) {
+-						opj_free(cp->ppm_data);
+-						opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-						return;
+-					}
+-				}
+-			}
+-#endif
 +OPJ_BOOL opj_j2k_end_compress(  opj_j2k_t *p_j2k,
 +                                                        opj_stream_private_t *p_stream,
 +                                                        opj_event_mgr_t * p_manager)
@@ -16154,49 +15235,100 @@ index d34c75f..881cc72 100644
 +        /* customization of the encoding */
 +        opj_j2k_setup_end_compress(p_j2k);
  
+-			cp->ppm_data_first = cp->ppm_data;
+-			cp->ppm_len = N_ppm + cp->ppm_store;
+-		}
+-		for (i = N_ppm; i > 0; i--) {	/* Read packet header */
+-			cp->ppm_data[j] = cio_read(cio, 1);
+-			j++;
+-			len--;
+-			if (len == 0)
+-				break;			/* Case of non-finished packet header in present marker but finished in next one */
+-		}
+-		cp->ppm_previous = i - 1;
+-		cp->ppm_store = j;
+-	}
+-}
+-
+-static void j2k_read_ppt(opj_j2k_t *j2k) {
+-	int len, Z_ppt, i, j = 0;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = cp->tcps + j2k->curtileno;
+-	opj_cio_t *cio = j2k->cio;
+-
+-	len = cio_read(cio, 2);
+-	Z_ppt = cio_read(cio, 1);
+-	tcp->ppt = 1;
+-	if (Z_ppt == 0) {		/* First PPT marker */
+-		tcp->ppt_data = (unsigned char *) opj_malloc((len - 3) * sizeof(unsigned char));
+-		tcp->ppt_data_first = tcp->ppt_data;
+-		tcp->ppt_store = 0;
+-		tcp->ppt_len = len - 3;
+-	} else {			/* NON-first PPT marker */
+-		tcp->ppt_data =	(unsigned char *) opj_realloc(tcp->ppt_data, (len - 3 + tcp->ppt_store) * sizeof(unsigned char));
+-		tcp->ppt_data_first = tcp->ppt_data;
+-		tcp->ppt_len = len - 3 + tcp->ppt_store;
+-	}
+-	j = tcp->ppt_store;
+-	for (i = len - 3; i > 0; i--) {
+-		tcp->ppt_data[j] = cio_read(cio, 1);
+-		j++;
+-	}
+-	tcp->ppt_store = j;
+-}
+-
+-static void j2k_write_tlm(opj_j2k_t *j2k){
+-	int lenp;
+-	opj_cio_t *cio = j2k->cio;
+-	j2k->tlm_start = cio_tell(cio);
+-	cio_write(cio, J2K_MS_TLM, 2);/* TLM */
+-	lenp = 4 + (5*j2k->totnum_tp);
+-	cio_write(cio,lenp,2);				/* Ltlm */
+-	cio_write(cio, 0,1);					/* Ztlm=0*/
+-	cio_write(cio,80,1);					/* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
+-	cio_skip(cio,5*j2k->totnum_tp);
+-}
+-
+-static void j2k_write_sot(opj_j2k_t *j2k) {
+-	int lenp, len;
+-
+-	opj_cio_t *cio = j2k->cio;
+-
+-	j2k->sot_start = cio_tell(cio);
+-	cio_write(cio, J2K_MS_SOT, 2);		/* SOT */
+-	lenp = cio_tell(cio);
+-	cio_skip(cio, 2);					/* Lsot (further) */
+-	cio_write(cio, j2k->curtileno, 2);	/* Isot */
+-	cio_skip(cio, 4);					/* Psot (further in j2k_write_sod) */
+-	cio_write(cio, j2k->cur_tp_num , 1);	/* TPsot */
+-	cio_write(cio, j2k->cur_totnum_tp[j2k->curtileno], 1);		/* TNsot */
+-	len = cio_tell(cio) - lenp;
+-	cio_seek(cio, lenp);
+-	cio_write(cio, len, 2);				/* Lsot */
+-	cio_seek(cio, lenp + len);
+-
+-	/* UniPG>> */
+-#ifdef USE_JPWL
+-	/* update markers struct */
+-	j2k_add_marker(j2k->cstr_info, J2K_MS_SOT, j2k->sot_start, len + 2);
+-#endif /* USE_JPWL */
+-	/* <<UniPG */
 +        if (! opj_j2k_exec (p_j2k, p_j2k->m_procedure_list, p_stream, p_manager))
 +        {
 +                return OPJ_FALSE;
 +        }
  
--#ifdef USE_JPWL
--	/*
--	calculate JPWL encoding parameters
--	*/
--
--	if (parameters->jpwl_epc_on) {
--		int i;
--
--		/* set JPWL on */
--		cp->epc_on = OPJ_TRUE;
--		cp->info_on = OPJ_FALSE; /* no informative technique */
--
--		/* set EPB on */
--		if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
--			cp->epb_on = OPJ_TRUE;
--			
--			cp->hprot_MH = parameters->jpwl_hprot_MH;
--			for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
--				cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
--				cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
--			}
--			/* if tile specs are not specified, copy MH specs */
--			if (cp->hprot_TPH[0] == -1) {
--				cp->hprot_TPH_tileno[0] = 0;
--				cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
--			}
--			for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
--				cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
--				cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
--				cp->pprot[i] = parameters->jpwl_pprot[i];
--			}
--		}
+-	if( j2k->cstr_info && j2k->cur_tp_num==0){
+-	  j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOT, lenp, len);
+-	}
 +        return OPJ_TRUE;
-+}
+ }
  
--		/* set ESD writing */
--		if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
--			cp->esd_on = OPJ_TRUE;
+-static void j2k_read_sot(opj_j2k_t *j2k) {
+-	int len, tileno, totlen, partno, numparts, i;
+-	opj_tcp_t *tcp = NULL;
+-	char status = 0;
 +OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
 +                                                            opj_stream_private_t *p_stream,
 +                                                            opj_image_t * p_image,
@@ -16221,29 +15353,270 @@ index d34c75f..881cc72 100644
 +                        }
 +                }
 +        }
-+
+ 
+-	opj_cp_t *cp = j2k->cp;
+-	opj_cio_t *cio = j2k->cio;
 +        /* customization of the validation */
 +        opj_j2k_setup_encoding_validation (p_j2k);
-+
+ 
+-	len = cio_read(cio, 2);
+-  (void)len;
+-	tileno = cio_read(cio, 2);
 +        /* validation of the parameters codec */
 +        if (! opj_j2k_exec(p_j2k,p_j2k->m_validation_list,p_stream,p_manager)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-
+-		static int backup_tileno = 0;
+-
+-		/* tileno is negative or larger than the number of tiles!!! */
+-		if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"JPWL: bad tile number (%d out of a maximum of %d)\n",
+-				tileno, (cp->tw * cp->th));
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			tileno = backup_tileno;
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+-				"- setting tile number to %d\n",
+-				tileno);
+-		}
 +        /* customization of the encoding */
 +        opj_j2k_setup_header_writing(p_j2k);
-+
+ 
+-		/* keep your private count of tiles */
+-		backup_tileno++;
+-	}
+-  else
+-#endif /* USE_JPWL */
+-  {
+-    /* tileno is negative or larger than the number of tiles!!! */
+-    if ((tileno < 0) || (tileno >= (cp->tw * cp->th))) {
+-      opj_event_msg(j2k->cinfo, EVT_ERROR,
+-        "JPWL: bad tile number (%d out of a maximum of %d)\n",
+-        tileno, (cp->tw * cp->th));
+-      return;
+-    }
+-  }
+-	
+-	if (cp->tileno_size == 0) {
+-		cp->tileno[cp->tileno_size] = tileno;
+-		cp->tileno_size++;
+-	} else {
+-		i = 0;
+-		while (i < cp->tileno_size && status == 0) {
+-			status = cp->tileno[i] == tileno ? 1 : 0;
+-			i++;
+-		}
+-		if (status == 0) {
+-			cp->tileno[cp->tileno_size] = tileno;
+-			cp->tileno_size++;
+-		}
+-	}
+-	
+-	totlen = cio_read(cio, 4);
 +        /* write header */
 +        if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-
+-		/* totlen is negative or larger than the bytes left!!! */
+-		if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
+-				totlen, cio_numbytesleft(cio) + 8);
+-			if (!JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-			/* we try to correct */
+-			totlen = 0;
+-			opj_event_msg(j2k->cinfo, EVT_WARNING, "- trying to adjust this\n"
+-				"- setting Psot to %d => assuming it is the last tile\n",
+-				totlen);
+-		}
 +        return OPJ_TRUE;
 +}
  
--			cp->sens_size = parameters->jpwl_sens_size;
--			cp->sens_addr = parameters->jpwl_sens_addr;
--			cp->sens_range = parameters->jpwl_sens_range;
+-	}
+-  else
+-#endif /* USE_JPWL */
+-  {
+-    /* totlen is negative or larger than the bytes left!!! */
+-    if ((totlen < 0) || (totlen > (cio_numbytesleft(cio) + 8))) {
+-      opj_event_msg(j2k->cinfo, EVT_ERROR,
+-        "JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
+-        totlen, cio_numbytesleft(cio) + 8);
+-      return;
+-    }
+-  }
+-
+-	if (!totlen)
+-		totlen = cio_numbytesleft(cio) + 8;
+-	
+-	partno = cio_read(cio, 1);
+-	numparts = cio_read(cio, 1);
+-  
+-  if (partno >= numparts) {
+-    opj_event_msg(j2k->cinfo, EVT_WARNING, "SOT marker inconsistency in tile %d: tile-part index greater (%d) than number of tile-parts (%d)\n", tileno, partno, numparts);
+-    numparts = partno+1;
+-  }
+-	
+-	j2k->curtileno = tileno;
+-	j2k->cur_tp_num = partno;
+-	j2k->eot = cio_getbp(cio) - 12 + totlen;
+-	j2k->state = J2K_STATE_TPH;
+-	tcp = &cp->tcps[j2k->curtileno];
+-
+-	/* Index */
+-	if (j2k->cstr_info) {
+-		if (tcp->first) {
+-			if (tileno == 0) 
+-				j2k->cstr_info->main_head_end = cio_tell(cio) - 13;
+-			j2k->cstr_info->tile[tileno].tileno = tileno;
+-			j2k->cstr_info->tile[tileno].start_pos = cio_tell(cio) - 12;
+-			j2k->cstr_info->tile[tileno].end_pos = j2k->cstr_info->tile[tileno].start_pos + totlen - 1;				
+-    } else {
+-			j2k->cstr_info->tile[tileno].end_pos += totlen;
+-		}
+-    j2k->cstr_info->tile[tileno].num_tps = numparts;
+-    if (numparts)
+-      j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, numparts * sizeof(opj_tp_info_t));
+-    else
+-      j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_realloc(j2k->cstr_info->tile[tileno].tp, 10 * sizeof(opj_tp_info_t)); /* Fixme (10)*/
+-		j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = cio_tell(cio) - 12;
+-		j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = 
+-			j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
+-	}
+-	
+-	if (tcp->first == 1) {		
+-		/* Initialization PPT */
+-		opj_tccp_t *tmp = tcp->tccps;
+-		memcpy(tcp, j2k->default_tcp, sizeof(opj_tcp_t));
+-		tcp->ppt = 0;
+-		tcp->ppt_data = NULL;
+-		tcp->ppt_data_first = NULL;
+-		tcp->tccps = tmp;
+-
+-		for (i = 0; i < j2k->image->numcomps; i++) {
+-			tcp->tccps[i] = j2k->default_tcp->tccps[i];
+-		}
+-		cp->tcps[j2k->curtileno].first = 0;
+-	}
+-}
+-
+-static void j2k_write_sod(opj_j2k_t *j2k, void *tile_coder) {
+-	int l, layno;
+-	int totlen;
+-	opj_tcp_t *tcp = NULL;
+-	opj_codestream_info_t *cstr_info = NULL;
+-	
+-	opj_tcd_t *tcd = (opj_tcd_t*)tile_coder;	/* cast is needed because of conflicts in header inclusions */
+-	opj_cp_t *cp = j2k->cp;
+-	opj_cio_t *cio = j2k->cio;
+-
+-	tcd->tp_num = j2k->tp_num ;
+-	tcd->cur_tp_num = j2k->cur_tp_num;
+-	
+-	cio_write(cio, J2K_MS_SOD, 2);
+-
+-	if( j2k->cstr_info && j2k->cur_tp_num==0){
+-	  j2k_add_tlmarker( j2k->curtileno, j2k->cstr_info, J2K_MS_SOD, cio_tell(cio), 0);
+-	}
+-
+-	if (j2k->curtileno == 0) {
+-		j2k->sod_start = cio_tell(cio) + j2k->pos_correction;
+-	}
+-
+-	/* INDEX >> */
+-	cstr_info = j2k->cstr_info;
+-	if (cstr_info) {
+-		if (!j2k->cur_tp_num ) {
+-			cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
+-			j2k->cstr_info->tile[j2k->curtileno].tileno = j2k->curtileno;
+-		}
+-		else{
+-			if(cstr_info->tile[j2k->curtileno].packet[cstr_info->packno - 1].end_pos < cio_tell(cio))
+-				cstr_info->tile[j2k->curtileno].packet[cstr_info->packno].start_pos = cio_tell(cio);
+-		}
+-		/* UniPG>> */
+-#ifdef USE_JPWL
+-		/* update markers struct */
+-		j2k_add_marker(j2k->cstr_info, J2K_MS_SOD, j2k->sod_start, 2);
+-#endif /* USE_JPWL */
+-		/* <<UniPG */
+-	}
+-	/* << INDEX */
+-	
+-	tcp = &cp->tcps[j2k->curtileno];
+-	for (layno = 0; layno < tcp->numlayers; layno++) {
+-		if (tcp->rates[layno]>(j2k->sod_start / (cp->th * cp->tw))) {
+-			tcp->rates[layno]-=(j2k->sod_start / (cp->th * cp->tw));
+-		} else if (tcp->rates[layno]) {
+-			tcp->rates[layno]=1;
+-		}
+-	}
+-	if(j2k->cur_tp_num == 0){
+-		tcd->tcd_image->tiles->packno = 0;
+-		if(cstr_info)
+-			cstr_info->packno = 0;
+-	}
+-	
+-	l = tcd_encode_tile(tcd, j2k->curtileno, cio_getbp(cio), cio_numbytesleft(cio) - 2, cstr_info);
+-	
+-	/* Writing Psot in SOT marker */
+-	totlen = cio_tell(cio) + l - j2k->sot_start;
+-	cio_seek(cio, j2k->sot_start + 6);
+-	cio_write(cio, totlen, 4);
+-	cio_seek(cio, j2k->sot_start + totlen);
+-	/* Writing Ttlm and Ptlm in TLM marker */
+-	if(cp->cinema){
+-		cio_seek(cio, j2k->tlm_start + 6 + (5*j2k->cur_tp_num));
+-		cio_write(cio, j2k->curtileno, 1);
+-		cio_write(cio, totlen, 4);
+-	}
+-	cio_seek(cio, j2k->sot_start + totlen);
+-}
+-
+-static void j2k_read_sod(opj_j2k_t *j2k) {
+-	int len, truncate = 0, i;
+-	unsigned char *data = NULL, *data_ptr = NULL;
+-
+-	opj_cio_t *cio = j2k->cio;
+-	int curtileno = j2k->curtileno;
+-
+-	/* Index */
+-	if (j2k->cstr_info) {
+-		j2k->cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
+-			cio_tell(cio) + j2k->pos_correction - 1;
+-		if (j2k->cur_tp_num == 0)
+-			j2k->cstr_info->tile[j2k->curtileno].end_header = cio_tell(cio) + j2k->pos_correction - 1;
+-		j2k->cstr_info->packno = 0;
+-	}
+-	
+-	len = int_min(j2k->eot - cio_getbp(cio), cio_numbytesleft(cio) + 1);
+-
+-	if (len == cio_numbytesleft(cio) + 1) {
+-		truncate = 1;		/* Case of a truncate codestream */
+-	}	
+-
+-	data = j2k->tile_data[curtileno];
+-  data_ptr = data; /* store in case of failure */
+-	data = (unsigned char*) opj_realloc(data, (j2k->tile_len[curtileno] + len) * sizeof(unsigned char));
+-  if( data == NULL ) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR, "Could not reallocated\n" );
+-    opj_free( data_ptr );
+-    return;
+-    }
 +OPJ_BOOL opj_j2k_pre_write_tile (       opj_j2k_t * p_j2k,
 +                                                                OPJ_UINT32 p_tile_index,
 +                                                                opj_stream_private_t *p_stream,
@@ -16254,27 +15627,95 @@ index d34c75f..881cc72 100644
 +                opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match." );
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	data_ptr = data + j2k->tile_len[curtileno];
+-	for (i = 0; i < len; i++) {
+-		data_ptr[i] = cio_read(cio, 1);
+-	}
+-
+-	j2k->tile_len[curtileno] += len;
+-	j2k->tile_data[curtileno] = data;
+-	
+-	if (!truncate) {
+-		j2k->state = J2K_STATE_TPHSOT;
+-	} else {
+-		j2k->state = J2K_STATE_NEOC;	/* RAJOUTE !! */
+-	}
+-	j2k->cur_tp_num++;
+-}
+-
+-static void j2k_write_rgn(opj_j2k_t *j2k, int compno, int tileno) {
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = &cp->tcps[tileno];
+-	opj_cio_t *cio = j2k->cio;
+-	int numcomps = j2k->image->numcomps;
+-	
+-	cio_write(cio, J2K_MS_RGN, 2);						/* RGN  */
+-	cio_write(cio, numcomps <= 256 ? 5 : 6, 2);			/* Lrgn */
+-	cio_write(cio, compno, numcomps <= 256 ? 1 : 2);	/* Crgn */
+-	cio_write(cio, 0, 1);								/* Srgn */
+-	cio_write(cio, tcp->tccps[compno].roishift, 1);		/* SPrgn */
+-}
+-
+-static void j2k_read_rgn(opj_j2k_t *j2k) {
+-	int len, compno, roisty;
+-
+-	opj_cp_t *cp = j2k->cp;
+-	opj_tcp_t *tcp = j2k->state == J2K_STATE_TPH ? &cp->tcps[j2k->curtileno] : j2k->default_tcp;
+-	opj_cio_t *cio = j2k->cio;
+-	int numcomps = j2k->image->numcomps;
+-
+-	len = cio_read(cio, 2);										/* Lrgn */
+-  (void)len;
+-	compno = cio_read(cio, numcomps <= 256 ? 1 : 2);			/* Crgn */
+-	roisty = cio_read(cio, 1);									/* Srgn */
+-  (void)roisty;
 +        opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n", p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
-+
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-		/* totlen is negative or larger than the bytes left!!! */
+-		if (compno >= numcomps) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"JPWL: bad component number in RGN (%d when there are only %d)\n",
+-				compno, numcomps);
+-			if (!JPWL_ASSUME || JPWL_ASSUME) {
+-				opj_event_msg(j2k->cinfo, EVT_ERROR, "JPWL: giving up\n");
+-				return;
+-			}
+-		}
+-	};
+-#endif /* USE_JPWL */
 +        p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
 +        p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
 +        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
-+
+ 
+-  if (compno >= numcomps) {
+-    opj_event_msg(j2k->cinfo, EVT_ERROR,
+-      "bad component number in RGN (%d out of a maximum of %d)\n",
+-      compno, j2k->image->numcomps);
+-    return;
+-  }
 +        /* initialisation before tile encoding  */
 +        if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	tcp->tccps[compno].roishift = cio_read(cio, 1);				/* SPrgn */
 +        return OPJ_TRUE;
-+}
+ }
  
--			cp->sens_MH = parameters->jpwl_sens_MH;
--			for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
--				cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
--				cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
--			}
--		}
+-static void j2k_write_eoc(opj_j2k_t *j2k) {
+-	opj_cio_t *cio = j2k->cio;
+-	/* opj_event_msg(j2k->cinfo, "%.8x: EOC\n", cio_tell(cio) + j2k->pos_correction); */
+-	cio_write(cio, J2K_MS_EOC, 2);
+-
+-/* UniPG>> */
+-#ifdef USE_JPWL
+-	/* update markers struct */
+-	j2k_add_marker(j2k->cstr_info, J2K_MS_EOC, cio_tell(cio) - 2, 2);
+-#endif /* USE_JPWL */
+-/* <<UniPG */
 +void opj_j2k_get_tile_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
 +{
 +        OPJ_UINT32 i,j,k = 0;
@@ -16376,10 +15817,80 @@ index d34c75f..881cc72 100644
 +                ++l_img_comp;
 +                ++l_tilec;
 +        }
-+}
+ }
  
--		/* always set RED writing to false: we are at the encoder */
--		cp->red_on = OPJ_FALSE;
+-static void j2k_read_eoc(opj_j2k_t *j2k) {
+-	int i, tileno;
+-	opj_bool success = OPJ_FALSE;
+-
+-	/* if packets should be decoded */
+-	if (j2k->cp->limit_decoding != DECODE_ALL_BUT_PACKETS) {
+-		opj_tcd_t *tcd = tcd_create(j2k->cinfo);
+-		tcd_malloc_decode(tcd, j2k->image, j2k->cp);
+-		for (i = 0; i < j2k->cp->tileno_size; i++) {
+-			tcd_malloc_decode_tile(tcd, j2k->image, j2k->cp, i, j2k->cstr_info);
+-			if (j2k->cp->tileno[i] != -1)
+-			{
+-				tileno = j2k->cp->tileno[i];
+-				success = tcd_decode_tile(tcd, j2k->tile_data[tileno], j2k->tile_len[tileno], tileno, j2k->cstr_info);
+-        assert( tileno != -1 );
+-				opj_free(j2k->tile_data[tileno]);
+-				j2k->tile_data[tileno] = NULL;
+-				tcd_free_decode_tile(tcd, i);
+-			}
+-			else
+-				success = OPJ_FALSE;
+-			if (success == OPJ_FALSE) {
+-				j2k->state |= J2K_STATE_ERR;
+-				break;
+-			}
+-		}
+-		tcd_free_decode(tcd);
+-		tcd_destroy(tcd);
+-	}
+-	/* if packets should not be decoded  */
+-	else {
+-		for (i = 0; i < j2k->cp->tileno_size; i++) {
+-			tileno = j2k->cp->tileno[i];
+-			opj_free(j2k->tile_data[tileno]);
+-			j2k->tile_data[tileno] = NULL;
+-		}
+-	}	
+-	if (j2k->state & J2K_STATE_ERR)
+-		j2k->state = J2K_STATE_MT + J2K_STATE_ERR;
+-	else
+-		j2k->state = J2K_STATE_MT; 
+-}
+-
+-typedef struct opj_dec_mstabent {
+-	/** marker value */
+-	int id;
+-	/** value of the state when the marker can appear */
+-	int states;
+-	/** action linked to the marker */
+-	void (*handler) (opj_j2k_t *j2k);
+-} opj_dec_mstabent_t;
+-
+-opj_dec_mstabent_t j2k_dec_mstab[] = {
+-  {J2K_MS_SOC, J2K_STATE_MHSOC, j2k_read_soc},
+-  {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, j2k_read_sot},
+-  {J2K_MS_SOD, J2K_STATE_TPH, j2k_read_sod},
+-  {J2K_MS_EOC, J2K_STATE_TPHSOT, j2k_read_eoc},
+-  {J2K_MS_SIZ, J2K_STATE_MHSIZ, j2k_read_siz},
+-  {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_cod},
+-  {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_coc},
+-  {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_rgn},
+-  {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcd},
+-  {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_qcc},
+-  {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_poc},
+-  {J2K_MS_TLM, J2K_STATE_MH, j2k_read_tlm},
+-  {J2K_MS_PLM, J2K_STATE_MH, j2k_read_plm},
+-  {J2K_MS_PLT, J2K_STATE_TPH, j2k_read_plt},
+-  {J2K_MS_PPM, J2K_STATE_MH, j2k_read_ppm},
+-  {J2K_MS_PPT, J2K_STATE_TPH, j2k_read_ppt},
+-  {J2K_MS_SOP, 0, 0},
+-  {J2K_MS_CRG, J2K_STATE_MH, j2k_read_crg},
+-  {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_com},
 +OPJ_BOOL opj_j2k_post_write_tile (      opj_j2k_t * p_j2k,
 +                                                                OPJ_BYTE * p_data,
 +                                                                OPJ_UINT32 p_data_size,
@@ -16405,373 +15916,155 @@ index d34c75f..881cc72 100644
 +                opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data." );
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-#ifdef USE_JPWL
+-  {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
+-  {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
+-  {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
+-  {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
+-#endif /* USE_JPWL */
+-#ifdef USE_JPSEC
+-  {J2K_MS_SEC, J2K_STATE_MH, j2k_read_sec},
+-  {J2K_MS_INSEC, 0, j2k_read_insec},
+-#endif /* USE_JPSEC */
 +        l_nb_bytes_written = 0;
 +        if (! opj_j2k_write_first_tile_part(p_j2k,l_current_data,&l_nb_bytes_written,l_available_data,p_stream,p_manager)) {
 +                return OPJ_FALSE;
 +        }
 +        l_current_data += l_nb_bytes_written;
 +        l_available_data -= l_nb_bytes_written;
-+
+ 
+-  {0, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_unk}
+-};
 +        l_nb_bytes_written = 0;
 +        if (! opj_j2k_write_all_tile_parts(p_j2k,l_current_data,&l_nb_bytes_written,l_available_data,p_stream,p_manager)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-static void j2k_read_unk(opj_j2k_t *j2k) {
+-	opj_event_msg(j2k->cinfo, EVT_WARNING, "Unknown marker\n");
 +        l_available_data -= l_nb_bytes_written;
 +        l_nb_bytes_written = l_tile_size - l_available_data;
-+
+ 
+-#ifdef USE_JPWL
+-	if (j2k->cp->correct) {
+-		int m = 0, id, i;
+-		int min_id = 0, min_dist = 17, cur_dist = 0, tmp_id;
+-		cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
+-		id = cio_read(j2k->cio, 2);
+-		opj_event_msg(j2k->cinfo, EVT_ERROR,
+-			"JPWL: really don't know this marker %x\n",
+-			id);
+-		if (!JPWL_ASSUME) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"- possible synch loss due to uncorrectable codestream errors => giving up\n");
+-			return;
+-		}
+-		/* OK, activate this at your own risk!!! */
+-		/* we look for the marker at the minimum hamming distance from this */
+-		while (j2k_dec_mstab[m].id) {
+-			
+-			/* 1's where they differ */
+-			tmp_id = j2k_dec_mstab[m].id ^ id;
+-
+-			/* compute the hamming distance between our id and the current */
+-			cur_dist = 0;
+-			for (i = 0; i < 16; i++) {
+-				if ((tmp_id >> i) & 0x0001) {
+-					cur_dist++;
+-				}
+-			}
+-
+-			/* if current distance is smaller, set the minimum */
+-			if (cur_dist < min_dist) {
+-				min_dist = cur_dist;
+-				min_id = j2k_dec_mstab[m].id;
+-			}
+-			
+-			/* jump to the next marker */
+-			m++;
+-		}
 +        if ( opj_stream_write_data(     p_stream,
 +                                                                p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
 +                                                                l_nb_bytes_written,p_manager) != l_nb_bytes_written) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-		/* do we substitute the marker? */
+-		if (min_dist < JPWL_MAXIMUM_HAMMING) {
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"- marker %x is at distance %d from the read %x\n",
+-				min_id, min_dist, id);
+-			opj_event_msg(j2k->cinfo, EVT_ERROR,
+-				"- trying to substitute in place and crossing fingers!\n");
+-			cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
+-			cio_write(j2k->cio, min_id, 2);
 +        ++p_j2k->m_current_tile_number;
-+
+ 
+-			/* rewind */
+-			cio_seek(j2k->cio, cio_tell(j2k->cio) - 2);
 +        return OPJ_TRUE;
 +}
  
--	} else {
--		cp->epc_on = OPJ_FALSE;
--	}
--#endif /* USE_JPWL */
+-		}
 +void opj_j2k_setup_end_compress (opj_j2k_t *p_j2k)
 +{
 +        /* preconditions */
 +        assert(p_j2k != 00);
  
+-	};
+-#endif /* USE_JPWL */
 +        /* DEVELOPER CORNER, insert your custom procedures */
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_eoc );
  
--	/* initialize the mutiple tiles */
--	/* ---------------------------- */
--	cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
--
--	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
--		opj_tcp_t *tcp = &cp->tcps[tileno];
--		tcp->numlayers = parameters->tcp_numlayers;
--		for (j = 0; j < tcp->numlayers; j++) {
--			if(cp->cinema){
--				if (cp->fixed_quality) {
--					tcp->distoratio[j] = parameters->tcp_distoratio[j];
--				}
--				tcp->rates[j] = parameters->tcp_rates[j];
--			}else{
--				if (cp->fixed_quality) {	/* add fixed_quality */
--					tcp->distoratio[j] = parameters->tcp_distoratio[j];
--				} else {
--					tcp->rates[j] = parameters->tcp_rates[j];
--				}
--			}
--		}
--		tcp->csty = parameters->csty;
--		tcp->prg = parameters->prog_order;
--		tcp->mct = parameters->tcp_mct; 
--
--		numpocs_tile = 0;
--		tcp->POC = 0;
--		if (parameters->numpocs) {
--			/* initialisation of POC */
--			tcp->POC = 1;
--			for (i = 0; i < parameters->numpocs; i++) {
--				if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {
--					opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
--					tcp_poc->resno0		= parameters->POC[numpocs_tile].resno0;
--					tcp_poc->compno0	= parameters->POC[numpocs_tile].compno0;
--					tcp_poc->layno1		= parameters->POC[numpocs_tile].layno1;
--					tcp_poc->resno1		= parameters->POC[numpocs_tile].resno1;
--					tcp_poc->compno1	= parameters->POC[numpocs_tile].compno1;
--					tcp_poc->prg1		= parameters->POC[numpocs_tile].prg1;
--					tcp_poc->tile		= parameters->POC[numpocs_tile].tile;
--					numpocs_tile++;
--				}
--			}
--			tcp->numpocs = numpocs_tile -1 ;
--		}else{ 
--			tcp->numpocs = 0;
--		}
+-}
 +        if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
 +                opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_updated_tlm);
 +        }
  
--		tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
--
--		for (i = 0; i < image->numcomps; i++) {
--			opj_tccp_t *tccp = &tcp->tccps[i];
--			tccp->csty = parameters->csty & 0x01;	/* 0 => one precinct || 1 => custom precinct  */
--			tccp->numresolutions = parameters->numresolution;
--			tccp->cblkw = int_floorlog2(parameters->cblockw_init);
--			tccp->cblkh = int_floorlog2(parameters->cblockh_init);
--			tccp->cblksty = parameters->mode;
--			tccp->qmfbid = parameters->irreversible ? 0 : 1;
--			tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
--			tccp->numgbits = 2;
--			if (i == parameters->roi_compno) {
--				tccp->roishift = parameters->roi_shift;
--			} else {
--				tccp->roishift = 0;
--			}
--
--			if(parameters->cp_cinema)
--			{
--				/*Precinct size for lowest frequency subband=128*/
--				tccp->prcw[0] = 7;
--				tccp->prch[0] = 7;
--				/*Precinct size at all other resolutions = 256*/
--				for (j = 1; j < tccp->numresolutions; j++) {
--					tccp->prcw[j] = 8;
--					tccp->prch[j] = 8;
--				}
--			}else{
--				if (parameters->csty & J2K_CCP_CSTY_PRT) {
--					int p = 0;
--					for (j = tccp->numresolutions - 1; j >= 0; j--) {
--						if (p < parameters->res_spec) {
--							
--							if (parameters->prcw_init[p] < 1) {
--								tccp->prcw[j] = 1;
--							} else {
--								tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]);
--							}
--							
--							if (parameters->prch_init[p] < 1) {
--								tccp->prch[j] = 1;
--							}else {
--								tccp->prch[j] = int_floorlog2(parameters->prch_init[p]);
--							}
--
--						} else {
--							int res_spec = parameters->res_spec;
--							int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
--							int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
--							
--							if (size_prcw < 1) {
--								tccp->prcw[j] = 1;
--							} else {
--								tccp->prcw[j] = int_floorlog2(size_prcw);
--							}
--							
--							if (size_prch < 1) {
--								tccp->prch[j] = 1;
--							} else {
--								tccp->prch[j] = int_floorlog2(size_prch);
--							}
--						}
--						p++;
--						/*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */
--					}	/*end for*/
--				} else {
--					for (j = 0; j < tccp->numresolutions; j++) {
--						tccp->prcw[j] = 15;
--						tccp->prch[j] = 15;
--					}
--				}
--			}
--
--			dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
--		}
--	}
--}
--
--opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
--	int tileno, compno;
--	opj_cp_t *cp = NULL;
--
--	opj_tcd_t *tcd = NULL;	/* TCD component */
--
--	j2k->cio = cio;	
--	j2k->image = image;
--
--	cp = j2k->cp;
--
--	/* INDEX >> */
--	j2k->cstr_info = cstr_info;
--	if (cstr_info) {
--		int compno;
--		cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t));
--		cstr_info->image_w = image->x1 - image->x0;
--		cstr_info->image_h = image->y1 - image->y0;
--		cstr_info->prog = (&cp->tcps[0])->prg;
--		cstr_info->tw = cp->tw;
--		cstr_info->th = cp->th;
--		cstr_info->tile_x = cp->tdx;	/* new version parser */
--		cstr_info->tile_y = cp->tdy;	/* new version parser */
--		cstr_info->tile_Ox = cp->tx0;	/* new version parser */
--		cstr_info->tile_Oy = cp->ty0;	/* new version parser */
--		cstr_info->numcomps = image->numcomps;
--		cstr_info->numlayers = (&cp->tcps[0])->numlayers;
--		cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
--		for (compno=0; compno < image->numcomps; compno++) {
--			cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1;
--		}
--		cstr_info->D_max = 0.0;		/* ADD Marcela */
--		cstr_info->main_head_start = cio_tell(cio); /* position of SOC */
--		cstr_info->maxmarknum = 100;
--		cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t));
--		cstr_info->marknum = 0;
--	}
--	/* << INDEX */
--
--	j2k_write_soc(j2k);
--	j2k_write_siz(j2k);
--	j2k_write_cod(j2k);
--	j2k_write_qcd(j2k);
--
--	if(cp->cinema){
--		for (compno = 1; compno < image->numcomps; compno++) {
--			j2k_write_coc(j2k, compno);
--			j2k_write_qcc(j2k, compno);
--		}
--	}
--
--	for (compno = 0; compno < image->numcomps; compno++) {
--		opj_tcp_t *tcp = &cp->tcps[0];
--		if (tcp->tccps[compno].roishift)
--			j2k_write_rgn(j2k, compno, 0);
--	}
--	if (cp->comment != NULL) {
--		j2k_write_com(j2k);
--	}
--
--	j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k);
--	/* TLM Marker*/
--	if(cp->cinema){
--		j2k_write_tlm(j2k);
--		if (cp->cinema == CINEMA4K_24) {
--			j2k_write_poc(j2k);
--		}
--	}
--
--	/* uncomment only for testing JPSEC marker writing */
--	/* j2k_write_sec(j2k); */
--
--	/* INDEX >> */
--	if(cstr_info) {
--		cstr_info->main_head_end = cio_tell(cio) - 1;
--	}
--	/* << INDEX */
--	/**** Main Header ENDS here ***/
--
--	/* create the tile encoder */
--	tcd = tcd_create(j2k->cinfo);
--
--	/* encode each tile */
--	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
--		int pino;
--		int tilepartno=0;
--		/* UniPG>> */
--		int acc_pack_num = 0;
--		/* <<UniPG */
--
--
--		opj_tcp_t *tcp = &cp->tcps[tileno];
--		opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th);
--
--		j2k->curtileno = tileno;
--		j2k->cur_tp_num = 0;
--		tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno];
--		/* initialisation before tile encoding  */
--		if (tileno == 0) {
--			tcd_malloc_encode(tcd, image, cp, j2k->curtileno);
--		} else {
--			tcd_init_encode(tcd, image, cp, j2k->curtileno);
--		}
-+        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_epc );
-+        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_end_encoding );
-+        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_destroy_header_memory);
-+}
- 
--		/* INDEX >> */
--		if(cstr_info) {
--			cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction;
--			cstr_info->tile[j2k->curtileno].maxmarknum = 10;
--			cstr_info->tile[j2k->curtileno].marker = (opj_marker_info_t *) opj_malloc(cstr_info->tile[j2k->curtileno].maxmarknum * sizeof(opj_marker_info_t));
--			cstr_info->tile[j2k->curtileno].marknum = 0;
--		}
--		/* << INDEX */
--
--		for(pino = 0; pino <= tcp->numpocs; pino++) {
--			int tot_num_tp;
--			tcd->cur_pino=pino;
--
--			/*Get number of tile parts*/
--			tot_num_tp = j2k_get_num_tp(cp,pino,tileno);
--			tcd->tp_pos = cp->tp_pos;
--
--			for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){
--				j2k->tp_num = tilepartno;
--				/* INDEX >> */
--				if(cstr_info)
--					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos =
--					cio_tell(cio) + j2k->pos_correction;
--				/* << INDEX */
--				j2k_write_sot(j2k);
--
--				if(j2k->cur_tp_num == 0 && cp->cinema == 0){
--					for (compno = 1; compno < image->numcomps; compno++) {
--						j2k_write_coc(j2k, compno);
--						j2k_write_qcc(j2k, compno);
--					}
--					if (cp->tcps[tileno].numpocs) {
--						j2k_write_poc(j2k);
--					}
--				}
--
--				/* INDEX >> */
--				if(cstr_info)
--					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
--					cio_tell(cio) + j2k->pos_correction + 1;
--				/* << INDEX */
--
--				j2k_write_sod(j2k, tcd);
--
--				/* INDEX >> */
--				if(cstr_info) {
--					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos =
--						cio_tell(cio) + j2k->pos_correction - 1;
--					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack =
--						acc_pack_num;
--					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks =
--						cstr_info->packno - acc_pack_num;
--					acc_pack_num = cstr_info->packno;
--				}
--				/* << INDEX */
--
--				j2k->cur_tp_num++;
--			}			
--		}
--		if(cstr_info) {
--			cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1;
+-/**
+-Read the lookup table containing all the marker, status and action
+- at param id Marker value
+-*/
+-static opj_dec_mstabent_t *j2k_dec_mstab_lookup(int id) {
+-	opj_dec_mstabent_t *e;
+-	for (e = j2k_dec_mstab; e->id != 0; e++) {
+-		if (e->id == id) {
+-			break;
 -		}
+-	}
+-	return e;
++        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_epc );
++        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_end_encoding );
++        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_destroy_header_memory);
+ }
+ 
+-/* ----------------------------------------------------------------------- */
+-/* J2K / JPT decoder interface                                             */
+-/* ----------------------------------------------------------------------- */
 +void opj_j2k_setup_encoding_validation (opj_j2k_t *p_j2k)
 +{
 +        /* preconditions */
 +        assert(p_j2k != 00);
  
+-opj_j2k_t* j2k_create_decompress(opj_common_ptr cinfo) {
+-	opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
+-	if(!j2k)
+-		return NULL;
 +        opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_encoder);
 +        opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_encoding_validation);
  
--		/*
--		if (tile->PPT) { // BAD PPT !!! 
--		FILE *PPT_file;
--		int i;
--		PPT_file=fopen("PPT","rb");
--		fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256);
--		for (i=0;i<tile->len_ppt;i++) {
--		unsigned char elmt;
--		fread(&elmt, 1, 1, PPT_file);
--		fwrite(&elmt,1,1,f);
--		}
--		fclose(PPT_file);
--		unlink("PPT");
--		}
--		*/
+-	j2k->default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t));
+-	if(!j2k->default_tcp) {
+-		opj_free(j2k);
+-		return NULL;
+-	}
 +        /* DEVELOPER CORNER, add your custom validation procedure */
 +        opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_mct_validation);
 +}
  
--	}
+-	j2k->cinfo = cinfo;
+-	j2k->tile_data = NULL;
 +void opj_j2k_setup_header_writing (opj_j2k_t *p_j2k)
 +{
 +        /* preconditions */
@@ -16794,30 +16087,88 @@ index d34c75f..881cc72 100644
 +                        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_poc );
 +                }
 +        }
-+
+ 
+-	return j2k;
+-}
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_regions);
-+
+ 
+-void j2k_destroy_decompress(opj_j2k_t *j2k) {
+-	int i = 0;
 +        if (p_j2k->m_cp.comment != 00)  {
 +                opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_com);
 +        }
-+
+ 
+-	if(j2k->tile_len != NULL) {
+-		opj_free(j2k->tile_len);
+-	}
+-	if(j2k->tile_data != NULL) {
+-        if(j2k->cp != NULL) {
+-            for (i = 0; i < j2k->cp->tileno_size; i++) {
+-                int tileno = j2k->cp->tileno[i];
+-                if( tileno != -1 )
+-                  {
+-                  opj_free(j2k->tile_data[tileno]);
+-                  j2k->tile_data[tileno] = NULL;
+-                  }
+-            }
 +        /* DEVELOPER CORNER, insert your custom procedures */
 +        if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
 +                opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_mct_data_group );
-+        }
+         }
 +        /* End of Developer Corner */
-+
+ 
+-		opj_free(j2k->tile_data);
+-	}
+-	if(j2k->default_tcp != NULL) {
+-		opj_tcp_t *default_tcp = j2k->default_tcp;
+-		if(default_tcp->ppt_data_first != NULL) {
+-			opj_free(default_tcp->ppt_data_first);
+-		}
+-		if(j2k->default_tcp->tccps != NULL) {
+-			opj_free(j2k->default_tcp->tccps);
+-		}
+-		opj_free(j2k->default_tcp);
+-	}
+-	if(j2k->cp != NULL) {
+-		opj_cp_t *cp = j2k->cp;
+-		if(cp->tcps != NULL) {
+-			for(i = 0; i < cp->tw * cp->th; i++) {
+-				if(cp->tcps[i].ppt_data_first != NULL) {
+-					opj_free(cp->tcps[i].ppt_data_first);
+-				}
+-				if(cp->tcps[i].tccps != NULL) {
+-					opj_free(cp->tcps[i].tccps);
+-				}
+-			}
+-			opj_free(cp->tcps);
+-		}
+-		if(cp->ppm_data_first != NULL) {
+-			opj_free(cp->ppm_data_first);
+-		}
+-		if(cp->tileno != NULL) {
+-			opj_free(cp->tileno);  
+-		}
+-		if(cp->comment != NULL) {
+-			opj_free(cp->comment);
+-		}
 +        if (p_j2k->cstr_index) {
 +                opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_get_end_header );
 +        }
-+
+ 
+-		opj_free(cp);
+-	}
+-	opj_free(j2k);
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_create_tcd);
 +        opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_update_rates);
-+}
+ }
  
--	/* destroy the tile encoder */
--	tcd_free_encode(tcd);
--	tcd_destroy(tcd);
+-void j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) {
+-	if(j2k && parameters) {
+-		/* create and initialize the coding parameters structure */
+-		opj_cp_t *cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
+-		cp->reduce = parameters->cp_reduce;	
+-		cp->layer = parameters->cp_layer;
+-		cp->limit_decoding = parameters->cp_limit_decoding;
 +OPJ_BOOL opj_j2k_write_first_tile_part (opj_j2k_t *p_j2k,
 +                                                                        OPJ_BYTE * p_data,
 +                                                                        OPJ_UINT32 * p_data_written,
@@ -16828,28 +16179,47 @@ index d34c75f..881cc72 100644
 +        OPJ_UINT32 l_nb_bytes_written = 0;
 +        OPJ_UINT32 l_current_nb_bytes_written;
 +        OPJ_BYTE * l_begin_data = 00;
-+
+ 
+-#ifdef USE_JPWL
+-		cp->correct = parameters->jpwl_correct;
+-		cp->exp_comps = parameters->jpwl_exp_comps;
+-		cp->max_tiles = parameters->jpwl_max_tiles;
+-#endif /* USE_JPWL */
 +        opj_tcd_t * l_tcd = 00;
 +        opj_cp_t * l_cp = 00;
-+
+ 
 +        l_tcd = p_j2k->m_tcd;
 +        l_cp = &(p_j2k->m_cp);
-+
+ 
+-		/* keep a link to cp so that we can destroy it later in j2k_destroy_decompress */
+-		j2k->cp = cp;
+-	}
+-}
 +        l_tcd->cur_pino = 0;
-+
+ 
+-opj_image_t* j2k_decode(opj_j2k_t *j2k, opj_cio_t *cio, opj_codestream_info_t *cstr_info) {
+-	opj_image_t *image = NULL;
 +        /*Get number of tile parts*/
 +        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
-+
+ 
+-	opj_common_ptr cinfo = j2k->cinfo;	
 +        /* INDEX >> */
 +        /* << INDEX */
-+
+ 
+-	j2k->cio = cio;
+-	j2k->cstr_info = cstr_info;
+-	if (cstr_info)
+-		memset(cstr_info, 0, sizeof(opj_codestream_info_t));
 +        l_current_nb_bytes_written = 0;
 +        l_begin_data = p_data;
 +        if (! opj_j2k_write_sot(p_j2k,p_data,&l_current_nb_bytes_written,p_stream,p_manager))
 +        {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	/* create an empty image */
+-	image = opj_image_create0();
+-	j2k->image = image;
 +        l_nb_bytes_written += l_current_nb_bytes_written;
 +        p_data += l_current_nb_bytes_written;
 +        p_total_data_size -= l_current_nb_bytes_written;
@@ -16871,7 +16241,7 @@ index d34c75f..881cc72 100644
 +                }
 +#endif
  
--	opj_free(j2k->cur_totnum_tp);
+-	j2k->state = J2K_STATE_MHSOC;
 +                if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
 +                        l_current_nb_bytes_written = 0;
 +                        opj_j2k_write_poc_in_memory(p_j2k,p_data,&l_current_nb_bytes_written,p_manager);
@@ -16881,43 +16251,200 @@ index d34c75f..881cc72 100644
 +                }
 +        }
  
--	j2k_write_eoc(j2k);
+-	for (;;) {
+-		opj_dec_mstabent_t *e;
+-		int id = cio_read(cio, 2);
 +        l_current_nb_bytes_written = 0;
 +        if (! opj_j2k_write_sod(p_j2k,l_tcd,p_data,&l_current_nb_bytes_written,p_total_data_size,p_stream,p_manager)) {
 +                return OPJ_FALSE;
 +        }
  
--	if(cstr_info) {
--		cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction;
--		/* UniPG>> */
--		/* The following adjustment is done to adjust the codestream size */
--		/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
--		/* the first bunch of bytes is not in the codestream              */
--		cstr_info->codestream_size -= cstr_info->main_head_start;
--		/* <<UniPG */
--	}
+-#ifdef USE_JPWL
+-		/* we try to honor JPWL correction power */
+-		if (j2k->cp->correct) {
+-
+-			int orig_pos = cio_tell(cio);
+-			opj_bool status;
+-
+-			/* call the corrector */
+-			status = jpwl_correct(j2k);
+-
+-			/* go back to where you were */
+-			cio_seek(cio, orig_pos - 2);
+-
+-			/* re-read the marker */
+-			id = cio_read(cio, 2);
+-
+-			/* check whether it begins with ff */
+-			if (id >> 8 != 0xff) {
+-				opj_event_msg(cinfo, EVT_ERROR,
+-					"JPWL: possible bad marker %x at %d\n",
+-					id, cio_tell(cio) - 2);
+-				if (!JPWL_ASSUME) {
+-					opj_image_destroy(image);
+-					opj_event_msg(cinfo, EVT_ERROR, "JPWL: giving up\n");
+-					return 0;
+-				}
+-				/* we try to correct */
+-				id = id | 0xff00;
+-				cio_seek(cio, cio_tell(cio) - 2);
+-				cio_write(cio, id, 2);
+-				opj_event_msg(cinfo, EVT_WARNING, "- trying to adjust this\n"
+-					"- setting marker to %x\n",
+-					id);
+-			}
 +        l_nb_bytes_written += l_current_nb_bytes_written;
 +        * p_data_written = l_nb_bytes_written;
  
--#ifdef USE_JPWL
--	/*
--	preparation of JPWL marker segments
--	*/
--	if(cp->epc_on) {
+-		}
+-#endif /* USE_JPWL */
 +        /* Writing Psot in SOT marker */
 +        opj_write_bytes(l_begin_data + 6,l_nb_bytes_written,4);                                 /* PSOT */
  
--		/* encode according to JPWL */
--		jpwl_encode(j2k, cio, image);
+-		if (id >> 8 != 0xff) {
+-		if(cio_numbytesleft(cio) != 0) /* not end of file reached and no EOC */
+-	   {
+-		opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+-		opj_image_destroy(image);
+-		return 0;
+-	   }
+-		opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+-		j2k->state = J2K_STATE_NEOC;
+-		break;
+-		}
+-		e = j2k_dec_mstab_lookup(id);
+-		/* Check if the marker is known*/
+-		if (!(j2k->state & e->states)) {
+-			opj_image_destroy(image);
+-			opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
+-			return 0;
+-		}
+-		/* Check if the decoding is limited to the main header*/
+-		if (e->id == J2K_MS_SOT && j2k->cp->limit_decoding == LIMIT_TO_MAIN_HEADER) {
+-			opj_event_msg(cinfo, EVT_INFO, "Main Header decoded.\n");
+-			return image;
+-		}		
+-
+-		if (e->handler) {
+-			(*e->handler)(j2k);
+-		}
+-		if (j2k->state & J2K_STATE_ERR) 
+-        {
+-            opj_image_destroy(image);
+-			return NULL;	
 +        if (OPJ_IS_CINEMA(l_cp->rsiz)){
 +                opj_j2k_update_tlm(p_j2k,l_nb_bytes_written);
-+        }
+         }
  
+-		if (j2k->state == J2K_STATE_MT) {
+-			break;
+-		}
+-		if (j2k->state == J2K_STATE_NEOC) {
+-			break;
+-		}
 -	}
--#endif /* USE_JPWL */
+-	if (j2k->state == J2K_STATE_NEOC) {
+-		j2k_read_eoc(j2k);
+-		/* Check one last time for errors during decoding before returning */
+-		if (j2k->state & J2K_STATE_ERR) {
+-			opj_image_destroy(image);
+-			return NULL;
+-		}
+-	}
+-
+-	if (j2k->state != J2K_STATE_MT) {
+-		opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
+-	}
+-	return image;
 +        return OPJ_TRUE;
-+}
-+
+ }
+ 
+-/*
+-* Read a JPT-stream and decode file
+-*
+-*/
+-opj_image_t* j2k_decode_jpt_stream(opj_j2k_t *j2k, opj_cio_t *cio,  opj_codestream_info_t *cstr_info) {
+-	opj_image_t *image = NULL;
+-	opj_jpt_msg_header_t header;
+-	int position;
+-	opj_common_ptr cinfo = j2k->cinfo;
+-
+-	OPJ_ARG_NOT_USED(cstr_info);
+-
+-	j2k->cio = cio;
+-
+-	/* create an empty image */
+-	image = opj_image_create0();
+-	j2k->image = image;
+-
+-	j2k->state = J2K_STATE_MHSOC;
+-	
+-	/* Initialize the header */
+-	jpt_init_msg_header(&header);
+-	/* Read the first header of the message */
+-	jpt_read_msg_header(cinfo, cio, &header);
+-	
+-	position = cio_tell(cio);
+-	if (header.Class_Id != 6) {	/* 6 : Main header data-bin message */
+-		opj_image_destroy(image);
+-		opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Main header first [class_Id %d] !\n", header.Class_Id);
+-		return 0;
+-	}
+-	
+-	for (;;) {
+-		opj_dec_mstabent_t *e = NULL;
+-		int id;
+-		
+-		if (!cio_numbytesleft(cio)) {
+-			j2k_read_eoc(j2k);
+-			return image;
+-		}
+-		/* data-bin read -> need to read a new header */
+-		if ((unsigned int) (cio_tell(cio) - position) == header.Msg_length) {
+-			jpt_read_msg_header(cinfo, cio, &header);
+-			position = cio_tell(cio);
+-			if (header.Class_Id != 4) {	/* 4 : Tile data-bin message */
+-				opj_image_destroy(image);
+-				opj_event_msg(cinfo, EVT_ERROR, "[JPT-stream] : Expecting Tile info !\n");
+-				return 0;
+-			}
+-		}
+-		
+-		id = cio_read(cio, 2);
+-		if (id >> 8 != 0xff) {
+-        if(cio_numbytesleft(cio) != 0) /* no end of file reached and no EOC */
+-	  {
+-		opj_event_msg(cinfo, EVT_ERROR, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+-		opj_image_destroy(image);
+-		return 0;
+-	  }
+-		opj_event_msg(cinfo, EVT_WARNING, "%.8x: expected a marker instead of %x\n", cio_tell(cio) - 2, id);
+-		j2k->state = J2K_STATE_NEOC;
+-		break;
+-		}
+-		e = j2k_dec_mstab_lookup(id);
+-		if (!(j2k->state & e->states)) {
+-			opj_image_destroy(image);
+-			opj_event_msg(cinfo, EVT_ERROR, "%.8x: unexpected marker %x\n", cio_tell(cio) - 2, id);
+-			return 0;
+-		}
+-		if (e->handler) {
+-			(*e->handler)(j2k);
+-		}
+-		if (j2k->state == J2K_STATE_MT) {
+-			break;
+-		}
+-		if (j2k->state == J2K_STATE_NEOC) {
+-			break;
+-		}
+-	}
+-	if (j2k->state == J2K_STATE_NEOC) {
+-		j2k_read_eoc(j2k);
+-	}
+-	
+-	if (j2k->state != J2K_STATE_MT) {
+-		opj_event_msg(cinfo, EVT_WARNING, "Incomplete bitstream\n");
+-	}
 +OPJ_BOOL opj_j2k_write_all_tile_parts(  opj_j2k_t *p_j2k,
 +                                                                        OPJ_BYTE * p_data,
 +                                                                        OPJ_UINT32 * p_data_written,
@@ -16981,10 +16508,15 @@ index d34c75f..881cc72 100644
 +
 +                ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
 +        }
-+
+ 
+-	return image;
+-}
 +        for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
 +                l_tcd->cur_pino = pino;
-+
+ 
+-/* ----------------------------------------------------------------------- */
+-/* J2K encoder interface                                                       */
+-/* ----------------------------------------------------------------------- */
 +                /*Get number of tile parts*/
 +                tot_num_tp = opj_j2k_get_num_tp(l_cp,pino,p_j2k->m_current_tile_number);
 +                for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
@@ -17012,7 +16544,13 @@ index d34c75f..881cc72 100644
 +                        p_data += l_current_nb_bytes_written;
 +                        p_total_data_size -= l_current_nb_bytes_written;
 +                        l_part_tile_size += l_current_nb_bytes_written;
-+
+ 
+-opj_j2k_t* j2k_create_compress(opj_common_ptr cinfo) {
+-	opj_j2k_t *j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t));
+-	if(j2k) {
+-		j2k->cinfo = cinfo;
+-	}
+-	return j2k;
 +                        /* Writing Psot in SOT marker */
 +                        opj_write_bytes(l_begin_data + 6,l_part_tile_size,4);                                   /* PSOT */
 +
@@ -17027,41 +16565,176 @@ index d34c75f..881cc72 100644
 +        *p_data_written = l_nb_bytes_written;
 +
 +        return OPJ_TRUE;
-+}
-+
+ }
+ 
+-void j2k_destroy_compress(opj_j2k_t *j2k) {
+-	int tileno;
 +OPJ_BOOL opj_j2k_write_updated_tlm( opj_j2k_t *p_j2k,
 +                                                                    struct opj_stream_private *p_stream,
 +                                                                    struct opj_event_mgr * p_manager )
 +{
 +        OPJ_UINT32 l_tlm_size;
 +        OPJ_OFF_T l_tlm_position, l_current_position;
-+
+ 
+-	if(!j2k) return;
+-	if(j2k->cp != NULL) {
+-		opj_cp_t *cp = j2k->cp;
 +        /* preconditions */
 +        assert(p_j2k != 00);
 +        assert(p_manager != 00);
 +        assert(p_stream != 00);
-+
+ 
+-		if(cp->comment) {
+-			opj_free(cp->comment);
+-		}
+-		if(cp->matrice) {
+-			opj_free(cp->matrice);
+-		}
+-		for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+-			opj_free(cp->tcps[tileno].tccps);
+-		}
+-		opj_free(cp->tcps);
+-		opj_free(cp);
+-	}
+-
+-	opj_free(j2k);
+-}
+-
+-void j2k_setup_encoder(opj_j2k_t *j2k, opj_cparameters_t *parameters, opj_image_t *image) {
+-	int i, j, tileno, numpocs_tile;
+-	opj_cp_t *cp = NULL;
+-
+-	if(!j2k || !parameters || ! image) {
+-		return;
+-	}
+-
+-	/* create and initialize the coding parameters structure */
+-	cp = (opj_cp_t*) opj_calloc(1, sizeof(opj_cp_t));
+-
+-	/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
+-	j2k->cp = cp;
+-
+-	/* set default values for cp */
+-	cp->tw = 1;
+-	cp->th = 1;
+-
+-	/* 
+-	copy user encoding parameters 
+-	*/
+-	cp->cinema = parameters->cp_cinema;
+-	cp->max_comp_size =	parameters->max_comp_size;
+-	cp->rsiz   = parameters->cp_rsiz;
+-	cp->disto_alloc = parameters->cp_disto_alloc;
+-	cp->fixed_alloc = parameters->cp_fixed_alloc;
+-	cp->fixed_quality = parameters->cp_fixed_quality;
+-
+-	/* mod fixed_quality */
+-	if(parameters->cp_matrice) {
+-		size_t array_size = parameters->tcp_numlayers * parameters->numresolution * 3 * sizeof(int);
+-		cp->matrice = (int *) opj_malloc(array_size);
+-		memcpy(cp->matrice, parameters->cp_matrice, array_size);
+-	}
+-
+-	/* tiles */
+-	cp->tdx = parameters->cp_tdx;
+-	cp->tdy = parameters->cp_tdy;
+-
+-	/* tile offset */
+-	cp->tx0 = parameters->cp_tx0;
+-	cp->ty0 = parameters->cp_ty0;
+-
+-	/* comment string */
+-	if(parameters->cp_comment) {
+-		cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1);
+-		if(cp->comment) {
+-			strcpy(cp->comment, parameters->cp_comment);
+-		}
+-	}
+-
+-	/*
+-	calculate other encoding parameters
+-	*/
+-
+-	if (parameters->tile_size_on) {
+-		cp->tw = int_ceildiv(image->x1 - cp->tx0, cp->tdx);
+-		cp->th = int_ceildiv(image->y1 - cp->ty0, cp->tdy);
+-	} else {
+-		cp->tdx = image->x1 - cp->tx0;
+-		cp->tdy = image->y1 - cp->ty0;
+-	}
+-
+-	if(parameters->tp_on){
+-		cp->tp_flag = parameters->tp_flag;
+-		cp->tp_on = 1;
+-	}
+-	
+-	cp->img_size = 0;
+-	for(i=0;i<image->numcomps ;i++){
+-	cp->img_size += (image->comps[i].w *image->comps[i].h * image->comps[i].prec);
+-	}
 +        l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
 +        l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
 +        l_current_position = opj_stream_tell(p_stream);
-+
+ 
 +        if (! opj_stream_seek(p_stream,l_tlm_position,p_manager)) {
 +                return OPJ_FALSE;
 +        }
  
--	return OPJ_TRUE;
+-#ifdef USE_JPWL
+-	/*
+-	calculate JPWL encoding parameters
+-	*/
+-
+-	if (parameters->jpwl_epc_on) {
+-		int i;
+-
+-		/* set JPWL on */
+-		cp->epc_on = OPJ_TRUE;
+-		cp->info_on = OPJ_FALSE; /* no informative technique */
+-
+-		/* set EPB on */
+-		if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
+-			cp->epb_on = OPJ_TRUE;
+-			
+-			cp->hprot_MH = parameters->jpwl_hprot_MH;
+-			for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
+-				cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
+-				cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
+-			}
+-			/* if tile specs are not specified, copy MH specs */
+-			if (cp->hprot_TPH[0] == -1) {
+-				cp->hprot_TPH_tileno[0] = 0;
+-				cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
+-			}
+-			for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
+-				cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
+-				cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
+-				cp->pprot[i] = parameters->jpwl_pprot[i];
+-			}
+-		}
 +        if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer,l_tlm_size,p_manager) != l_tlm_size) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-		/* set ESD writing */
+-		if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
+-			cp->esd_on = OPJ_TRUE;
 +        if (! opj_stream_seek(p_stream,l_current_position,p_manager)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-			cp->sens_size = parameters->jpwl_sens_size;
+-			cp->sens_addr = parameters->jpwl_sens_addr;
+-			cp->sens_range = parameters->jpwl_sens_range;
 +        return OPJ_TRUE;
- }
++}
  
--static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
+-			cp->sens_MH = parameters->jpwl_sens_MH;
+-			for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
+-				cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
+-				cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
+-			}
+-		}
 +OPJ_BOOL opj_j2k_end_encoding(  opj_j2k_t *p_j2k,
 +                                                        struct opj_stream_private *p_stream,
 +                                                        struct opj_event_mgr * p_manager )
@@ -17080,28 +16753,69 @@ index d34c75f..881cc72 100644
 +                p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
 +        }
  
--	if (!cstr_info)
--		return;
+-		/* always set RED writing to false: we are at the encoder */
+-		cp->red_on = OPJ_FALSE;
 +        if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
 +                opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
 +                p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
 +        }
  
--	/* expand the list? */
--	if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {
--		cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F);
--		cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum);
+-	} else {
+-		cp->epc_on = OPJ_FALSE;
 -	}
+-#endif /* USE_JPWL */
 +        p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
  
--	/* add the marker */
--	cstr_info->marker[cstr_info->marknum].type = type;
--	cstr_info->marker[cstr_info->marknum].pos = pos;
--	cstr_info->marker[cstr_info->marknum].len = len;
--	cstr_info->marknum++;
 +        return OPJ_TRUE;
 +}
  
+-	/* initialize the mutiple tiles */
+-	/* ---------------------------- */
+-	cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
+-
+-	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+-		opj_tcp_t *tcp = &cp->tcps[tileno];
+-		tcp->numlayers = parameters->tcp_numlayers;
+-		for (j = 0; j < tcp->numlayers; j++) {
+-			if(cp->cinema){
+-				if (cp->fixed_quality) {
+-					tcp->distoratio[j] = parameters->tcp_distoratio[j];
+-				}
+-				tcp->rates[j] = parameters->tcp_rates[j];
+-			}else{
+-				if (cp->fixed_quality) {	/* add fixed_quality */
+-					tcp->distoratio[j] = parameters->tcp_distoratio[j];
+-				} else {
+-					tcp->rates[j] = parameters->tcp_rates[j];
+-				}
+-			}
+-		}
+-		tcp->csty = parameters->csty;
+-		tcp->prg = parameters->prog_order;
+-		tcp->mct = parameters->tcp_mct; 
+-
+-		numpocs_tile = 0;
+-		tcp->POC = 0;
+-		if (parameters->numpocs) {
+-			/* initialisation of POC */
+-			tcp->POC = 1;
+-			for (i = 0; i < parameters->numpocs; i++) {
+-				if((tileno == parameters->POC[i].tile - 1) || (parameters->POC[i].tile == -1)) {
+-					opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
+-					tcp_poc->resno0		= parameters->POC[numpocs_tile].resno0;
+-					tcp_poc->compno0	= parameters->POC[numpocs_tile].compno0;
+-					tcp_poc->layno1		= parameters->POC[numpocs_tile].layno1;
+-					tcp_poc->resno1		= parameters->POC[numpocs_tile].resno1;
+-					tcp_poc->compno1	= parameters->POC[numpocs_tile].compno1;
+-					tcp_poc->prg1		= parameters->POC[numpocs_tile].prg1;
+-					tcp_poc->tile		= parameters->POC[numpocs_tile].tile;
+-					numpocs_tile++;
+-				}
+-			}
+-			tcp->numpocs = numpocs_tile -1 ;
+-		}else{ 
+-			tcp->numpocs = 0;
+-		}
 +/**
 + * Destroys the memory associated with the decoding of headers.
 + */
@@ -17119,76 +16833,367 @@ index d34c75f..881cc72 100644
 +                opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
 +                p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
 +        }
-+
+ 
+-		tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
+-
+-		for (i = 0; i < image->numcomps; i++) {
+-			opj_tccp_t *tccp = &tcp->tccps[i];
+-			tccp->csty = parameters->csty & 0x01;	/* 0 => one precinct || 1 => custom precinct  */
+-			tccp->numresolutions = parameters->numresolution;
+-			tccp->cblkw = int_floorlog2(parameters->cblockw_init);
+-			tccp->cblkh = int_floorlog2(parameters->cblockh_init);
+-			tccp->cblksty = parameters->mode;
+-			tccp->qmfbid = parameters->irreversible ? 0 : 1;
+-			tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
+-			tccp->numgbits = 2;
+-			if (i == parameters->roi_compno) {
+-				tccp->roishift = parameters->roi_shift;
+-			} else {
+-				tccp->roishift = 0;
+-			}
+-
+-			if(parameters->cp_cinema)
+-			{
+-				/*Precinct size for lowest frequency subband=128*/
+-				tccp->prcw[0] = 7;
+-				tccp->prch[0] = 7;
+-				/*Precinct size at all other resolutions = 256*/
+-				for (j = 1; j < tccp->numresolutions; j++) {
+-					tccp->prcw[j] = 8;
+-					tccp->prch[j] = 8;
+-				}
+-			}else{
+-				if (parameters->csty & J2K_CCP_CSTY_PRT) {
+-					int p = 0;
+-					for (j = tccp->numresolutions - 1; j >= 0; j--) {
+-						if (p < parameters->res_spec) {
+-							
+-							if (parameters->prcw_init[p] < 1) {
+-								tccp->prcw[j] = 1;
+-							} else {
+-								tccp->prcw[j] = int_floorlog2(parameters->prcw_init[p]);
+-							}
+-							
+-							if (parameters->prch_init[p] < 1) {
+-								tccp->prch[j] = 1;
+-							}else {
+-								tccp->prch[j] = int_floorlog2(parameters->prch_init[p]);
+-							}
+-
+-						} else {
+-							int res_spec = parameters->res_spec;
+-							int size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
+-							int size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
+-							
+-							if (size_prcw < 1) {
+-								tccp->prcw[j] = 1;
+-							} else {
+-								tccp->prcw[j] = int_floorlog2(size_prcw);
+-							}
+-							
+-							if (size_prch < 1) {
+-								tccp->prch[j] = 1;
+-							} else {
+-								tccp->prch[j] = int_floorlog2(size_prch);
+-							}
+-						}
+-						p++;
+-						/*printf("\nsize precinct for level %d : %d,%d\n", j,tccp->prcw[j], tccp->prch[j]); */
+-					}	/*end for*/
+-				} else {
+-					for (j = 0; j < tccp->numresolutions; j++) {
+-						tccp->prcw[j] = 15;
+-						tccp->prch[j] = 15;
+-					}
+-				}
+-			}
+-
+-			dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
+-		}
+-	}
+-}
+-
+-opj_bool j2k_encode(opj_j2k_t *j2k, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
+-	int tileno, compno;
+-	opj_cp_t *cp = NULL;
+-
+-	opj_tcd_t *tcd = NULL;	/* TCD component */
+-
+-	j2k->cio = cio;	
+-	j2k->image = image;
+-
+-	cp = j2k->cp;
+-
+-	/* INDEX >> */
+-	j2k->cstr_info = cstr_info;
+-	if (cstr_info) {
+-		int compno;
+-		cstr_info->tile = (opj_tile_info_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tile_info_t));
+-		cstr_info->image_w = image->x1 - image->x0;
+-		cstr_info->image_h = image->y1 - image->y0;
+-		cstr_info->prog = (&cp->tcps[0])->prg;
+-		cstr_info->tw = cp->tw;
+-		cstr_info->th = cp->th;
+-		cstr_info->tile_x = cp->tdx;	/* new version parser */
+-		cstr_info->tile_y = cp->tdy;	/* new version parser */
+-		cstr_info->tile_Ox = cp->tx0;	/* new version parser */
+-		cstr_info->tile_Oy = cp->ty0;	/* new version parser */
+-		cstr_info->numcomps = image->numcomps;
+-		cstr_info->numlayers = (&cp->tcps[0])->numlayers;
+-		cstr_info->numdecompos = (int*) opj_malloc(image->numcomps * sizeof(int));
+-		for (compno=0; compno < image->numcomps; compno++) {
+-			cstr_info->numdecompos[compno] = (&cp->tcps[0])->tccps->numresolutions - 1;
+-		}
+-		cstr_info->D_max = 0.0;		/* ADD Marcela */
+-		cstr_info->main_head_start = cio_tell(cio); /* position of SOC */
+-		cstr_info->maxmarknum = 100;
+-		cstr_info->marker = (opj_marker_info_t *) opj_malloc(cstr_info->maxmarknum * sizeof(opj_marker_info_t));
+-		cstr_info->marknum = 0;
+-	}
+-	/* << INDEX */
+-
+-	j2k_write_soc(j2k);
+-	j2k_write_siz(j2k);
+-	j2k_write_cod(j2k);
+-	j2k_write_qcd(j2k);
+-
+-	if(cp->cinema){
+-		for (compno = 1; compno < image->numcomps; compno++) {
+-			j2k_write_coc(j2k, compno);
+-			j2k_write_qcc(j2k, compno);
+-		}
+-	}
+-
+-	for (compno = 0; compno < image->numcomps; compno++) {
+-		opj_tcp_t *tcp = &cp->tcps[0];
+-		if (tcp->tccps[compno].roishift)
+-			j2k_write_rgn(j2k, compno, 0);
+-	}
+-	if (cp->comment != NULL) {
+-		j2k_write_com(j2k);
+-	}
+-
+-	j2k->totnum_tp = j2k_calculate_tp(cp,image->numcomps,image,j2k);
+-	/* TLM Marker*/
+-	if(cp->cinema){
+-		j2k_write_tlm(j2k);
+-		if (cp->cinema == CINEMA4K_24) {
+-			j2k_write_poc(j2k);
+-		}
+-	}
+-
+-	/* uncomment only for testing JPSEC marker writing */
+-	/* j2k_write_sec(j2k); */
+-
+-	/* INDEX >> */
+-	if(cstr_info) {
+-		cstr_info->main_head_end = cio_tell(cio) - 1;
+-	}
+-	/* << INDEX */
+-	/**** Main Header ENDS here ***/
+-
+-	/* create the tile encoder */
+-	tcd = tcd_create(j2k->cinfo);
+-
+-	/* encode each tile */
+-	for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
+-		int pino;
+-		int tilepartno=0;
+-		/* UniPG>> */
+-		int acc_pack_num = 0;
+-		/* <<UniPG */
+-
+-
+-		opj_tcp_t *tcp = &cp->tcps[tileno];
+-		opj_event_msg(j2k->cinfo, EVT_INFO, "tile number %d / %d\n", tileno + 1, cp->tw * cp->th);
+-
+-		j2k->curtileno = tileno;
+-		j2k->cur_tp_num = 0;
+-		tcd->cur_totnum_tp = j2k->cur_totnum_tp[j2k->curtileno];
+-		/* initialisation before tile encoding  */
+-		if (tileno == 0) {
+-			tcd_malloc_encode(tcd, image, cp, j2k->curtileno);
+-		} else {
+-			tcd_init_encode(tcd, image, cp, j2k->curtileno);
+-		}
 +        p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
-+
+ 
+-		/* INDEX >> */
+-		if(cstr_info) {
+-			cstr_info->tile[j2k->curtileno].start_pos = cio_tell(cio) + j2k->pos_correction;
+-			cstr_info->tile[j2k->curtileno].maxmarknum = 10;
+-			cstr_info->tile[j2k->curtileno].marker = (opj_marker_info_t *) opj_malloc(cstr_info->tile[j2k->curtileno].maxmarknum * sizeof(opj_marker_info_t));
+-			cstr_info->tile[j2k->curtileno].marknum = 0;
+-		}
+-		/* << INDEX */
+-
+-		for(pino = 0; pino <= tcp->numpocs; pino++) {
+-			int tot_num_tp;
+-			tcd->cur_pino=pino;
+-
+-			/*Get number of tile parts*/
+-			tot_num_tp = j2k_get_num_tp(cp,pino,tileno);
+-			tcd->tp_pos = cp->tp_pos;
+-
+-			for(tilepartno = 0; tilepartno < tot_num_tp ; tilepartno++){
+-				j2k->tp_num = tilepartno;
+-				/* INDEX >> */
+-				if(cstr_info)
+-					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pos =
+-					cio_tell(cio) + j2k->pos_correction;
+-				/* << INDEX */
+-				j2k_write_sot(j2k);
+-
+-				if(j2k->cur_tp_num == 0 && cp->cinema == 0){
+-					for (compno = 1; compno < image->numcomps; compno++) {
+-						j2k_write_coc(j2k, compno);
+-						j2k_write_qcc(j2k, compno);
+-					}
+-					if (cp->tcps[tileno].numpocs) {
+-						j2k_write_poc(j2k);
+-					}
+-				}
+-
+-				/* INDEX >> */
+-				if(cstr_info)
+-					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_header =
+-					cio_tell(cio) + j2k->pos_correction + 1;
+-				/* << INDEX */
+-
+-				j2k_write_sod(j2k, tcd);
+-
+-				/* INDEX >> */
+-				if(cstr_info) {
+-					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_end_pos =
+-						cio_tell(cio) + j2k->pos_correction - 1;
+-					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_start_pack =
+-						acc_pack_num;
+-					cstr_info->tile[j2k->curtileno].tp[j2k->cur_tp_num].tp_numpacks =
+-						cstr_info->packno - acc_pack_num;
+-					acc_pack_num = cstr_info->packno;
+-				}
+-				/* << INDEX */
+-
+-				j2k->cur_tp_num++;
+-			}			
+-		}
+-		if(cstr_info) {
+-			cstr_info->tile[j2k->curtileno].end_pos = cio_tell(cio) + j2k->pos_correction - 1;
+-		}
 +        return OPJ_TRUE;
- }
++}
  
--static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
 +OPJ_BOOL opj_j2k_init_info(     opj_j2k_t *p_j2k,
 +                                                struct opj_stream_private *p_stream,
 +                                                struct opj_event_mgr * p_manager )
 +{
 +        opj_codestream_info_t * l_cstr_info = 00;
-+
+ 
+-		/*
+-		if (tile->PPT) { // BAD PPT !!! 
+-		FILE *PPT_file;
+-		int i;
+-		PPT_file=fopen("PPT","rb");
+-		fprintf(stderr,"%c%c%c%c",255,97,tile->len_ppt/256,tile->len_ppt%256);
+-		for (i=0;i<tile->len_ppt;i++) {
+-		unsigned char elmt;
+-		fread(&elmt, 1, 1, PPT_file);
+-		fwrite(&elmt,1,1,f);
+-		}
+-		fclose(PPT_file);
+-		unlink("PPT");
+-		}
+-		*/
 +        /* preconditions */
 +        assert(p_j2k != 00);
 +        assert(p_manager != 00);
 +        assert(p_stream != 00);
 +  (void)l_cstr_info;
  
--  opj_marker_info_t *marker;
+-	}
 +        /* TODO mergeV2: check this part which use cstr_info */
 +        /*l_cstr_info = p_j2k->cstr_info;
  
--	if (!cstr_info)
--		return;
+-	/* destroy the tile encoder */
+-	tcd_free_encode(tcd);
+-	tcd_destroy(tcd);
 +        if (l_cstr_info)  {
 +                OPJ_UINT32 compno;
 +                l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
  
--	/* expand the list? */
--	if ((cstr_info->tile[tileno].marknum + 1) > cstr_info->tile[tileno].maxmarknum) {
--		cstr_info->tile[tileno].maxmarknum = 100 + (int) ((float) cstr_info->tile[tileno].maxmarknum * 1.0F);
--		cstr_info->tile[tileno].marker = (opj_marker_info_t*)opj_realloc(cstr_info->tile[tileno].marker, cstr_info->maxmarknum);
--	}
+-	opj_free(j2k->cur_totnum_tp);
 +                l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
 +                l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
  
--	marker = &(cstr_info->tile[tileno].marker[cstr_info->tile[tileno].marknum]);
+-	j2k_write_eoc(j2k);
 +                l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
-+
+ 
+-	if(cstr_info) {
+-		cstr_info->codestream_size = cio_tell(cio) + j2k->pos_correction;
+-		/* UniPG>> */
+-		/* The following adjustment is done to adjust the codestream size */
+-		/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
+-		/* the first bunch of bytes is not in the codestream              */
+-		cstr_info->codestream_size -= cstr_info->main_head_start;
+-		/* <<UniPG */
+-	}
 +                l_cstr_info->tw = p_j2k->m_cp.tw;
 +                l_cstr_info->th = p_j2k->m_cp.th;
-+
+ 
+-#ifdef USE_JPWL
+-	/*
+-	preparation of JPWL marker segments
+-	*/
+-	if(cp->epc_on) {
 +                l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/        /* new version parser */
 +                /*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/      /* new version parser */
 +                /*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/     /* new version parser */
 +                /*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/     /* new version parser */
-+
+ 
+-		/* encode according to JPWL */
+-		jpwl_encode(j2k, cio, image);
 +                /*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
-+
+ 
+-	}
+-#endif /* USE_JPWL */
 +                l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
-+
+ 
+-	return OPJ_TRUE;
+-}
 +                l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
-+
+ 
+-static void j2k_add_mhmarker(opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
 +                for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
 +                        l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
 +                }
-+
+ 
+-	if (!cstr_info)
+-		return;
 +                l_cstr_info->D_max = 0.0;       */      /* ADD Marcela */
-+
+ 
+-	/* expand the list? */
+-	if ((cstr_info->marknum + 1) > cstr_info->maxmarknum) {
+-		cstr_info->maxmarknum = 100 + (int) ((float) cstr_info->maxmarknum * 1.0F);
+-		cstr_info->marker = (opj_marker_info_t*)opj_realloc(cstr_info->marker, cstr_info->maxmarknum);
+-	}
 +                /*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
-+
+ 
+-	/* add the marker */
+-	cstr_info->marker[cstr_info->marknum].type = type;
+-	cstr_info->marker[cstr_info->marknum].pos = pos;
+-	cstr_info->marker[cstr_info->marknum].len = len;
+-	cstr_info->marknum++;
 +                /*l_cstr_info->maxmarknum = 100;
 +                l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
 +                l_cstr_info->marknum = 0;
 +        }*/
-+
+ 
 +        return opj_j2k_calculate_tp(p_j2k,&(p_j2k->m_cp),&p_j2k->m_specific_param.m_encoder.m_total_tile_parts,p_j2k->m_private_image,p_manager);
-+}
-+
+ }
+ 
+-static void j2k_add_tlmarker( int tileno, opj_codestream_info_t *cstr_info, unsigned short int type, int pos, int len) {
+-
+-  opj_marker_info_t *marker;
 +/**
 + * Creates a tile-coder decoder.
 + *
@@ -17212,21 +17217,24 @@ index d34c75f..881cc72 100644
 +                opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	if (!cstr_info)
+-		return;
 +        if (!opj_tcd_init(p_j2k->m_tcd,p_j2k->m_private_image,&p_j2k->m_cp)) {
 +                opj_tcd_destroy(p_j2k->m_tcd);
 +                p_j2k->m_tcd = 00;
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	/* expand the list? */
+-	if ((cstr_info->tile[tileno].marknum + 1) > cstr_info->tile[tileno].maxmarknum) {
+-		cstr_info->tile[tileno].maxmarknum = 100 + (int) ((float) cstr_info->tile[tileno].maxmarknum * 1.0F);
+-		cstr_info->tile[tileno].marker = (opj_marker_info_t*)opj_realloc(cstr_info->tile[tileno].marker, cstr_info->maxmarknum);
+-	}
 +        return OPJ_TRUE;
 +}
  
--	/* add the marker */
--	marker->type = type;
--	marker->pos = pos;
--	marker->len = len;
--	cstr_info->tile[tileno].marknum++;
+-	marker = &(cstr_info->tile[tileno].marker[cstr_info->tile[tileno].marknum]);
 +OPJ_BOOL opj_j2k_write_tile (opj_j2k_t * p_j2k,
 +                                                 OPJ_UINT32 p_tile_index,
 +                                                 OPJ_BYTE * p_data,
@@ -17244,7 +17252,12 @@ index d34c75f..881cc72 100644
 +                        return OPJ_FALSE;
 +                }
 +        }
-+
+ 
+-	/* add the marker */
+-	marker->type = type;
+-	marker->pos = pos;
+-	marker->len = len;
+-	cstr_info->tile[tileno].marknum++;
 +        return OPJ_TRUE;
  }
 diff --git a/extern/libopenjpeg/j2k.h b/extern/libopenjpeg/j2k.h
@@ -18213,133 +18226,8 @@ index 6338c29..d0f59d7 100644
 +
  
  #endif /* __J2K_H */
-diff --git a/extern/libopenjpeg/j2k_lib.c b/extern/libopenjpeg/j2k_lib.c
-deleted file mode 100644
-index a66e31e..0000000
---- a/extern/libopenjpeg/j2k_lib.c
-+++ /dev/null
-@@ -1,59 +0,0 @@
--/*
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
--
--#ifdef _WIN32
--#include <windows.h>
--#else
--#include <sys/time.h>
--#include <sys/resource.h>
--#include <sys/times.h>
--#endif /* _WIN32 */
--#include "opj_includes.h"
--
--double opj_clock(void) {
--#ifdef _WIN32
--	/* _WIN32: use QueryPerformance (very accurate) */
--    LARGE_INTEGER freq , t ;
--    /* freq is the clock speed of the CPU */
--    QueryPerformanceFrequency(&freq) ;
--	/* cout << "freq = " << ((double) freq.QuadPart) << endl; */
--    /* t is the high resolution performance counter (see MSDN) */
--    QueryPerformanceCounter ( & t ) ;
--    return ( t.QuadPart /(double) freq.QuadPart ) ;
--#else
--	/* Unix or Linux: use resource usage */
--    struct rusage t;
--    double procTime;
--    /* (1) Get the rusage data structure at this moment (man getrusage) */
--    getrusage(0,&t);
--    /* (2) What is the elapsed time ? - CPU time = User time + System time */
--	/* (2a) Get the seconds */
--    procTime = t.ru_utime.tv_sec + t.ru_stime.tv_sec;
--    /* (2b) More precisely! Get the microseconds part ! */
--    return ( procTime + (t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
--#endif
--}
--
-diff --git a/extern/libopenjpeg/j2k_lib.h b/extern/libopenjpeg/j2k_lib.h
-deleted file mode 100644
-index 5f3406e..0000000
---- a/extern/libopenjpeg/j2k_lib.h
-+++ /dev/null
-@@ -1,54 +0,0 @@
--/*
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
--#ifndef __J2K_LIB_H
--#define __J2K_LIB_H
--/**
-- at file j2k_lib.h
-- at brief Internal functions
--
--The functions in J2K_LIB.C are internal utilities mainly used for timing.
--*/
--
--/** @defgroup MISC MISC - Miscellaneous internal functions */
--/*@{*/
--
--/** @name Exported functions */
--/*@{*/
--/* ----------------------------------------------------------------------- */
--
--/**
--Difference in successive opj_clock() calls tells you the elapsed time
-- at return Returns time in seconds
--*/
--double opj_clock(void);
--
--/* ----------------------------------------------------------------------- */
--/*@}*/
--
--/*@}*/
--
--#endif /* __J2K_LIB_H */
--
 diff --git a/extern/libopenjpeg/jp2.c b/extern/libopenjpeg/jp2.c
-index 5ae114c..5c88c4d 100644
+index d332260..5c88c4d 100644
 --- a/extern/libopenjpeg/jp2.c
 +++ b/extern/libopenjpeg/jp2.c
 @@ -1,11 +1,19 @@
@@ -18365,7 +18253,12 @@ index 5ae114c..5c88c4d 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -34,152 +42,457 @@
+@@ -30,160 +38,461 @@
+  * POSSIBILITY OF SUCH DAMAGE.
+  */
+ #include "opj_includes.h"
+-#include <assert.h>
+ 
  /** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
  /*@{*/
  
@@ -18906,6 +18799,9 @@ index 5ae114c..5c88c4d 100644
 -	}
 -	else if (box->length == 0) {
 -		box->length = cio_numbytesleft(cio) + 8;
+-	} else if (box->length < 0) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
+-		return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
 +
 +        *p_number_bytes_read = 16;
 +		opj_read_bytes(l_data_header,&l_xl_part_size, 4);
@@ -18927,7 +18823,7 @@ index 5ae114c..5c88c4d 100644
  	opj_jp2_box_t box;
  
  	box.init_pos = cio_tell(cio);
-@@ -201,125 +514,242 @@ static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
+@@ -205,131 +514,242 @@ static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
  }
  #endif
  
@@ -18945,7 +18841,10 @@ index 5ae114c..5c88c4d 100644
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
  
--	jp2_read_boxhdr(cinfo, cio, &box);
+-  if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
+-    opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
+-    return OPJ_FALSE;
+-  }
 -	if (JP2_IHDR != box.type) {
 -		opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
 +	if (p_image_header_size != 14) {
@@ -19133,7 +19032,10 @@ index 5ae114c..5c88c4d 100644
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
  
--	jp2_read_boxhdr(cinfo, cio, &box);
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
+-    opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
+-    return OPJ_FALSE;
+-  }
 -	if (JP2_BPCC != box.type) {
 -		opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
 -		return OPJ_FALSE;
@@ -19249,7 +19151,7 @@ index 5ae114c..5c88c4d 100644
  {
      opj_free(color->jp2_pclr->channel_sign);
      opj_free(color->jp2_pclr->channel_size);
-@@ -330,30 +760,95 @@ static void jp2_free_pclr(opj_jp2_color_t *color)
+@@ -340,986 +760,2023 @@ static void jp2_free_pclr(opj_jp2_color_t *color)
      opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
  }
  
@@ -19266,13 +19168,33 @@ index 5ae114c..5c88c4d 100644
 -	opj_free(color->jp2_cdef);
 -   }
 -	if(color->icc_profile_buf) opj_free(color->icc_profile_buf);
+-}
+-
+-static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo)
+-{
+-	opj_image_comp_t *old_comps, *new_comps;
+-	unsigned char *channel_size, *channel_sign;
+-	unsigned int *entries;
+-	opj_jp2_cmap_comp_t *cmap;
+-	int *src, *dst;
+-	unsigned int j, max;
+-	unsigned short i, nr_channels, cmp, pcol;
+-	int k, top_k;
 +	OPJ_UINT16 i;
-+
+ 
+-	channel_size = color->jp2_pclr->channel_size;
+-	channel_sign = color->jp2_pclr->channel_sign;
+-	entries = color->jp2_pclr->entries;
+-	cmap = color->jp2_pclr->cmap;
+-	nr_channels = color->jp2_pclr->nr_channels;
 +	/* testcase 4149.pdf.SIGSEGV.cf7.3501 */
 +	if (color->jp2_cdef) {
 +		opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
 +		OPJ_UINT16 n = color->jp2_cdef->n;
-+
+ 
+-	old_comps = image->comps;
+-	new_comps = (opj_image_comp_t*)
+-	 opj_malloc(nr_channels * sizeof(opj_image_comp_t));
 +		for (i = 0; i < n; i++) {
 +			if (info[i].cn >= image->numcomps) {
 +				opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, image->numcomps);
@@ -19284,14 +19206,24 @@ index 5ae114c..5c88c4d 100644
 +			}
 +		}
 +	}
-+
+ 
+-	for(i = 0; i < nr_channels; ++i)
+-   {
+-	pcol = cmap[i].pcol; cmp = cmap[i].cmp;
 +	/* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
 +	   66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
 +	if (color->jp2_pclr && color->jp2_pclr->cmap) {
 +		OPJ_UINT16 nr_channels = color->jp2_pclr->nr_channels;
 +		opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
 +		OPJ_BOOL *pcol_usage, is_sane = OPJ_TRUE;
-+
+ 
+-  if( pcol < nr_channels )
+-    new_comps[pcol] = old_comps[cmp];
+-  else
+-    {
+-    opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels);
+-    continue;
+-    }
 +		/* verify that all original components match an existing one */
 +		for (i = 0; i < nr_channels; i++) {
 +			if (cmap[i].cmp >= image->numcomps) {
@@ -19340,45 +19272,28 @@ index 5ae114c..5c88c4d 100644
 +	}
 +
 +	return OPJ_TRUE;
- }
- 
--static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo)
++}
++
 +/* file9.jp2 */
 +void opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color)
- {
- 	opj_image_comp_t *old_comps, *new_comps;
--	unsigned char *channel_size, *channel_sign;
--	unsigned int *entries;
++{
++	opj_image_comp_t *old_comps, *new_comps;
 +	OPJ_BYTE *channel_size, *channel_sign;
 +	OPJ_UINT32 *entries;
- 	opj_jp2_cmap_comp_t *cmap;
--	int *src, *dst;
--	unsigned int j, max;
--	unsigned short i, nr_channels, cmp, pcol;
--	int k, top_k;
++	opj_jp2_cmap_comp_t *cmap;
 +	OPJ_INT32 *src, *dst;
 +	OPJ_UINT32 j, max;
 +	OPJ_UINT16 i, nr_channels, cmp, pcol;
 +	OPJ_INT32 k, top_k;
- 
- 	channel_size = color->jp2_pclr->channel_size;
- 	channel_sign = color->jp2_pclr->channel_sign;
-@@ -363,742 +858,723 @@ static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_commo
- 
- 	old_comps = image->comps;
- 	new_comps = (opj_image_comp_t*)
--	 opj_malloc(nr_channels * sizeof(opj_image_comp_t));
--
--	for(i = 0; i < nr_channels; ++i)
--   {
--	pcol = cmap[i].pcol; cmp = cmap[i].cmp;
--
--  if( pcol < nr_channels )
--    new_comps[pcol] = old_comps[cmp];
--  else
--    {
--    opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels);
--    continue;
++
++	channel_size = color->jp2_pclr->channel_size;
++	channel_sign = color->jp2_pclr->channel_sign;
++	entries = color->jp2_pclr->entries;
++	cmap = color->jp2_pclr->cmap;
++	nr_channels = color->jp2_pclr->nr_channels;
++
++	old_comps = image->comps;
++	new_comps = (opj_image_comp_t*)
 +			opj_malloc(nr_channels * sizeof(opj_image_comp_t));
 +
 +	for(i = 0; i < nr_channels; ++i) {
@@ -19391,7 +19306,14 @@ index 5ae114c..5c88c4d 100644
 +    } else {
 +      assert( i == pcol );
 +      new_comps[pcol] = old_comps[cmp];
-     }
++    }
++
++		/* Palette mapping: */
++		new_comps[i].data = (OPJ_INT32*)
++				opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(OPJ_INT32));
++		new_comps[i].prec = channel_size[i];
++		new_comps[i].sgnd = channel_sign[i];
++	}
  
 -	if(cmap[i].mtyp == 0) /* Direct use */
 -  {
@@ -19403,13 +19325,6 @@ index 5ae114c..5c88c4d 100644
 -	new_comps[pcol].prec = channel_size[i];
 -	new_comps[pcol].sgnd = channel_sign[i];
 -   }
-+		/* Palette mapping: */
-+		new_comps[i].data = (OPJ_INT32*)
-+				opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(OPJ_INT32));
-+		new_comps[i].prec = channel_size[i];
-+		new_comps[i].sgnd = channel_sign[i];
-+	}
-+
  	top_k = color->jp2_pclr->nr_entries - 1;
  
 -	for(i = 0; i < nr_channels; ++i)
@@ -19508,33 +19423,33 @@ index 5ae114c..5c88c4d 100644
 +
 +	if(jp2->color.jp2_pclr)
 +		return OPJ_FALSE;
++
++	if (p_pclr_header_size < 3)
++		return OPJ_FALSE;
  
 -	OPJ_ARG_NOT_USED(box);
 -	OPJ_ARG_NOT_USED(jp2);
-+	if (p_pclr_header_size < 3)
-+		return OPJ_FALSE;
++	opj_read_bytes(p_pclr_header_data, &l_value , 2);	/* NE */
++	p_pclr_header_data += 2;
++	nr_entries = (OPJ_UINT16) l_value;
  
 -/* Part 1, I.5.3.4: 'There shall be at most one Palette box inside
 - * a JP2 Header box' :
 -*/
 -	if(color->jp2_pclr) return OPJ_FALSE;
-+	opj_read_bytes(p_pclr_header_data, &l_value , 2);	/* NE */
-+	p_pclr_header_data += 2;
-+	nr_entries = (OPJ_UINT16) l_value;
- 
--	nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
--	nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
 +	opj_read_bytes(p_pclr_header_data, &l_value , 1);	/* NPC */
 +	++p_pclr_header_data;
 +	nr_channels = (OPJ_UINT16) l_value;
  
+-	nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
+-	nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
++	if (p_pclr_header_size < 3 + (OPJ_UINT32)nr_channels || nr_channels == 0 || nr_entries >= (OPJ_UINT32)-1 / nr_channels)
++		return OPJ_FALSE;
+ 
 -	entries = (unsigned int*)
 -	 opj_malloc(nr_channels * nr_entries * sizeof(unsigned int));
 -	channel_size = (unsigned char*)opj_malloc(nr_channels);
 -	channel_sign = (unsigned char*)opj_malloc(nr_channels);
-+	if (p_pclr_header_size < 3 + (OPJ_UINT32)nr_channels || nr_channels == 0 || nr_entries >= (OPJ_UINT32)-1 / nr_channels)
-+		return OPJ_FALSE;
-+
 +	entries = (OPJ_UINT32*) opj_malloc((size_t)nr_channels * nr_entries * sizeof(OPJ_UINT32));
 +    if (!entries)
 +        return OPJ_FALSE;
@@ -19551,8 +19466,8 @@ index 5ae114c..5c88c4d 100644
 +        opj_free(channel_size);
 +        return OPJ_FALSE;
 +	}
-+
-+	jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
+ 
+ 	jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
 +    if (!jp2_pclr)
 +    {
 +        opj_free(entries);
@@ -19560,8 +19475,7 @@ index 5ae114c..5c88c4d 100644
 +        opj_free(channel_sign);
 +        return OPJ_FALSE;
 +    }
- 
--	jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
++
  	jp2_pclr->channel_sign = channel_sign;
  	jp2_pclr->channel_size = channel_size;
  	jp2_pclr->entries = entries;
@@ -19588,7 +19502,7 @@ index 5ae114c..5c88c4d 100644
 -	for(i = 0; i < nr_channels; ++i)
 -  {
 -/* Cji */
--	*entries++ = cio_read(cio, channel_size[i]>>3);
+-	*entries++ = cio_read(cio, (channel_size[i]+7)>>3);
 -  }
 -   }
 +		channel_size[i] = (OPJ_BYTE)((l_value & 0x7f) + 1);
@@ -19639,7 +19553,9 @@ index 5ae114c..5c88c4d 100644
 +		opj_event_msg(p_manager, EVT_ERROR, "Need to read a PCLR box before the CMAP box.\n");
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-	OPJ_ARG_NOT_USED(box);
+-	OPJ_ARG_NOT_USED(jp2);
 +	/* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
 +	 * inside a JP2 Header box' :
 +	*/
@@ -19647,50 +19563,48 @@ index 5ae114c..5c88c4d 100644
 +		opj_event_msg(p_manager, EVT_ERROR, "Only one CMAP box is allowed.\n");
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-/* Need nr_channels: */
+-	if(color->jp2_pclr == NULL) return OPJ_FALSE;
 +	nr_channels = jp2->color.jp2_pclr->nr_channels;
 +	if (p_cmap_header_size < (OPJ_UINT32)nr_channels * 4) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CMAP box.\n");
 +		return OPJ_FALSE;
 +	}
  
--	OPJ_ARG_NOT_USED(box);
--	OPJ_ARG_NOT_USED(jp2);
-+	cmap = (opj_jp2_cmap_comp_t*) opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
-+    if (!cmap)
-+        return OPJ_FALSE;
- 
--/* Need nr_channels: */
--	if(color->jp2_pclr == NULL) return OPJ_FALSE;
- 
 -/* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
 - * inside a JP2 Header box' :
 -*/
 -	if(color->jp2_pclr->cmap) return OPJ_FALSE;
-+	for(i = 0; i < nr_channels; ++i) {
-+		opj_read_bytes(p_cmap_header_data, &l_value, 2);			/* CMP^i */
-+		p_cmap_header_data +=2;
-+		cmap[i].cmp = (OPJ_UINT16) l_value;
++	cmap = (opj_jp2_cmap_comp_t*) opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
++    if (!cmap)
++        return OPJ_FALSE;
  
 -	nr_channels = color->jp2_pclr->nr_channels;
 -	cmap = (opj_jp2_cmap_comp_t*)
 -	 opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
-+		opj_read_bytes(p_cmap_header_data, &l_value, 1);			/* MTYP^i */
-+		++p_cmap_header_data;
-+		cmap[i].mtyp = (OPJ_BYTE) l_value;
  
 -	for(i = 0; i < nr_channels; ++i)
 -   {
 -	cmap[i].cmp = (unsigned short)cio_read(cio, 2);
 -	cmap[i].mtyp = cio_read(cio, 1);
 -	cmap[i].pcol = cio_read(cio, 1);
++	for(i = 0; i < nr_channels; ++i) {
++		opj_read_bytes(p_cmap_header_data, &l_value, 2);			/* CMP^i */
++		p_cmap_header_data +=2;
++		cmap[i].cmp = (OPJ_UINT16) l_value;
+ 
+-   }
+-	color->jp2_pclr->cmap = cmap;
++		opj_read_bytes(p_cmap_header_data, &l_value, 1);			/* MTYP^i */
++		++p_cmap_header_data;
++		cmap[i].mtyp = (OPJ_BYTE) l_value;
++
 +		opj_read_bytes(p_cmap_header_data, &l_value, 1);			/* PCOL^i */
 +		++p_cmap_header_data;
 +		cmap[i].pcol = (OPJ_BYTE) l_value;
 +	}
- 
--   }
--	color->jp2_pclr->cmap = cmap;
++
 +	jp2->color.jp2_pclr->cmap = cmap;
  
  	return OPJ_TRUE;
@@ -19701,11 +19615,9 @@ index 5ae114c..5c88c4d 100644
 +void opj_jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
  {
  	opj_jp2_cdef_info_t *info;
--	int color_space;
 -	unsigned short i, n, cn, typ, asoc, acn;
 +	OPJ_UINT16 i, n, cn, asoc, acn;
  
--	color_space = image->color_space;
  	info = color->jp2_cdef->info;
  	n = color->jp2_cdef->n;
  
@@ -19713,12 +19625,6 @@ index 5ae114c..5c88c4d 100644
 -   {
 -/* WATCH: acn = asoc - 1 ! */
 -	if((asoc = info[i].asoc) == 0) continue;
--
--	cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
--
--	if(cn != acn)
--  {
--	opj_image_comp_t saved;
 +  for(i = 0; i < n; ++i)
 +    {
 +    /* WATCH: acn = asoc - 1 ! */
@@ -19737,22 +19643,27 @@ index 5ae114c..5c88c4d 100644
 +      fprintf(stderr, "cn=%d, acn=%d, numcomps=%d\n", cn, acn, image->numcomps);
 +      continue;
 +      }
-+
+ 
+-	cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
+-  (void)typ;
 +		if(cn != acn)
 +		{
 +			opj_image_comp_t saved;
-+
+ 
+-	if(cn != acn)
+-  {
+-	opj_image_comp_t saved;
 +			memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
 +			memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
 +			memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
-+
-+			info[i].asoc = (OPJ_UINT16)(cn + 1);
-+			info[acn].asoc = (OPJ_UINT16)(info[acn].cn + 1);
-+		}
  
 -	memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
 -	memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
 -	memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
++			info[i].asoc = (OPJ_UINT16)(cn + 1);
++			info[acn].asoc = (OPJ_UINT16)(info[acn].cn + 1);
++		}
++
 +		image->comps[cn].alpha = info[i].typ;
 +	}
  
@@ -19768,47 +19679,14 @@ index 5ae114c..5c88c4d 100644
  
 -static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio,
 -	opj_jp2_box_t *box, opj_jp2_color_t *color)
--{
--	opj_jp2_cdef_info_t *info;
--	unsigned short i, n;
--
--	OPJ_ARG_NOT_USED(box);
--	OPJ_ARG_NOT_USED(jp2);
--
--/* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
-- * inside a JP2 Header box.' 
--*/
--	if(color->jp2_cdef) return OPJ_FALSE;
--
--	if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
--
--	info = (opj_jp2_cdef_info_t*)
--	 opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
--
--	color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
--	color->jp2_cdef->info = info;
--	color->jp2_cdef->n = n;
--
--	for(i = 0; i < n; ++i)
--   {
--	info[i].cn = (unsigned short)cio_read(cio, 2);
--	info[i].typ = (unsigned short)cio_read(cio, 2);
--	info[i].asoc = (unsigned short)cio_read(cio, 2);
--
--   }
--	return OPJ_TRUE;
--}/* jp2_read_cdef() */
--
--static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
--	opj_jp2_box_t *box, opj_jp2_color_t *color) 
 +OPJ_BOOL opj_jp2_read_cdef(	opj_jp2_t * jp2,
 +                            OPJ_BYTE * p_cdef_header_data,
 +							OPJ_UINT32 p_cdef_header_size,
 +							opj_event_mgr_t * p_manager
 +                            )
  {
--	int skip_len;
--    opj_common_ptr cinfo;
+-	opj_jp2_cdef_info_t *info;
+-	unsigned short i, n;
 +	opj_jp2_cdef_info_t *cdef_info;
 +	OPJ_UINT16 i;
 +	OPJ_UINT32 l_value;
@@ -19828,51 +19706,32 @@ index 5ae114c..5c88c4d 100644
 +		return OPJ_FALSE;
 +	}
  
--/* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
-- * Specification boxes after the first.' 
--*/
--	if(color->jp2_has_colr) return OPJ_FALSE;
+-	OPJ_ARG_NOT_USED(box);
+-	OPJ_ARG_NOT_USED(jp2);
 +	opj_read_bytes(p_cdef_header_data,&l_value ,2);			/* N */
 +	p_cdef_header_data+= 2;
  
--	cinfo = jp2->cinfo;
+-/* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
+- * inside a JP2 Header box.' 
+-*/
+-	if(color->jp2_cdef) return OPJ_FALSE;
 +	if ( (OPJ_UINT16)l_value == 0){ /* szukw000: FIXME */
 +		opj_event_msg(p_manager, EVT_ERROR, "Number of channel description is equal to zero in CDEF box.\n");
 +		return OPJ_FALSE;
 +	}
- 
--	jp2->meth = cio_read(cio, 1);		/* METH */
--	jp2->precedence = cio_read(cio, 1);	/* PRECEDENCE */
--	jp2->approx = cio_read(cio, 1);		/* APPROX */
++
 +	if (p_cdef_header_size < 2 + (OPJ_UINT32)(OPJ_UINT16)l_value * 6) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CDEF box.\n");
 +		return OPJ_FALSE;
 +	}
  
--	if (jp2->meth == 1) 
--   {
--	jp2->enumcs = cio_read(cio, 4);	/* EnumCS */
--   } 
--	else
--	if (jp2->meth == 2) 
--   {
--/* skip PROFILE */
--	skip_len = box->init_pos + box->length - cio_tell(cio);
--	if (skip_len < 0) 
--  {
--	opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
--	return OPJ_FALSE;
--  }
--	if(skip_len > 0)
--  {
--	unsigned char *start;
+-	if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
 +	cdef_info = (opj_jp2_cdef_info_t*) opj_malloc(l_value * sizeof(opj_jp2_cdef_info_t));
 +    if (!cdef_info)
 +        return OPJ_FALSE;
  
--	start = cio_getbp(cio);
--	color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
--	color->icc_profile_len = skip_len;
+-	info = (opj_jp2_cdef_info_t*)
+-	 opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
 +	jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
 +    if(!jp2->color.jp2_cdef)
 +    {
@@ -19882,127 +19741,62 @@ index 5ae114c..5c88c4d 100644
 +	jp2->color.jp2_cdef->info = cdef_info;
 +	jp2->color.jp2_cdef->n = (OPJ_UINT16) l_value;
  
--	cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
+-	color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
+-	color->jp2_cdef->info = info;
+-	color->jp2_cdef->n = n;
 +	for(i = 0; i < jp2->color.jp2_cdef->n; ++i) {
 +		opj_read_bytes(p_cdef_header_data, &l_value, 2);			/* Cn^i */
 +		p_cdef_header_data +=2;
 +		cdef_info[i].cn = (OPJ_UINT16) l_value;
  
--	memcpy(color->icc_profile_buf, start, skip_len);
--  }
--   }
+-	for(i = 0; i < n; ++i)
+-   {
+-	info[i].cn = (unsigned short)cio_read(cio, 2);
+-	info[i].typ = (unsigned short)cio_read(cio, 2);
+-	info[i].asoc = (unsigned short)cio_read(cio, 2);
 +		opj_read_bytes(p_cdef_header_data, &l_value, 2);			/* Typ^i */
 +		p_cdef_header_data +=2;
 +		cdef_info[i].typ = (OPJ_UINT16) l_value;
  
--	if (cio_tell(cio) - box->init_pos != box->length) 
--   {
--	opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
--	return OPJ_FALSE;
 +		opj_read_bytes(p_cdef_header_data, &l_value, 2);			/* Asoc^i */
 +		p_cdef_header_data +=2;
 +		cdef_info[i].asoc = (OPJ_UINT16) l_value;
     }
--	color->jp2_has_colr = 1;
- 
++
  	return OPJ_TRUE;
--}/* jp2_read_colr() */
-+}
- 
--opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
-+OPJ_BOOL opj_jp2_read_colr( opj_jp2_t *jp2,
-+                            OPJ_BYTE * p_colr_header_data,
-+                            OPJ_UINT32 p_colr_header_size,
-+                            opj_event_mgr_t * p_manager
-+                            )
- {
--	opj_jp2_box_t box;
--	int jp2h_end;
--
--	opj_common_ptr cinfo = jp2->cinfo;
--
--	jp2_read_boxhdr(cinfo, cio, &box);
--	do 
--   {
--	if (JP2_JP2H != box.type) 
--  {
--	if (box.type == JP2_JP2C) 
-- {
--	opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
--	return OPJ_FALSE;
-- }
--	cio_skip(cio, box.length - 8);
-+	OPJ_UINT32 l_value;
- 
--	if(cio->bp >= cio->end) return OPJ_FALSE;
-+	/* preconditions */
-+	assert(jp2 != 00);
-+	assert(p_colr_header_data != 00);
-+	assert(p_manager != 00);
- 
--	jp2_read_boxhdr(cinfo, cio, &box);
--  }
--   } while(JP2_JP2H != box.type);
--
--	if (!jp2_read_ihdr(jp2, cio))
-+	if (p_colr_header_size < 3) {
-+		opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size)\n");
- 		return OPJ_FALSE;
--	jp2h_end = box.init_pos + box.length;
-+	}
- 
--	if (jp2->bpc == 255) 
--   {
--	if (!jp2_read_bpcc(jp2, cio))
--		return OPJ_FALSE;
--   }
--	jp2_read_boxhdr(cinfo, cio, &box);
--
--	while(cio_tell(cio) < jp2h_end)
--   {
--	if(box.type == JP2_COLR)
--  {
--	if( !jp2_read_colr(jp2, cio, &box, color))
-- {
--    cio_seek(cio, box.init_pos + 8);
--    cio_skip(cio, box.length - 8);
-- }
--    jp2_read_boxhdr(cinfo, cio, &box);
--    continue;
--  }
--    if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
--  {
--    if( !jp2_read_cdef(jp2, cio, &box, color))
-- {
--    cio_seek(cio, box.init_pos + 8);
--    cio_skip(cio, box.length - 8);
-- }
--    jp2_read_boxhdr(cinfo, cio, &box);
--    continue;
--  }
--    if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
--  {
--    if( !jp2_read_pclr(jp2, cio, &box, color))
-- {
--    cio_seek(cio, box.init_pos + 8);
--    cio_skip(cio, box.length - 8);
-- }
--    jp2_read_boxhdr(cinfo, cio, &box);
--    continue;
--  }
--    if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
--  {
--    if( !jp2_read_cmap(jp2, cio, &box, color))
-- {
--    cio_seek(cio, box.init_pos + 8);
--    cio_skip(cio, box.length - 8);
-- }
--    jp2_read_boxhdr(cinfo, cio, &box);
--    continue;
--  }
--	cio_seek(cio, box.init_pos + 8);
--	cio_skip(cio, box.length - 8);
--	jp2_read_boxhdr(cinfo, cio, &box);
+-}/* jp2_read_cdef() */
++}
+ 
+-static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
+-	opj_jp2_box_t *box, opj_jp2_color_t *color) 
++OPJ_BOOL opj_jp2_read_colr( opj_jp2_t *jp2,
++                            OPJ_BYTE * p_colr_header_data,
++                            OPJ_UINT32 p_colr_header_size,
++                            opj_event_mgr_t * p_manager
++                            )
+ {
+-	int skip_len;
+-    opj_common_ptr cinfo;
++	OPJ_UINT32 l_value;
+ 
+-/* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
+- * Specification boxes after the first.' 
+-*/
+-	if(color->jp2_has_colr) return OPJ_FALSE;
++	/* preconditions */
++	assert(jp2 != 00);
++	assert(p_colr_header_data != 00);
++	assert(p_manager != 00);
+ 
+-	cinfo = jp2->cinfo;
++	if (p_colr_header_size < 3) {
++		opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size)\n");
++		return OPJ_FALSE;
++	}
+ 
+-	jp2->meth = cio_read(cio, 1);		/* METH */
+-	jp2->precedence = cio_read(cio, 1);	/* PRECEDENCE */
+-	jp2->approx = cio_read(cio, 1);		/* APPROX */
 +	/* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
 +	 * Specification boxes after the first.'
 +	*/
@@ -20012,19 +19806,39 @@ index 5ae114c..5c88c4d 100644
 +		return OPJ_TRUE;
 +	}
  
--   }/* while(cio_tell(cio) < box_end) */
+-	if (jp2->meth == 1) 
+-   {
+-	jp2->enumcs = cio_read(cio, 4);	/* EnumCS */
+-   } 
+-	else
+-	if (jp2->meth == 2) 
+-   {
+-/* skip PROFILE */
+-	skip_len = box->init_pos + box->length - cio_tell(cio);
+-	if (skip_len < 0) 
+-  {
+-	opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
+-	return OPJ_FALSE;
+-  }
+-	if(skip_len > 0)
+-  {
+-	unsigned char *start;
 +	opj_read_bytes(p_colr_header_data,&jp2->meth ,1);			/* METH */
 +	++p_colr_header_data;
  
--	cio_seek(cio, jp2h_end);
+-	start = cio_getbp(cio);
+-	color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
+-	color->icc_profile_len = skip_len;
 +	opj_read_bytes(p_colr_header_data,&jp2->precedence ,1);		/* PRECEDENCE */
 +	++p_colr_header_data;
  
--/* Part 1, I.5.3.3 : 'must contain at least one' */
--	return (color->jp2_has_colr == 1);
+-	cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
 +	opj_read_bytes(p_colr_header_data,&jp2->approx ,1);			/* APPROX */
 +	++p_colr_header_data;
-+
+ 
+-	memcpy(color->icc_profile_buf, start, skip_len);
+-  }
+-   }
 +	if (jp2->meth == 1) {
 +		if (p_colr_header_size < 7) {
 +			opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
@@ -20035,7 +19849,12 @@ index 5ae114c..5c88c4d 100644
 +			opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
 +		}
  
--}/* jp2_read_jp2h() */
+-	if (cio_tell(cio) - box->init_pos != box->length) 
+-   {
+-	opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
+-	return OPJ_FALSE;
+-   }
+-	color->jp2_has_colr = 1;
 +		opj_read_bytes(p_colr_header_data,&jp2->enumcs ,4);			/* EnumCS */
 +        
 +        jp2->color.jp2_has_colr = 1;
@@ -20053,7 +19872,9 @@ index 5ae114c..5c88c4d 100644
 +            return OPJ_FALSE;
 +        }
 +		memset(jp2->color.icc_profile_buf, 0, (size_t)icc_len * sizeof(OPJ_BYTE));
-+
+ 
+-	return OPJ_TRUE;
+-}/* jp2_read_colr() */
 +		for (it_icc_value = 0; it_icc_value < icc_len; ++it_icc_value)
 +		{
 +			opj_read_bytes(p_colr_header_data,&l_value,1);		/* icc values */
@@ -20073,54 +19894,45 @@ index 5ae114c..5c88c4d 100644
 +    return OPJ_TRUE;
 +}
  
--opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
--	opj_codestream_info_t *cstr_info) 
+-opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
 +OPJ_BOOL opj_jp2_decode(opj_jp2_t *jp2,
 +                        opj_stream_private_t *p_stream,
 +                        opj_image_t* p_image,
 +                        opj_event_mgr_t * p_manager)
  {
--	opj_common_ptr cinfo;
--	opj_image_t *image = NULL;
--	opj_jp2_color_t color;
--
--	if(!jp2 || !cio) 
--   {
--	return NULL;
--   }
--	memset(&color, 0, sizeof(opj_jp2_color_t));
--	cinfo = jp2->cinfo;
+-	opj_jp2_box_t box;
+-	int jp2h_end;
 -
--/* JP2 decoding */
--	if(!jp2_read_struct(jp2, cio, &color)) 
--   {
--	free_color_data(&color);
--	opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
--	return NULL;
--   }
+-	opj_common_ptr cinfo = jp2->cinfo;
 +	if (!p_image)
 +		return OPJ_FALSE;
  
--/* J2K decoding */
--	image = j2k_decode(jp2->j2k, cio, cstr_info);
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-  do {
+-    if (JP2_JP2H != box.type) 
+-      {
+-      if (box.type == JP2_JP2C) 
+-        {
+-        opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
+-        return OPJ_FALSE;
+-        }
+-	  if (box.length <= 8) return OPJ_FALSE;
+-      cio_skip(cio, box.length - 8);
 +	/* J2K decoding */
 +	if( ! opj_j2k_decode(jp2->j2k, p_stream, p_image, p_manager) ) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n");
 +		return OPJ_FALSE;
 +	}
  
--	if(!image) 
--   {
--	free_color_data(&color);
--	opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
--	return NULL;
--   }
--   
-     if (!jp2->ignore_pclr_cmap_cdef){
+-      if(cio->bp >= cio->end) return OPJ_FALSE;
++    if (!jp2->ignore_pclr_cmap_cdef){
 +	    if (!opj_jp2_check_color(p_image, &(jp2->color), p_manager)) {
 +		    return OPJ_FALSE;
 +	    }
-+
+ 
+-      if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-      }
+-  } while(JP2_JP2H != box.type);
 +	    /* Set Image Color Space */
 +	    if (jp2->enumcs == 16)
 +		    p_image->color_space = OPJ_CLRSPC_SRGB;
@@ -20137,7 +19949,10 @@ index 5ae114c..5c88c4d 100644
 +	    if(jp2->color.jp2_cdef) {
 +		    opj_jp2_apply_cdef(p_image, &(jp2->color));
 +	    }
-+
+ 
+-	if (!jp2_read_ihdr(jp2, cio))
+-		return OPJ_FALSE;
+-	jp2h_end = box.init_pos + box.length;
 +	    if(jp2->color.jp2_pclr) {
 +		    /* Part 1, I.5.3.4: Either both or none : */
 +		    if( !jp2->color.jp2_pclr->cmap)
@@ -20145,50 +19960,73 @@ index 5ae114c..5c88c4d 100644
 +		    else
 +			    opj_jp2_apply_pclr(p_image, &(jp2->color));
 +	    }
-+
+ 
+-  if (jp2->bpc == 255) 
+-    {
+-    if (!jp2_read_bpcc(jp2, cio))
+-      return OPJ_FALSE;
 +	    if(jp2->color.icc_profile_buf) {
 +		    p_image->icc_profile_buf = jp2->color.icc_profile_buf;
 +		    p_image->icc_profile_len = jp2->color.icc_profile_len;
 +		    jp2->color.icc_profile_buf = NULL;
 +	    }
-+    }
+     }
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
  
--    /* Set Image Color Space */
--	if (jp2->enumcs == 16)
--		image->color_space = CLRSPC_SRGB;
--	else if (jp2->enumcs == 17)
--		image->color_space = CLRSPC_GRAY;
--	else if (jp2->enumcs == 18)
--		image->color_space = CLRSPC_SYCC;
--	else
--		image->color_space = CLRSPC_UNKNOWN;
--
--	if(color.jp2_cdef)
--   {
--	jp2_apply_cdef(image, &color);
--   }
--	if(color.jp2_pclr)
--   {
--/* Part 1, I.5.3.4: Either both or none : */
--	if( !color.jp2_pclr->cmap) 
--	 jp2_free_pclr(&color);
--	else
--	 jp2_apply_pclr(&color, image, cinfo);
--   }
--	if(color.icc_profile_buf)
--   {
--	image->icc_profile_buf = color.icc_profile_buf;
--	color.icc_profile_buf = NULL;
--	image->icc_profile_len = color.icc_profile_len;
--   }
--   }
--   
--	return image;
--
--}/* opj_jp2_decode() */
+-  while(cio_tell(cio) < jp2h_end)
+-    {
+-    if(box.type == JP2_COLR)
+-      {
+-      if( !jp2_read_colr(jp2, cio, &box, color))
+-        {
+-        if (box.length <= 8) return OPJ_FALSE;
+-        cio_seek(cio, box.init_pos + 8);
+-        cio_skip(cio, box.length - 8);
+-        }
+-      if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-      continue;
+-      }
+-    if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
+-      {
+-      if( !jp2_read_cdef(jp2, cio, &box, color))
+-        {
+-        if (box.length <= 8) return OPJ_FALSE;
+-        cio_seek(cio, box.init_pos + 8);
+-        cio_skip(cio, box.length - 8);
+-        }
+-      if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-      continue;
+-      }
+-    if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
+-      {
+-      if( !jp2_read_pclr(jp2, cio, &box, color))
+-        {
+-        if (box.length <= 8) return OPJ_FALSE;
+-        cio_seek(cio, box.init_pos + 8);
+-        cio_skip(cio, box.length - 8);
+-        }
+-      if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-      continue;
+-      }
+-    if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
+-      {
+-      if( !jp2_read_cmap(jp2, cio, &box, color))
+-        {
+-        if (box.length <= 8) return OPJ_FALSE;
+-        cio_seek(cio, box.init_pos + 8);
+-        cio_skip(cio, box.length - 8);
+-        }
+-      if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
+-      continue;
+-      }
+-    if (box.length <= 8) return OPJ_FALSE;
+-    cio_seek(cio, box.init_pos + 8);
+-    cio_skip(cio, box.length - 8);
+-    if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
 +	return OPJ_TRUE;
 +}
  
+-    }/* while(cio_tell(cio) < box_end) */
 +OPJ_BOOL opj_jp2_write_jp2h(opj_jp2_t *jp2,
 +                            opj_stream_private_t *stream,
 +                            opj_event_mgr_t * p_manager
@@ -20197,16 +20035,14 @@ index 5ae114c..5c88c4d 100644
 +	opj_jp2_img_header_writer_handler_t l_writers [3];
 +	opj_jp2_img_header_writer_handler_t * l_current_writer;
  
--void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
--	opj_jp2_box_t box;
+-  cio_seek(cio, jp2h_end);
 +	OPJ_INT32 i, l_nb_pass;
 +	/* size of data for super box*/
 +	OPJ_UINT32 l_jp2h_size = 8;
 +	OPJ_BOOL l_result = OPJ_TRUE;
  
--	box.init_pos = cio_tell(cio);
--	cio_skip(cio, 4);
--	cio_write(cio, JP2_JP2H, 4);	/* JP2H */
+-  /* Part 1, I.5.3.3 : 'must contain at least one' */
+-  return (color->jp2_has_colr == 1);
 +	/* to store the data of the super box */
 +	OPJ_BYTE l_jp2h_data [8];
 +	
@@ -20215,42 +20051,23 @@ index 5ae114c..5c88c4d 100644
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
  
--	jp2_write_ihdr(jp2, cio);
+-}/* jp2_read_jp2h() */
 +	memset(l_writers,0,sizeof(l_writers));
  
- 	if (jp2->bpc == 255) {
--		jp2_write_bpcc(jp2, cio);
+-static opj_bool opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_common_ptr cinfo)
+-{
+-	int i;
++	if (jp2->bpc == 255) {
 +		l_nb_pass = 3;
 +		l_writers[0].handler = opj_jp2_write_ihdr;
 +		l_writers[1].handler = opj_jp2_write_bpcc;
 +		l_writers[2].handler = opj_jp2_write_colr;
- 	}
--	jp2_write_colr(jp2, cio);
--
--	box.length = cio_tell(cio) - box.init_pos;
--	cio_seek(cio, box.init_pos);
--	cio_write(cio, box.length, 4);	/* L */
--	cio_seek(cio, box.init_pos + box.length);
--}
--
--static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
--	unsigned int i;
--	opj_jp2_box_t box;
--
--	box.init_pos = cio_tell(cio);
--	cio_skip(cio, 4);
--	cio_write(cio, JP2_FTYP, 4);		/* FTYP */
--
--	cio_write(cio, jp2->brand, 4);		/* BR */
--	cio_write(cio, jp2->minversion, 4);	/* MinV */
--
--	for (i = 0; i < jp2->numcl; i++) {
--		cio_write(cio, jp2->cl[i], 4);	/* CL */
++	}
 +	else {
 +		l_nb_pass = 2;
 +		l_writers[0].handler = opj_jp2_write_ihdr;
 +		l_writers[1].handler = opj_jp2_write_colr;
- 	}
++	}
 +	
 +	/* write box header */
 +	/* write JP2H type */
@@ -20265,43 +20082,46 @@ index 5ae114c..5c88c4d 100644
 +			break;
 +		}
  
--	box.length = cio_tell(cio) - box.init_pos;
--	cio_seek(cio, box.init_pos);
--	cio_write(cio, box.length, 4);	/* L */
--	cio_seek(cio, box.init_pos + box.length);
--}
--
--static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
--	int i;
--	opj_jp2_box_t box;
--
--	opj_common_ptr cinfo = jp2->cinfo;
+-	/* testcase 4149.pdf.SIGSEGV.cf7.3501 */
+-	if (color->jp2_cdef) {
+-		opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
+-		int n = color->jp2_cdef->n;
 +		l_jp2h_size += l_current_writer->m_size;
 +		++l_current_writer;
 +	}
  
--	jp2_read_boxhdr(cinfo, cio, &box);
+-		for (i = 0; i < n; i++) {
+-			if (info[i].cn >= image->numcomps) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, image->numcomps);
+-				return OPJ_FALSE;
+-			}
+-			if (info[i].asoc > 0 && (info[i].asoc - 1) >= image->numcomps) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, image->numcomps);
+-				return OPJ_FALSE;
 +	if (! l_result) {
 +		l_current_writer = l_writers;
 +		for (i=0;i<l_nb_pass;++i) {
 +			if (l_current_writer->m_data != 00) {
 +				opj_free(l_current_writer->m_data );
-+			}
+ 			}
 +			++l_current_writer;
-+		}
+ 		}
+-	}
  
--	if (JP2_FTYP != box.type) {
--		opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
- 		return OPJ_FALSE;
- 	}
+-	/* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
+-	   66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
+-	if (color->jp2_pclr && color->jp2_pclr->cmap) {
+-		int nr_channels = color->jp2_pclr->nr_channels;
+-		opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
+-		opj_bool *pcol_usage, is_sane = OPJ_TRUE;
++		return OPJ_FALSE;
++	}
  
--	jp2->brand = cio_read(cio, 4);		/* BR */
--	jp2->minversion = cio_read(cio, 4);	/* MinV */
--	jp2->numcl = (box.length - 16) / 4;
--	jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
--
--	for (i = 0; i < (int)jp2->numcl; i++) {
--		jp2->cl[i] = cio_read(cio, 4);	/* CLi */
+-		/* verify that all original components match an existing one */
+-		for (i = 0; i < nr_channels; i++) {
+-			if (cmap[i].cmp >= image->numcomps) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps);
+-				is_sane = OPJ_FALSE;
 +	/* write super box size */
 +	opj_write_bytes(l_jp2h_data,l_jp2h_size,4);
 +	
@@ -20318,33 +20138,55 @@ index 5ae114c..5c88c4d 100644
 +				opj_event_msg(p_manager, EVT_ERROR, "Stream error while writing JP2 Header box\n");
 +				l_result = OPJ_FALSE;
 +				break;
-+			}
+ 			}
 +			++l_current_writer;
-+		}
- 	}
+ 		}
++	}
  
--	if (cio_tell(cio) - box.init_pos != box.length) {
--		opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
--		return OPJ_FALSE;
+-		pcol_usage = opj_calloc(nr_channels, sizeof(opj_bool));
+-		if (!pcol_usage) {
+-			opj_event_msg(cinfo, EVT_ERROR, "Unexpected OOM.\n");
+-			return OPJ_FALSE;
+-		}
+-		/* verify that no component is targeted more than once */
+-		for (i = 0; i < nr_channels; i++) {
+-      int pcol = cmap[i].pcol;
+-      assert(cmap[i].mtyp == 0 || cmap[i].mtyp == 1);
+-			if (pcol >= nr_channels) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol);
+-				is_sane = OPJ_FALSE;
+-			}
+-			else if (pcol_usage[pcol] && cmap[i].mtyp == 1) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Component %d is mapped twice.\n", pcol);
+-				is_sane = OPJ_FALSE;
+-			}
+-      else if (cmap[i].mtyp == 0 && cmap[i].pcol != 0) {
+-        /* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then
+-         * the value of this field shall be 0. */
+-				opj_event_msg(cinfo, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol);
+-				is_sane = OPJ_FALSE;
+-      }
+-			else
+-				pcol_usage[pcol] = OPJ_TRUE;
 +	l_current_writer = l_writers;
 +	
 +	/* cleanup */
 +	for (i=0;i<l_nb_pass;++i) {
 +		if (l_current_writer->m_data != 00) {
 +			opj_free(l_current_writer->m_data );
-+		}
+ 		}
+-		/* verify that all components are targeted at least once */
+-		for (i = 0; i < nr_channels; i++) {
+-			if (!pcol_usage[i] && cmap[i].mtyp != 0) {
+-				opj_event_msg(cinfo, EVT_ERROR, "Component %d doesn't have a mapping.\n", i);
+-				is_sane = OPJ_FALSE;
+-			}
 +		++l_current_writer;
- 	}
- 
--	return OPJ_TRUE;
++	}
++
 +	return l_result;
- }
- 
--static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
--	unsigned int j2k_codestream_offset, j2k_codestream_length;
--	opj_jp2_box_t box;
--
--	opj_j2k_t *j2k = jp2->j2k;
++}
++
 +OPJ_BOOL opj_jp2_write_ftyp(opj_jp2_t *jp2,
 +							opj_stream_private_t *cio,
 +							opj_event_mgr_t * p_manager )
@@ -20353,75 +20195,35 @@ index 5ae114c..5c88c4d 100644
 +	OPJ_UINT32 l_ftyp_size = 16 + 4 * jp2->numcl;
 +	OPJ_BYTE * l_ftyp_data, * l_current_data_ptr;
 +	OPJ_BOOL l_result;
- 
--	box.init_pos = cio_tell(cio);
--	cio_skip(cio, 4);
--	cio_write(cio, JP2_JP2C, 4);	/* JP2C */
++
 +	/* preconditions */
 +	assert(cio != 00);
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
- 
--	/* J2K encoding */
--	j2k_codestream_offset = cio_tell(cio);
--	if(!j2k_encode(j2k, cio, image, cstr_info)) {
--		opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
--		return 0;
++
 +	l_ftyp_data = (OPJ_BYTE *) opj_malloc(l_ftyp_size);
 +	
 +	if (l_ftyp_data == 00) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle ftyp data\n");
 +		return OPJ_FALSE;
- 	}
--	j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
--
--	jp2->j2k_codestream_offset = j2k_codestream_offset;
--	jp2->j2k_codestream_length = j2k_codestream_length;
--
--	box.length = 8 + jp2->j2k_codestream_length;
--	cio_seek(cio, box.init_pos);
--	cio_write(cio, box.length, 4);	/* L */
--	cio_seek(cio, box.init_pos + box.length);
- 
--	return box.length;
--}
--
--static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
--	opj_jp2_box_t box;
++	}
++
 +	memset(l_ftyp_data,0,l_ftyp_size);
- 
--	opj_common_ptr cinfo = jp2->cinfo;
++
 +	l_current_data_ptr = l_ftyp_data;
- 
--	jp2_read_boxhdr(cinfo, cio, &box);
--	do {
--		if(JP2_JP2C != box.type) {
--			cio_skip(cio, box.length - 8);
--			jp2_read_boxhdr(cinfo, cio, &box);
--		}
--	} while(JP2_JP2C != box.type);
++
 +	opj_write_bytes(l_current_data_ptr, l_ftyp_size,4); /* box size */
 +	l_current_data_ptr += 4;
- 
--	*j2k_codestream_offset = cio_tell(cio);
--	*j2k_codestream_length = box.length - 8;
++
 +	opj_write_bytes(l_current_data_ptr, JP2_FTYP,4); /* FTYP */
 +	l_current_data_ptr += 4;
- 
--	return OPJ_TRUE;
--}
++
 +	opj_write_bytes(l_current_data_ptr, jp2->brand,4); /* BR */
 +	l_current_data_ptr += 4;
- 
--static void jp2_write_jp(opj_cio_t *cio) {
--	opj_jp2_box_t box;
++
 +	opj_write_bytes(l_current_data_ptr, jp2->minversion,4); /* MinV */
 +	l_current_data_ptr += 4;
- 
--	box.init_pos = cio_tell(cio);
--	cio_skip(cio, 4);
--	cio_write(cio, JP2_JP, 4);		/* JP2 signature */
--	cio_write(cio, 0x0d0a870a, 4);
++
 +	for (i = 0; i < jp2->numcl; i++)  {
 +		opj_write_bytes(l_current_data_ptr, jp2->cl[i],4);	/* CL */
 +	}
@@ -20431,24 +20233,12 @@ index 5ae114c..5c88c4d 100644
 +	{
 +		opj_event_msg(p_manager, EVT_ERROR, "Error while writing ftyp data to stream\n");
 +	}
- 
--	box.length = cio_tell(cio) - box.init_pos;
--	cio_seek(cio, box.init_pos);
--	cio_write(cio, box.length, 4);	/* L */
--	cio_seek(cio, box.init_pos + box.length);
++
 +	opj_free(l_ftyp_data);
 +	
 +	return l_result;
- }
- 
--static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
--	opj_jp2_box_t box;
--
--	opj_common_ptr cinfo = jp2->cinfo;
--
--	jp2_read_boxhdr(cinfo, cio, &box);
--	if (JP2_JP != box.type) {
--		opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
++}
++
 +OPJ_BOOL opj_jp2_write_jp2c(opj_jp2_t *jp2,
 +							opj_stream_private_t *cio,
 +							opj_event_mgr_t * p_manager )
@@ -20470,86 +20260,26 @@ index 5ae114c..5c88c4d 100644
 +
 +	if (! opj_stream_seek(cio,jp2->j2k_codestream_offset,p_manager)) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
- 		return OPJ_FALSE;
- 	}
--	if (0x0d0a870a != cio_read(cio, 4)) {
--		opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
++		return OPJ_FALSE;
++	}
 +	
 +	if (opj_stream_write_data(cio,l_data_header,8,p_manager) != 8) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
- 		return OPJ_FALSE;
- 	}
--	if (cio_tell(cio) - box.init_pos != box.length) {
--		opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
++		return OPJ_FALSE;
++	}
 +
 +	if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
- 		return OPJ_FALSE;
- 	}
- 
- 	return OPJ_TRUE;
- }
- 
--
--static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
--	opj_jp2_color_t *color) {
--	if (!jp2_read_jp(jp2, cio))
--		return OPJ_FALSE;
--	if (!jp2_read_ftyp(jp2, cio))
--		return OPJ_FALSE;
--	if (!jp2_read_jp2h(jp2, cio, color))
--		return OPJ_FALSE;
--	if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
--		return OPJ_FALSE;
--	
--	return OPJ_TRUE;
--}
--
--
--static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
--{  
--  int len, lenp;
--  
--  lenp = cio_tell( cio);
--  cio_skip( cio, 4);              /* L [at the end] */
--  cio_write( cio, JPIP_FIDX, 4);  /* IPTR           */
--  
--  write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio);
--
--  len = cio_tell( cio)-lenp;
--  cio_seek( cio, lenp);
--  cio_write( cio, len, 4);        /* L              */
--  cio_seek( cio, lenp+len);  
--
--  return len;
--}
--
--static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
++		return OPJ_FALSE;
++	}
++
++	return OPJ_TRUE;
++}
++
 +OPJ_BOOL opj_jp2_write_jp(	opj_jp2_t *jp2,
 +			    		    opj_stream_private_t *cio,
 +				    		opj_event_mgr_t * p_manager )
- {
--  int len, lenp;
--
--  lenp = cio_tell( cio);
--  cio_skip( cio, 4);              /* L [at the end] */
--  cio_write( cio, JPIP_PRXY, 4);  /* IPTR           */
--  
--  cio_write( cio, offset_jp2c, 8); /* OOFF           */
--  cio_write( cio, length_jp2c, 4); /* OBH part 1     */
--  cio_write( cio, JP2_JP2C, 4);        /* OBH part 2     */
--  
--  cio_write( cio, 1,1);           /* NI             */
--
--  cio_write( cio, offset_idx, 8);  /* IOFF           */
--  cio_write( cio, length_idx, 4);  /* IBH part 1     */
--  cio_write( cio, JPIP_CIDX, 4);   /* IBH part 2     */
--
--  len = cio_tell( cio)-lenp;
--  cio_seek( cio, lenp);
--  cio_write( cio, len, 4);        /* L              */
--  cio_seek( cio, lenp+len);
--}
++{
 +	/* 12 bytes will be read */
 +	OPJ_BYTE l_signature_data [12];
 +
@@ -20568,108 +20298,28 @@ index 5ae114c..5c88c4d 100644
 +	if (opj_stream_write_data(cio,l_signature_data,12,p_manager) != 12) {
 +		return OPJ_FALSE;
 +	}
- 
--static void write_iptr( int offset, int length, opj_cio_t *cio)
--{
--  int len, lenp;
--  
--  lenp = cio_tell( cio);
--  cio_skip( cio, 4);              /* L [at the end] */
--  cio_write( cio, JPIP_IPTR, 4);  /* IPTR           */
--  
--  cio_write( cio, offset, 8);
--  cio_write( cio, length, 8);
--
--  len = cio_tell( cio)-lenp;
--  cio_seek( cio, lenp);
--  cio_write( cio, len, 4);        /* L             */
--  cio_seek( cio, lenp+len);
-+	return OPJ_TRUE;
- }
- 
--
- /* ----------------------------------------------------------------------- */
- /* JP2 decoder interface                                             */
- /* ----------------------------------------------------------------------- */
- 
--opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
--	opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
--	if(jp2) {
--		jp2->cinfo = cinfo;
--		/* create the J2K codec */
--		jp2->j2k = j2k_create_decompress(cinfo);
--		if(jp2->j2k == NULL) {
--			jp2_destroy_decompress(jp2);
--			return NULL;
--		}
--	}
--	return jp2;
--}
--
--void jp2_destroy_decompress(opj_jp2_t *jp2) {
--	if(jp2) {
--		/* destroy the J2K codec */
--		j2k_destroy_decompress(jp2->j2k);
--
--		if(jp2->comps) {
--			opj_free(jp2->comps);
--		}
--		if(jp2->cl) {
--			opj_free(jp2->cl);
--		}
--		opj_free(jp2);
--	}
--}
--
--void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
-+void opj_jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters)
-+{
- 	/* setup the J2K codec */
--	j2k_setup_decoder(jp2->j2k, parameters);
-+	opj_j2k_setup_decoder(jp2->j2k, parameters);
 +
- 	/* further JP2 initializations go here */
--	jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
-+	jp2->color.jp2_has_colr = 0;
-+    jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
- }
- 
- /* ----------------------------------------------------------------------- */
- /* JP2 encoder interface                                             */
- /* ----------------------------------------------------------------------- */
- 
--opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
--	opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
--	if(jp2) {
--		jp2->cinfo = cinfo;
--		/* create the J2K codec */
--		jp2->j2k = j2k_create_compress(cinfo);
--		if(jp2->j2k == NULL) {
--			jp2_destroy_compress(jp2);
--			return NULL;
--		}
--	}
--	return jp2;
--}
--
--void jp2_destroy_compress(opj_jp2_t *jp2) {
--	if(jp2) {
--		/* destroy the J2K codec */
--		j2k_destroy_compress(jp2->j2k);
--
--		if(jp2->comps) {
--			opj_free(jp2->comps);
--		}
--		if(jp2->cl) {
--			opj_free(jp2->cl);
--		}
--		opj_free(jp2);
--	}
--}
--
--void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
--	int i;
--	int depth_0, sign;
++	return OPJ_TRUE;
++}
++
++/* ----------------------------------------------------------------------- */
++/* JP2 decoder interface                                             */
++/* ----------------------------------------------------------------------- */
++
++void opj_jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters)
++{
++	/* setup the J2K codec */
++	opj_j2k_setup_decoder(jp2->j2k, parameters);
++
++	/* further JP2 initializations go here */
++	jp2->color.jp2_has_colr = 0;
++    jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
++}
++
++/* ----------------------------------------------------------------------- */
++/* JP2 encoder interface                                             */
++/* ----------------------------------------------------------------------- */
++
 +void opj_jp2_setup_encoder(	opj_jp2_t *jp2,
 +                            opj_cparameters_t *parameters,
 +                            opj_image_t *image,
@@ -20678,73 +20328,67 @@ index 5ae114c..5c88c4d 100644
 +    OPJ_UINT32 i;
 +	OPJ_UINT32 depth_0;
 +  OPJ_UINT32 sign;
- 
- 	if(!jp2 || !parameters || !image)
- 		return;
-@@ -1108,11 +1584,11 @@ void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_
- 
- 	/* Check if number of components respects standard */
- 	if (image->numcomps < 1 || image->numcomps > 16384) {
--		opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
++
++	if(!jp2 || !parameters || !image)
++		return;
++
++	/* setup the J2K codec */
++	/* ------------------- */
++
++	/* Check if number of components respects standard */
++	if (image->numcomps < 1 || image->numcomps > 16384) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
- 		return;
- 	}
- 
--	j2k_setup_encoder(jp2->j2k, parameters, image);
++		return;
++	}
++
 +	opj_j2k_setup_encoder(jp2->j2k, parameters, image, p_manager );
- 
- 	/* setup the JP2 codec */
- 	/* ------------------- */
-@@ -1122,13 +1598,24 @@ void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_
- 	jp2->brand = JP2_JP2;	/* BR */
- 	jp2->minversion = 0;	/* MinV */
- 	jp2->numcl = 1;
--	jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
++
++	/* setup the JP2 codec */
++	/* ------------------- */
++	
++	/* Profile box */
++
++	jp2->brand = JP2_JP2;	/* BR */
++	jp2->minversion = 0;	/* MinV */
++	jp2->numcl = 1;
 +	jp2->cl = (OPJ_UINT32*) opj_malloc(jp2->numcl * sizeof(OPJ_UINT32));
 +    if (!jp2->cl){
 +        jp2->cl = NULL;
 +        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
 +        return;
 +    }
- 	jp2->cl[0] = JP2_JP2;	/* CL0 : JP2 */
- 
- 	/* Image Header box */
- 
- 	jp2->numcomps = image->numcomps;	/* NC */
- 	jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
++	jp2->cl[0] = JP2_JP2;	/* CL0 : JP2 */
++
++	/* Image Header box */
++
++	jp2->numcomps = image->numcomps;	/* NC */
++	jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
 +    if (!jp2->comps) {
 +        jp2->comps = NULL;
 +        opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
 +        return;
 +    }
 +
- 	jp2->h = image->y1 - image->y0;		/* HEIGHT */
- 	jp2->w = image->x1 - image->x0;		/* WIDTH */
- 	/* BPC */
-@@ -1136,7 +1623,7 @@ void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_
- 	sign = image->comps[0].sgnd;
- 	jp2->bpc = depth_0 + (sign << 7);
- 	for (i = 1; i < image->numcomps; i++) {
--		int depth = image->comps[i].prec - 1;
++	jp2->h = image->y1 - image->y0;		/* HEIGHT */
++	jp2->w = image->x1 - image->x0;		/* WIDTH */
++	/* BPC */
++	depth_0 = image->comps[0].prec - 1;
++	sign = image->comps[0].sgnd;
++	jp2->bpc = depth_0 + (sign << 7);
++	for (i = 1; i < image->numcomps; i++) {
 +		OPJ_UINT32 depth = image->comps[i].prec - 1;
- 		sign = image->comps[i].sgnd;
- 		if (depth_0 != depth)
- 			jp2->bpc = 255;
-@@ -1146,65 +1633,1150 @@ void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_
- 	jp2->IPR = 0;		/* IPR, no intellectual property */
- 	
- 	/* BitsPerComponent box */
--
- 	for (i = 0; i < image->numcomps; i++) {
- 		jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
- 	}
--	jp2->meth = 1;
--	if (image->color_space == 1)
--		jp2->enumcs = 16;	/* sRGB as defined by IEC 61966-2.1 */
--	else if (image->color_space == 2)
--		jp2->enumcs = 17;	/* greyscale */
--	else if (image->color_space == 3)
--		jp2->enumcs = 18;	/* YUV */
++		sign = image->comps[i].sgnd;
++		if (depth_0 != depth)
++			jp2->bpc = 255;
++	}
++	jp2->C = 7;			/* C : Always 7 */
++	jp2->UnkC = 0;		/* UnkC, colorspace specified in colr box */
++	jp2->IPR = 0;		/* IPR, no intellectual property */
++	
++	/* BitsPerComponent box */
++	for (i = 0; i < image->numcomps; i++) {
++		jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
++	}
 +
 +	/* Colour Specification box */
 +    if(image->icc_profile_len) {
@@ -20762,23 +20406,19 @@ index 5ae114c..5c88c4d 100644
 +    }
 +
 +
- 	jp2->precedence = 0;	/* PRECEDENCE */
- 	jp2->approx = 0;		/* APPROX */
--	
++	jp2->precedence = 0;	/* PRECEDENCE */
++	jp2->approx = 0;		/* APPROX */
++
++	jp2->jpip_on = parameters->jpip_on;
++}
 +
- 	jp2->jpip_on = parameters->jpip_on;
- }
- 
--opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
 +OPJ_BOOL opj_jp2_encode(opj_jp2_t *jp2,
 +						opj_stream_private_t *stream,
 +						opj_event_mgr_t * p_manager)
 +{
 +	return opj_j2k_encode(jp2->j2k, stream, p_manager);
 +}
- 
--	int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
--	pos_jp2c = pos_iptr = -1; /* remove a warning */
++
 +OPJ_BOOL opj_jp2_end_decompress(opj_jp2_t *jp2,
 +                                opj_stream_private_t *cio,
 +                                opj_event_mgr_t * p_manager
@@ -20788,17 +20428,10 @@ index 5ae114c..5c88c4d 100644
 +	assert(jp2 != 00);
 +	assert(cio != 00);
 +	assert(p_manager != 00);
- 
--	/* JP2 encoding */
++
 +	/* customization of the end encoding */
 +	opj_jp2_setup_end_header_reading(jp2);
- 
--	/* JPEG 2000 Signature box */
--	jp2_write_jp(cio);
--	/* File Type box */
--	jp2_write_ftyp(jp2, cio);
--	/* JP2 Header box */
--	jp2_write_jp2h(jp2, cio);
++
 +	/* write header */
 +	if (! opj_jp2_exec (jp2,jp2->m_procedure_list,cio,p_manager)) {
 +		return OPJ_FALSE;
@@ -20948,7 +20581,9 @@ index 5ae114c..5c88c4d 100644
 +				opj_free(l_current_data);
 +				return OPJ_FALSE;
 +			}
-+		}
+ 		}
+-		opj_free(pcol_usage);
+-		if (!is_sane) {
 +		else if	(box.length == 0) {
 +			opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
 +			opj_free(l_current_data);
@@ -20958,8 +20593,8 @@ index 5ae114c..5c88c4d 100644
 +		else if	(box.length < l_nb_bytes_read) {
 +			opj_event_msg(p_manager, EVT_ERROR, "invalid box size %d (%x)\n", box.length, box.type);
 +			opj_free(l_current_data);
-+			return OPJ_FALSE;
-+		}
+ 			return OPJ_FALSE;
+ 		}
 +
 +		l_current_handler = opj_jp2_find_handler(box.type);
 +		l_current_data_size = box.length - l_nb_bytes_read;
@@ -20996,13 +20631,15 @@ index 5ae114c..5c88c4d 100644
 +				return OPJ_FALSE;
 +			}
 +		}
-+	}
-+
+ 	}
+ 
 +	opj_free(l_current_data);
 +
-+	return OPJ_TRUE;
-+}
-+
+ 	return OPJ_TRUE;
+ }
+ 
+-opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
+-	opj_codestream_info_t *cstr_info) 
 +/**
 + * Excutes the given procedures on the given codec.
 + *
@@ -21019,7 +20656,10 @@ index 5ae114c..5c88c4d 100644
 +                                opj_event_mgr_t * p_manager
 +                                )
 +
-+{
+ {
+-	opj_common_ptr cinfo;
+-	opj_image_t *image = NULL;
+-	opj_jp2_color_t color;
 +	OPJ_BOOL (** l_procedure) (opj_jp2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *) = 00;
 +	OPJ_BOOL l_result = OPJ_TRUE;
 +	OPJ_UINT32 l_nb_proc, i;
@@ -21037,7 +20677,21 @@ index 5ae114c..5c88c4d 100644
 +		l_result = l_result && (*l_procedure) (jp2,stream,p_manager);
 +		++l_procedure;
 +	}
-+
+ 
+-	if(!jp2 || !cio) 
+-   {
+-	return NULL;
+-   }
+-	memset(&color, 0, sizeof(opj_jp2_color_t));
+-	cinfo = jp2->cinfo;
+-
+-/* JP2 decoding */
+-	if(!jp2_read_struct(jp2, cio, &color)) 
+-   {
+-	free_color_data(&color);
+-	opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
+-	return NULL;
+-   }
 +	/* and clear the procedure list at the end. */
 +	opj_procedure_list_clear(p_procedure_list);
 +	return l_result;
@@ -21061,10 +20715,16 @@ index 5ae114c..5c88c4d 100644
 +	if (! opj_jp2_exec(jp2,jp2->m_validation_list,stream,p_manager)) {
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-/* J2K decoding */
+-	image = j2k_decode(jp2->j2k, cio, cstr_info);
 +	/* customization of the encoding */
 +	opj_jp2_setup_header_writing(jp2);
-+
+ 
+-	if(!image) 
+-   {
+-	free_color_data(&color);
+-	opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
 +	/* write header */
 +	if (! opj_jp2_exec (jp2,jp2->m_procedure_list,stream,p_manager)) {
 +		return OPJ_FALSE;
@@ -21082,9 +20742,25 @@ index 5ae114c..5c88c4d 100644
 +			return &jp2_header[i];
 +		}
 +	}
-+	return NULL;
+ 	return NULL;
+-   }
+-   
+-    if (!jp2->ignore_pclr_cmap_cdef){
+-	    if (!opj_jp2_check_color(image, &color, cinfo)) {
+-        opj_event_msg(cinfo, EVT_ERROR, "Failed to decode PCRL box\n");
+-		    return NULL;
+-	    }
 +}
-+
+ 
+-    /* Set Image Color Space */
+-	if (jp2->enumcs == 16)
+-		image->color_space = CLRSPC_SRGB;
+-	else if (jp2->enumcs == 17)
+-		image->color_space = CLRSPC_GRAY;
+-	else if (jp2->enumcs == 18)
+-		image->color_space = CLRSPC_SYCC;
+-	else
+-		image->color_space = CLRSPC_UNKNOWN;
 +/**
 + * Finds the image execution function related to the given box id.
 + *
@@ -21101,10 +20777,32 @@ index 5ae114c..5c88c4d 100644
 +			return &jp2_img_header[i];
 +		}
 +	}
-+
+ 
+-	if(color.jp2_cdef)
+-   {
+-	jp2_apply_cdef(image, &color);
+-   }
+-	if(color.jp2_pclr)
+-   {
+-/* Part 1, I.5.3.4: Either both or none : */
+-	if( !color.jp2_pclr->cmap) 
+-	 jp2_free_pclr(&color);
+-	else
+-	 jp2_apply_pclr(&color, image, cinfo);
+-   }
+-	if(color.icc_profile_buf)
+-   {
+-	image->icc_profile_buf = color.icc_profile_buf;
+-	color.icc_profile_buf = NULL;
+-	image->icc_profile_len = color.icc_profile_len;
+-   }
+-   }
+-   
+-	return image;
 +	return NULL;
 +}
-+
+ 
+-}/* opj_jp2_decode() */
 +/**
 + * Reads a jpeg2000 file signature box.
 + *
@@ -21120,38 +20818,54 @@ index 5ae114c..5c88c4d 100644
 +                                OPJ_UINT32 p_header_size,
 +                                opj_event_mgr_t * p_manager
 +                                )
-+
+ 
 +{
 +	OPJ_UINT32 l_magic_number;
-+
+ 
+-void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
+-	opj_jp2_box_t box;
 +	/* preconditions */
 +	assert(p_header_data != 00);
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
-+
+ 
+-	box.init_pos = cio_tell(cio);
+-	cio_skip(cio, 4);
+-	cio_write(cio, JP2_JP2H, 4);	/* JP2H */
 +	if (jp2->jp2_state != JP2_STATE_NONE) {
 +		opj_event_msg(p_manager, EVT_ERROR, "The signature box must be the first box in the file.\n");
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-	jp2_write_ihdr(jp2, cio);
 +	/* assure length of data is correct (4 -> magic number) */
 +	if (p_header_size != 4) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Error with JP signature Box size\n");
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-	if (jp2->bpc == 255) {
+-		jp2_write_bpcc(jp2, cio);
 +	/* rearrange data */
 +	opj_read_bytes(p_header_data,&l_magic_number,4);
 +	if (l_magic_number != 0x0d0a870a ) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Error with JP Signature : bad magic number\n");
 +		return OPJ_FALSE;
-+	}
-+
+ 	}
+-	jp2_write_colr(jp2, cio);
+ 
+-	box.length = cio_tell(cio) - box.init_pos;
+-	cio_seek(cio, box.init_pos);
+-	cio_write(cio, box.length, 4);	/* L */
+-	cio_seek(cio, box.init_pos + box.length);
 +	jp2->jp2_state |= JP2_STATE_SIGNATURE;
 +
 +	return OPJ_TRUE;
-+}
-+
+ }
+ 
+-static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
+-	unsigned int i;
+-	opj_jp2_box_t box;
 +/**
 + * Reads a a FTYP box - File type box
 + *
@@ -21169,7 +20883,10 @@ index 5ae114c..5c88c4d 100644
 +                                    )
 +{
 +	OPJ_UINT32 i, l_remaining_bytes;
-+
+ 
+-	box.init_pos = cio_tell(cio);
+-	cio_skip(cio, 4);
+-	cio_write(cio, JP2_FTYP, 4);		/* FTYP */
 +	/* preconditions */
 +	assert(p_header_data != 00);
 +	assert(jp2 != 00);
@@ -21222,11 +20939,8 @@ index 5ae114c..5c88c4d 100644
 +	return OPJ_TRUE;
 +}
  
--	if( jp2->jpip_on){
--	  pos_iptr = cio_tell( cio);
--	  cio_skip( cio, 24); /* IPTR further ! */
--	  
--	  pos_jp2c = cio_tell( cio);
+-	cio_write(cio, jp2->brand, 4);		/* BR */
+-	cio_write(cio, jp2->minversion, 4);	/* MinV */
 +OPJ_BOOL opj_jp2_skip_jp2c(	opj_jp2_t *jp2,
 +					    	opj_stream_private_t *stream,
 +					    	opj_event_mgr_t * p_manager )
@@ -21237,18 +20951,23 @@ index 5ae114c..5c88c4d 100644
 +	assert(p_manager != 00);
 +
 +	jp2->j2k_codestream_offset = opj_stream_tell(stream);
-+
+ 
+-	for (i = 0; i < jp2->numcl; i++) {
+-		cio_write(cio, jp2->cl[i], 4);	/* CL */
 +	if (opj_stream_skip(stream,8,p_manager) != 8) {
 +		return OPJ_FALSE;
  	}
  
--	/* J2K encoding */
--	if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
--	    opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
--	    return OPJ_FALSE;
+-	box.length = cio_tell(cio) - box.init_pos;
+-	cio_seek(cio, box.init_pos);
+-	cio_write(cio, box.length, 4);	/* L */
+-	cio_seek(cio, box.init_pos + box.length);
 +	return OPJ_TRUE;
-+}
-+
+ }
+ 
+-static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
+-	int i;
+-	opj_jp2_box_t box;
 +static OPJ_BOOL opj_jpip_skip_iptr(	opj_jp2_t *jp2,
 +  opj_stream_private_t *stream,
 +  opj_event_mgr_t * p_manager )
@@ -21257,13 +20976,23 @@ index 5ae114c..5c88c4d 100644
 +  assert(jp2 != 00);
 +  assert(stream != 00);
 +  assert(p_manager != 00);
-+
+ 
+-	opj_common_ptr cinfo = jp2->cinfo;
 +  jp2->jpip_iptr_offset = opj_stream_tell(stream);
-+
+ 
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
+-    opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
 +  if (opj_stream_skip(stream,24,p_manager) != 24) {
-+    return OPJ_FALSE;
-+  }
-+
+     return OPJ_FALSE;
+   }
+-	if (JP2_FTYP != box.type) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
+-		return OPJ_FALSE;
+-	}
+ 
+-	jp2->brand = cio_read(cio, 4);		/* BR */
+-	jp2->minversion = cio_read(cio, 4);	/* MinV */
+-	jp2->numcl = (box.length - 16) / 4;
 +  return OPJ_TRUE;
 +}
 +
@@ -21291,29 +21020,27 @@ index 5ae114c..5c88c4d 100644
 +	assert(p_header_data != 00);
 +	assert(jp2 != 00);
 +	assert(p_manager != 00);
-+
+ 
+-  /* edf_c2_1673169.jp2 */
+-	if (cio_numbytesleft(cio) < ((int)jp2->numcl * 4)) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Not enough bytes in FTYP Box "
+-				"(expected %d, but only %d left)\n",
+-				((int)jp2->numcl * 4), cio_numbytesleft(cio));
 +	/* make sure the box is well placed */
 +	if ((jp2->jp2_state & JP2_STATE_FILE_TYPE) != JP2_STATE_FILE_TYPE ) {
 +		opj_event_msg(p_manager, EVT_ERROR, "The  box must be the first box in the file.\n");
-+		return OPJ_FALSE;
+ 		return OPJ_FALSE;
  	}
+-	jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
  
--	if( jp2->jpip_on){
--	  pos_cidx = cio_tell( cio);
--	  
--	  len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
--	  
--	  pos_fidx = cio_tell( cio);
--	  len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
--	  
--	  end_pos = cio_tell( cio);
--	  
--	  cio_seek( cio, pos_iptr);
--	  write_iptr( pos_fidx, len_fidx, cio);
--	  
--	  cio_seek( cio, end_pos);
+-	for (i = 0; i < (int)jp2->numcl; i++) {
+-		jp2->cl[i] = cio_read(cio, 4);	/* CLi */
+-	}
 +	jp2->jp2_img_state = JP2_IMG_STATE_NONE;
-+
+ 
+-	if (cio_tell(cio) - box.init_pos != box.length) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
+-		return OPJ_FALSE;
 +	/* iterate while remaining data */
 +	while (p_header_size > 0) {
 +
@@ -21348,7 +21075,12 @@ index 5ae114c..5c88c4d 100644
 +
  	return OPJ_TRUE;
  }
-+
+ 
+-static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
+-	unsigned int j2k_codestream_offset, j2k_codestream_length;
+-	opj_jp2_box_t box;
+-
+-	opj_j2k_t *j2k = jp2->j2k;
 +OPJ_BOOL opj_jp2_read_boxhdr_char(   opj_jp2_box_t *box,
 +                                     OPJ_BYTE * p_data,
 +                                     OPJ_UINT32 * p_number_bytes_read,
@@ -21357,52 +21089,94 @@ index 5ae114c..5c88c4d 100644
 +                                     )
 +{
 +	OPJ_UINT32 l_value;
-+
+ 
+-	box.init_pos = cio_tell(cio);
+-	cio_skip(cio, 4);
+-	cio_write(cio, JP2_JP2C, 4);	/* JP2C */
 +	/* preconditions */
 +	assert(p_data != 00);
 +	assert(box != 00);
 +	assert(p_number_bytes_read != 00);
 +	assert(p_manager != 00);
-+
+ 
+-	/* J2K encoding */
+-	j2k_codestream_offset = cio_tell(cio);
+-	if(!j2k_encode(j2k, cio, image, cstr_info)) {
+-		opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
+-		return 0;
 +	if (p_box_max_size < 8) {
 +		opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of less than 8 bytes\n");
 +		return OPJ_FALSE;
-+	}
-+
+ 	}
+-	j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
+-
+-	jp2->j2k_codestream_offset = j2k_codestream_offset;
+-	jp2->j2k_codestream_length = j2k_codestream_length;
+ 
+-	box.length = 8 + jp2->j2k_codestream_length;
+-	cio_seek(cio, box.init_pos);
+-	cio_write(cio, box.length, 4);	/* L */
+-	cio_seek(cio, box.init_pos + box.length);
 +	/* process read data */
 +	opj_read_bytes(p_data, &l_value, 4);
 +	p_data += 4;
 +	box->length = (OPJ_UINT32)(l_value);
-+
+ 
+-	return box.length;
+-}
 +	opj_read_bytes(p_data, &l_value, 4);
 +	p_data += 4;
 +	box->type = (OPJ_UINT32)(l_value);
-+
+ 
+-static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
+-	opj_jp2_box_t box;
 +	*p_number_bytes_read = 8;
-+
+ 
+-	opj_common_ptr cinfo = jp2->cinfo;
 +	/* do we have a "special very large box ?" */
 +	/* read then the XLBox */
 +	if (box->length == 1) {
 +		OPJ_UINT32 l_xl_part_size;
-+
+ 
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
+-    opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
+-    return OPJ_FALSE;
+-  }
+-	do {
+-		if(JP2_JP2C != box.type) {
+-			if (box.length <= 8) return OPJ_FALSE;
+-			cio_skip(cio, box.length - 8);
+-			if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
 +		if (p_box_max_size < 16) {
 +			opj_event_msg(p_manager, EVT_ERROR, "Cannot handle XL box of less than 16 bytes\n");
 +			return OPJ_FALSE;
-+		}
-+
+ 		}
+-	} while(JP2_JP2C != box.type);
+ 
+-	*j2k_codestream_offset = cio_tell(cio);
+-	if (box.length <= 8) return OPJ_FALSE;
+-	*j2k_codestream_length = box.length - 8;
 +		opj_read_bytes(p_data,&l_xl_part_size, 4);
 +		p_data += 4;
 +		*p_number_bytes_read += 4;
-+
+ 
+-	return OPJ_TRUE;
+-}
 +		if (l_xl_part_size != 0) {
 +			opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
 +			return OPJ_FALSE;
 +		}
-+
+ 
+-static void jp2_write_jp(opj_cio_t *cio) {
+-	opj_jp2_box_t box;
 +		opj_read_bytes(p_data, &l_value, 4);
 +		*p_number_bytes_read += 4;
 +		box->length = (OPJ_UINT32)(l_value);
-+
+ 
+-	box.init_pos = cio_tell(cio);
+-	cio_skip(cio, 4);
+-	cio_write(cio, JP2_JP, 4);		/* JP2 signature */
+-	cio_write(cio, 0x0d0a870a, 4);
 +		if (box->length == 0) {
 +			opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
 +			return OPJ_FALSE;
@@ -21412,10 +21186,16 @@ index 5ae114c..5c88c4d 100644
 +		opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
 +		return OPJ_FALSE;
 +	}
-+
+ 
+-	box.length = cio_tell(cio) - box.init_pos;
+-	cio_seek(cio, box.init_pos);
+-	cio_write(cio, box.length, 4);	/* L */
+-	cio_seek(cio, box.init_pos + box.length);
 +	return OPJ_TRUE;
-+}
-+
+ }
+ 
+-static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
+-	opj_jp2_box_t box;
 +OPJ_BOOL opj_jp2_read_header(	opj_stream_private_t *p_stream,
 +                                opj_jp2_t *jp2,
 +                                opj_image_t ** p_image,
@@ -21426,34 +21206,60 @@ index 5ae114c..5c88c4d 100644
 +	assert(jp2 != 00);
 +	assert(p_stream != 00);
 +	assert(p_manager != 00);
-+
+ 
+-	opj_common_ptr cinfo = jp2->cinfo;
 +	/* customization of the validation */
 +	opj_jp2_setup_decoding_validation (jp2);
-+
+ 
+-  if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
+-    opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
+-    return OPJ_FALSE;
+-  }
+-	if (JP2_JP != box.type) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
+-		return OPJ_FALSE;
+-	}
+-	if (0x0d0a870a != cio_read(cio, 4)) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
 +	/* customization of the encoding */
 +	opj_jp2_setup_header_reading(jp2);
 +
 +	/* validation of the parameters codec */
 +	if (! opj_jp2_exec(jp2,jp2->m_validation_list,p_stream,p_manager)) {
-+		return OPJ_FALSE;
-+	}
+ 		return OPJ_FALSE;
+ 	}
+-	if (cio_tell(cio) - box.init_pos != box.length) {
+-		opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
 +
 +	/* read header */
 +	if (! opj_jp2_exec (jp2,jp2->m_procedure_list,p_stream,p_manager)) {
-+		return OPJ_FALSE;
-+	}
-+
+ 		return OPJ_FALSE;
+ 	}
+ 
+-	return OPJ_TRUE;
 +	return opj_j2k_read_header(	p_stream,
 +							jp2->j2k,
 +							p_image,
 +							p_manager);
-+}
-+
+ }
+ 
 +void opj_jp2_setup_encoding_validation (opj_jp2_t *jp2)
 +{
 +	/* preconditions */
 +	assert(jp2 != 00);
-+
+ 
+-static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
+-	opj_jp2_color_t *color) {
+-	if (!jp2_read_jp(jp2, cio))
+-		return OPJ_FALSE;
+-	if (!jp2_read_ftyp(jp2, cio))
+-		return OPJ_FALSE;
+-	if (!jp2_read_jp2h(jp2, cio, color))
+-		return OPJ_FALSE;
+-	if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
+-		return OPJ_FALSE;
+-	
+-	return OPJ_TRUE;
 +	opj_procedure_list_add_procedure(jp2->m_validation_list, (opj_procedure)opj_jp2_default_validation);
 +	/* DEVELOPER CORNER, add your custom validation procedure */
 +}
@@ -21463,33 +21269,69 @@ index 5ae114c..5c88c4d 100644
 +	/* preconditions */
 +	assert(jp2 != 00);
 +	/* DEVELOPER CORNER, add your custom validation procedure */
-+}
-+
+ }
+ 
 +void opj_jp2_setup_header_writing (opj_jp2_t *jp2)
 +{
 +	/* preconditions */
 +	assert(jp2 != 00);
-+
+ 
+-static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
+-{  
+-  int len, lenp;
+-  
+-  lenp = cio_tell( cio);
+-  cio_skip( cio, 4);              /* L [at the end] */
+-  cio_write( cio, JPIP_FIDX, 4);  /* IPTR           */
+-  
+-  write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio);
 +	opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_jp );
 +	opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_ftyp );
 +	opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_jp2h );
 +  if( jp2->jpip_on )
 +    opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jpip_skip_iptr );
 +	opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_skip_jp2c );
-+
+ 
+-  len = cio_tell( cio)-lenp;
+-  cio_seek( cio, lenp);
+-  cio_write( cio, len, 4);        /* L              */
+-  cio_seek( cio, lenp+len);  
 +	/* DEVELOPER CORNER, insert your custom procedures */
-+
-+}
-+
+ 
+-  return len;
+ }
+ 
+-static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
 +void opj_jp2_setup_header_reading (opj_jp2_t *jp2)
-+{
+ {
+-  int len, lenp;
+-
+-  lenp = cio_tell( cio);
+-  cio_skip( cio, 4);              /* L [at the end] */
+-  cio_write( cio, JPIP_PRXY, 4);  /* IPTR           */
+-  
+-  cio_write( cio, offset_jp2c, 8); /* OOFF           */
+-  cio_write( cio, length_jp2c, 4); /* OBH part 1     */
+-  cio_write( cio, JP2_JP2C, 4);        /* OBH part 2     */
+-  
+-  cio_write( cio, 1,1);           /* NI             */
+-
+-  cio_write( cio, offset_idx, 8);  /* IOFF           */
+-  cio_write( cio, length_idx, 4);  /* IBH part 1     */
+-  cio_write( cio, JPIP_CIDX, 4);   /* IBH part 2     */
+-
+-  len = cio_tell( cio)-lenp;
+-  cio_seek( cio, lenp);
+-  cio_write( cio, len, 4);        /* L              */
+-  cio_seek( cio, lenp+len);
 +	/* preconditions */
 +	assert(jp2 != 00);
 +
 +	opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_read_header_procedure );
 +	/* DEVELOPER CORNER, add your custom procedures */
-+}
-+
+ }
+ 
+-static void write_iptr( int offset, int length, opj_cio_t *cio)
 +OPJ_BOOL opj_jp2_read_tile_header ( opj_jp2_t * p_jp2,
 +                                    OPJ_UINT32 * p_tile_index,
 +                                    OPJ_UINT32 * p_data_size,
@@ -21502,7 +21344,20 @@ index 5ae114c..5c88c4d 100644
 +                                    opj_stream_private_t *p_stream,
 +                                    opj_event_mgr_t * p_manager
 +                                    )
-+{
+ {
+-  int len, lenp;
+-  
+-  lenp = cio_tell( cio);
+-  cio_skip( cio, 4);              /* L [at the end] */
+-  cio_write( cio, JPIP_IPTR, 4);  /* IPTR           */
+-  
+-  cio_write( cio, offset, 8);
+-  cio_write( cio, length, 8);
+-
+-  len = cio_tell( cio)-lenp;
+-  cio_seek( cio, lenp);
+-  cio_write( cio, len, 4);        /* L             */
+-  cio_seek( cio, lenp+len);
 +	return opj_j2k_read_tile_header(p_jp2->j2k,
 +								p_tile_index,
 +								p_data_size,
@@ -21512,8 +21367,8 @@ index 5ae114c..5c88c4d 100644
 +								p_go_on,
 +								p_stream,
 +								p_manager);
-+}
-+
+ }
+ 
 +OPJ_BOOL opj_jp2_write_tile (	opj_jp2_t *p_jp2,
 +					 	 	    OPJ_UINT32 p_tile_index,
 +					 	 	    OPJ_BYTE * p_data,
@@ -21521,11 +21376,26 @@ index 5ae114c..5c88c4d 100644
 +					 	 	    opj_stream_private_t *p_stream,
 +					 	 	    opj_event_mgr_t * p_manager
 +                                )
-+
+ 
+-/* ----------------------------------------------------------------------- */
+-/* JP2 decoder interface                                             */
+-/* ----------------------------------------------------------------------- */
 +{
 +	return opj_j2k_write_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
 +}
-+
+ 
+-opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
+-	opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
+-	if(jp2) {
+-		jp2->cinfo = cinfo;
+-		/* create the J2K codec */
+-		jp2->j2k = j2k_create_decompress(cinfo);
+-		if(jp2->j2k == NULL) {
+-			jp2_destroy_decompress(jp2);
+-			return NULL;
+-		}
+-	}
+-	return jp2;
 +OPJ_BOOL opj_jp2_decode_tile (  opj_jp2_t * p_jp2,
 +                                OPJ_UINT32 p_tile_index,
 +                                OPJ_BYTE * p_data,
@@ -21535,22 +21405,27 @@ index 5ae114c..5c88c4d 100644
 +                                )
 +{
 +	return opj_j2k_decode_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
-+}
-+
+ }
+ 
+-void jp2_destroy_decompress(opj_jp2_t *jp2) {
+-	if(jp2) {
 +void opj_jp2_destroy(opj_jp2_t *jp2)
 +{
 +	if (jp2) {
-+		/* destroy the J2K codec */
+ 		/* destroy the J2K codec */
+-		j2k_destroy_decompress(jp2->j2k);
 +		opj_j2k_destroy(jp2->j2k);
 +		jp2->j2k = 00;
-+
+ 
+-		if(jp2->comps) {
 +		if (jp2->comps) {
-+			opj_free(jp2->comps);
+ 			opj_free(jp2->comps);
 +			jp2->comps = 00;
-+		}
+ 		}
+-		if(jp2->cl) {
 +
 +		if (jp2->cl) {
-+			opj_free(jp2->cl);
+ 			opj_free(jp2->cl);
 +			jp2->cl = 00;
 +		}
 +
@@ -21594,17 +21469,22 @@ index 5ae114c..5c88c4d 100644
 +		if (jp2->m_validation_list) {
 +			opj_procedure_list_destroy(jp2->m_validation_list);
 +			jp2->m_validation_list = 00;
-+		}
+ 		}
 +
 +		if (jp2->m_procedure_list) {
 +			opj_procedure_list_destroy(jp2->m_procedure_list);
 +			jp2->m_procedure_list = 00;
 +		}
 +
-+		opj_free(jp2);
-+	}
-+}
-+
+ 		opj_free(jp2);
+ 	}
+ }
+ 
+-void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
+-	/* setup the J2K codec */
+-	j2k_setup_decoder(jp2->j2k, parameters);
+-	/* further JP2 initializations go here */
+-	jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
 +OPJ_BOOL opj_jp2_set_decode_area(	opj_jp2_t *p_jp2,
 +								    opj_image_t* p_image,
 +								    OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
@@ -21666,31 +21546,48 @@ index 5ae114c..5c88c4d 100644
 +	}
 +
 +	return OPJ_TRUE;
-+}
-+
-+/* ----------------------------------------------------------------------- */
-+/* JP2 encoder interface                                             */
-+/* ----------------------------------------------------------------------- */
-+
+ }
+ 
+ /* ----------------------------------------------------------------------- */
+ /* JP2 encoder interface                                             */
+ /* ----------------------------------------------------------------------- */
+ 
+-opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
 +opj_jp2_t* opj_jp2_create(OPJ_BOOL p_is_decoder)
 +{
-+	opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
+ 	opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
+-	if(jp2) {
+-		memset(jp2, 0, sizeof(opj_jp2_t));
+-		jp2->cinfo = cinfo;
 +	if (jp2) {
 +		memset(jp2,0,sizeof(opj_jp2_t));
 +
-+		/* create the J2K codec */
+ 		/* create the J2K codec */
+-		jp2->j2k = j2k_create_compress(cinfo);
+-		if(jp2->j2k == NULL) {
+-			jp2_destroy_compress(jp2);
+-			return NULL;
 +		if (! p_is_decoder) {
 +			jp2->j2k = opj_j2k_create_compress();
 +		}
 +		else {
 +			jp2->j2k = opj_j2k_create_decompress();
-+		}
-+
+ 		}
+-	}
+-	return jp2;
+-}
+ 
+-void jp2_destroy_compress(opj_jp2_t *jp2) {
+-	if(jp2) {
+-		/* destroy the J2K codec */
+-		j2k_destroy_compress(jp2->j2k);
 +		if (jp2->j2k == 00) {
 +			opj_jp2_destroy(jp2);
 +			return 00;
 +		}
-+
+ 
+-		if(jp2->comps) {
+-			opj_free(jp2->comps);
 +		/* Color structure */
 +		jp2->color.icc_profile_buf = NULL;
 +		jp2->color.icc_profile_len = 0;
@@ -21703,48 +21600,73 @@ index 5ae114c..5c88c4d 100644
 +		if (! jp2->m_validation_list) {
 +			opj_jp2_destroy(jp2);
 +			return 00;
-+		}
+ 		}
+-		if(jp2->cl) {
+-			opj_free(jp2->cl);
 +
 +		/* execution list creation */
 +		jp2->m_procedure_list = opj_procedure_list_create();
 +		if (! jp2->m_procedure_list) {
 +			opj_jp2_destroy(jp2);
 +			return 00;
-+		}
-+	}
+ 		}
+-		opj_free(jp2);
+ 	}
 +
 +	return jp2;
-+}
-+
+ }
+ 
+-void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
+-	int i;
+-	int depth_0, sign;
 +void jp2_dump(opj_jp2_t* p_jp2, OPJ_INT32 flag, FILE* out_stream)
 +{
 +	/* preconditions */
 +	assert(p_jp2 != 00);
-+
+ 
+-	if(!jp2 || !parameters || !image)
+-		return;
 +	j2k_dump(p_jp2->j2k,
 +					flag,
 +					out_stream);
 +}
-+
+ 
+-	/* setup the J2K codec */
+-	/* ------------------- */
 +opj_codestream_index_t* jp2_get_cstr_index(opj_jp2_t* p_jp2)
 +{
 +	return j2k_get_cstr_index(p_jp2->j2k);
 +}
-+
+ 
+-	/* Check if number of components respects standard */
+-	if (image->numcomps < 1 || image->numcomps > 16384) {
+-		opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
+-		return;
+-	}
 +opj_codestream_info_v2_t* jp2_get_cstr_info(opj_jp2_t* p_jp2)
 +{
 +	return j2k_get_cstr_info(p_jp2->j2k);
 +}
-+
+ 
+-	j2k_setup_encoder(jp2->j2k, parameters, image);
 +OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
 +                                               OPJ_UINT32 res_factor,
 +                                               opj_event_mgr_t * p_manager)
 +{
 +	return opj_j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager);
 +}
-+
+ 
+-	/* setup the JP2 codec */
+-	/* ------------------- */
+-	
+-	/* Profile box */
 +/* JPIP specific */
-+
+ 
+-	jp2->brand = JP2_JP2;	/* BR */
+-	jp2->minversion = 0;	/* MinV */
+-	jp2->numcl = 1;
+-	jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
+-	jp2->cl[0] = JP2_JP2;	/* CL0 : JP2 */
 +#ifdef USE_JPIP
 +static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2,
 +  opj_stream_private_t *cio,
@@ -21769,17 +21691,51 @@ index 5ae114c..5c88c4d 100644
 +  opj_write_double(l_data_header + 4 + 4, 0); /* offset */
 +  opj_write_double(l_data_header + 8 + 8, 0); /* length */
 +#endif
-+
+ 
+-	/* Image Header box */
 +  if (! opj_stream_seek(cio,jp2->jpip_iptr_offset,p_manager)) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
 +  }
-+
+ 
+-	jp2->numcomps = image->numcomps;	/* NC */
+-	jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
+-	jp2->h = image->y1 - image->y0;		/* HEIGHT */
+-	jp2->w = image->x1 - image->x0;		/* WIDTH */
+-	/* BPC */
+-	depth_0 = image->comps[0].prec - 1;
+-	sign = image->comps[0].sgnd;
+-	jp2->bpc = depth_0 + (sign << 7);
+-	for (i = 1; i < image->numcomps; i++) {
+-		int depth = image->comps[i].prec - 1;
+-		sign = image->comps[i].sgnd;
+-		if (depth_0 != depth)
+-			jp2->bpc = 255;
+-	}
+-	jp2->C = 7;			/* C : Always 7 */
+-	jp2->UnkC = 0;		/* UnkC, colorspace specified in colr box */
+-	jp2->IPR = 0;		/* IPR, no intellectual property */
+-	
+-	/* BitsPerComponent box */
 +  if (opj_stream_write_data(cio,l_data_header,24,p_manager) != 24) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
 +  }
-+
+ 
+-	for (i = 0; i < image->numcomps; i++) {
+-		jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
+-	}
+-	jp2->meth = 1;
+-	if (image->color_space == 1)
+-		jp2->enumcs = 16;	/* sRGB as defined by IEC 61966-2.1 */
+-	else if (image->color_space == 2)
+-		jp2->enumcs = 17;	/* greyscale */
+-	else if (image->color_space == 3)
+-		jp2->enumcs = 18;	/* YUV */
+-	jp2->precedence = 0;	/* PRECEDENCE */
+-	jp2->approx = 0;		/* APPROX */
+-	
+-	jp2->jpip_on = parameters->jpip_on;
 +  if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
@@ -21818,8 +21774,9 @@ index 5ae114c..5c88c4d 100644
 +  }
 +
 +  return OPJ_TRUE;
-+}
-+
+ }
+ 
+-opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
 +static OPJ_BOOL opj_jpip_write_cidx(opj_jp2_t *jp2,
 +  opj_stream_private_t *cio,
 +  opj_event_mgr_t * p_manager )
@@ -21843,26 +21800,46 @@ index 5ae114c..5c88c4d 100644
 +  opj_write_double(l_data_header + 4 + 4, 0); /* offset */
 +  opj_write_double(l_data_header + 8 + 8, 0); /* length */
 +#endif
-+
+ 
+-	int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
+-	pos_jp2c = pos_iptr = -1; /* remove a warning */
 +  if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
 +  }
-+
+ 
+-	/* JP2 encoding */
 +  if (opj_stream_write_data(cio,l_data_header,24,p_manager) != 24) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
 +  }
-+
+ 
+-	/* JPEG 2000 Signature box */
+-	jp2_write_jp(cio);
+-	/* File Type box */
+-	jp2_write_ftyp(jp2, cio);
+-	/* JP2 Header box */
+-	jp2_write_jp2h(jp2, cio);
 +  j2k_codestream_exit = opj_stream_tell(cio);
 +  if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
 +    opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
 +    return OPJ_FALSE;
 +  }
-+
+ 
+-	if( jp2->jpip_on){
+-	  pos_iptr = cio_tell( cio);
+-	  cio_skip( cio, 24); /* IPTR further ! */
+-	  
+-	  pos_jp2c = cio_tell( cio);
+-	}
 +  return OPJ_TRUE;
 +}
-+
+ 
+-	/* J2K encoding */
+-	if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
+-	    opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
+-	    return OPJ_FALSE;
+-	}
 +#if 0
 +static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio,
 +  opj_event_mgr_t * p_manager )
@@ -21897,8 +21874,24 @@ index 5ae114c..5c88c4d 100644
 +  opj_stream_seek(cio, lenp+len,p_manager);
 +}
 +#endif
-+
-+
+ 
+-	if( jp2->jpip_on){
+-	  pos_cidx = cio_tell( cio);
+-	  
+-	  len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
+-	  
+-	  pos_fidx = cio_tell( cio);
+-	  len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
+-	  
+-	  end_pos = cio_tell( cio);
+-	  
+-	  cio_seek( cio, pos_iptr);
+-	  write_iptr( pos_fidx, len_fidx, cio);
+-	  
+-	  cio_seek( cio, end_pos);
+-	}
+ 
+-	return OPJ_TRUE;
 +#if 0
 +static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio,
 +  opj_event_mgr_t * p_manager )
@@ -21920,7 +21913,7 @@ index 5ae114c..5c88c4d 100644
 +  opj_stream_seek(cio, lenp+len,p_manager);
 +
 +  return len;
-+}
+ }
 +#endif
 +#endif /* USE_JPIP */
 diff --git a/extern/libopenjpeg/jp2.h b/extern/libopenjpeg/jp2.h
@@ -22665,124 +22658,6 @@ index a2566ea..0000000
 -		header->Layer_nb = jpt_read_VBAS_info(cio, header->Layer_nb);
 -	}
 -}
-diff --git a/extern/libopenjpeg/jpt.h b/extern/libopenjpeg/jpt.h
-deleted file mode 100644
-index eb01f98..0000000
---- a/extern/libopenjpeg/jpt.h
-+++ /dev/null
-@@ -1,75 +0,0 @@
--/*
-- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
-- * Copyright (c) 2002-2007, Professor Benoit Macq
-- * Copyright (c) 2002-2003, Yannick Verschueren
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
--
--#ifndef __JPT_H
--#define __JPT_H
--/**
-- at file jpt.h
-- at brief JPT-stream reader (JPEG 2000, JPIP)
--
--JPT-stream functions are implemented in J2K.C. 
--*/
--
--/**
--Message Header JPT stream structure
--*/
--typedef struct opj_jpt_msg_header {
--	/** In-class Identifier */
--	unsigned int Id;
--	/** Last byte information */
--	unsigned int last_byte;	
--	/** Class Identifier */
--	unsigned int Class_Id;	
--	/** CSn : index identifier */
--	unsigned int CSn_Id;
--	/** Message offset */
--	unsigned int Msg_offset;
--	/** Message length */
--	unsigned int Msg_length;
--	/** Auxiliary for JPP case */
--	unsigned int Layer_nb;
--} opj_jpt_msg_header_t;
--
--/* ----------------------------------------------------------------------- */
--
--/**
--Initialize the value of the message header structure 
-- at param header Message header structure
--*/
--void jpt_init_msg_header(opj_jpt_msg_header_t * header);
--
--/**
--Read the message header for a JPP/JPT - stream
-- at param cinfo Codec context info
-- at param cio CIO handle
-- at param header Message header structure
--*/
--void jpt_read_msg_header(opj_common_ptr cinfo, opj_cio_t *cio, opj_jpt_msg_header_t *header);
--
--#endif
-diff --git a/extern/libopenjpeg/license.txt b/extern/libopenjpeg/license.txt
-deleted file mode 100644
-index d1e5b6a..0000000
---- a/extern/libopenjpeg/license.txt
-+++ /dev/null
-@@ -1,30 +0,0 @@
--/*
-- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
-- * Copyright (c) 2002-2007, Professor Benoit Macq
-- * Copyright (c) 2001-2003, David Janssens
-- * Copyright (c) 2002-2003, Yannick Verschueren
-- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
-- * Copyright (c) 2005, Herve Drolon, FreeImage Team
-- * All rights reserved.
-- *
-- * Redistribution and use in source and binary forms, with or without
-- * modification, are permitted provided that the following conditions
-- * are met:
-- * 1. Redistributions of source code must retain the above copyright
-- *    notice, this list of conditions and the following disclaimer.
-- * 2. Redistributions in binary form must reproduce the above copyright
-- *    notice, this list of conditions and the following disclaimer in the
-- *    documentation and/or other materials provided with the distribution.
-- *
-- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- * POSSIBILITY OF SUCH DAMAGE.
-- */
-\ No newline at end of file
 diff --git a/extern/libopenjpeg/mct.c b/extern/libopenjpeg/mct.c
 index 870993b..60ee096 100644
 --- a/extern/libopenjpeg/mct.c
@@ -25009,7 +24884,7 @@ index 180cc84..4665d90 100644
 +    return l_stream;
 +}
 diff --git a/extern/libopenjpeg/openjpeg.h b/extern/libopenjpeg/openjpeg.h
-index 53e9fac..988db72 100644
+index 59147c8..988db72 100644
 --- a/extern/libopenjpeg/openjpeg.h
 +++ b/extern/libopenjpeg/openjpeg.h
 @@ -1,12 +1,21 @@
@@ -25136,7 +25011,7 @@ index 53e9fac..988db72 100644
  #define JPWL_MAX_NO_TILESPECS	16 /**< Maximum number of tile parts expected by JPWL: increase at your will */
  #define JPWL_MAX_NO_PACKSPECS	16 /**< Maximum number of packet parts expected by JPWL: increase at your will */
  #define JPWL_MAX_NO_MARKERS	512 /**< Maximum number of JPWL markers: increase at your will */
-@@ -88,71 +159,141 @@ typedef int opj_bool;
+@@ -88,75 +159,141 @@ typedef int opj_bool;
  #define JPWL_MAXIMUM_EPB_ROOM 65450 /**< Expect this maximum number of bytes for composition of EPBs */
  /* <<UniPG */
  
@@ -25290,6 +25165,10 @@ index 53e9fac..988db72 100644
 +    OPJ_CLRSPC_CMYK = 5         /**< CMYK */
  } OPJ_COLOR_SPACE;
  
+-#define ENUMCS_SRGB 16
+-#define ENUMCS_GRAY 17
+-#define ENUMCS_SYCC 18
+-
  /**
 -Supported codec
 + * Supported codec
@@ -25318,7 +25197,7 @@ index 53e9fac..988db72 100644
  
  /* 
  ==========================================================
-@@ -161,31 +302,12 @@ typedef enum LIMIT_DECODING {
+@@ -165,31 +302,12 @@ typedef enum LIMIT_DECODING {
  */
  
  /**
@@ -25354,7 +25233,7 @@ index 53e9fac..988db72 100644
  /* 
  ==========================================================
     codec typedef definitions
-@@ -193,39 +315,40 @@ typedef struct opj_event_mgr {
+@@ -197,39 +315,40 @@ typedef struct opj_event_mgr {
  */
  
  /**
@@ -25410,7 +25289,7 @@ index 53e9fac..988db72 100644
  	/** XTOsiz */
  	int cp_tx0;
  	/** YTOsiz */
-@@ -246,15 +369,15 @@ typedef struct opj_cparameters {
+@@ -250,15 +369,15 @@ typedef struct opj_cparameters {
  	char *cp_comment;
  	/** csty : coding style */
  	int csty;
@@ -25429,7 +25308,7 @@ index 53e9fac..988db72 100644
  	float tcp_rates[100];
  	/** different psnr for successive layers */
  	float tcp_distoratio[100];
-@@ -275,9 +398,9 @@ typedef struct opj_cparameters {
+@@ -279,9 +398,9 @@ typedef struct opj_cparameters {
  	/* number of precinct size specifications */
  	int res_spec;
  	/** initial precinct width */
@@ -25441,7 +25320,7 @@ index 53e9fac..988db72 100644
  
  	/**@name command line encoder parameters (not used inside the library) */
  	/*@{*/
-@@ -303,11 +426,11 @@ typedef struct opj_cparameters {
+@@ -307,11 +426,11 @@ typedef struct opj_cparameters {
  	int cod_format;
  	/*@}*/
  
@@ -25455,7 +25334,7 @@ index 53e9fac..988db72 100644
  	/** error protection method for MH (0,1,16,32,37-128) */
  	int jpwl_hprot_MH;
  	/** tile number of header protection specification (>=0) */
-@@ -335,12 +458,21 @@ typedef struct opj_cparameters {
+@@ -339,12 +458,21 @@ typedef struct opj_cparameters {
  	/*@}*/
  /* <<UniPG */
  
@@ -25482,7 +25361,7 @@ index 53e9fac..988db72 100644
  	/** Tile part generation*/
  	char tp_on;
  	/** Flag for Tile part generation*/
-@@ -348,14 +480,27 @@ typedef struct opj_cparameters {
+@@ -352,14 +480,27 @@ typedef struct opj_cparameters {
  	/** MCT (multiple component transform) */
  	char tcp_mct;
  	/** Enable JPIP indexing*/
@@ -25514,7 +25393,7 @@ index 53e9fac..988db72 100644
  typedef struct opj_dparameters {
  	/** 
  	Set the number of highest resolution levels to be discarded. 
-@@ -364,16 +509,16 @@ typedef struct opj_dparameters {
+@@ -368,16 +509,16 @@ typedef struct opj_dparameters {
  	if != 0, then original dimension divided by 2^(reduce); 
  	if == 0 or not used, image is decoded to the full resolution 
  	*/
@@ -25534,7 +25413,7 @@ index 53e9fac..988db72 100644
  	/*@{*/
  	/** input file name */
  	char infile[OPJ_PATH_LEN];
-@@ -383,13 +528,30 @@ typedef struct opj_dparameters {
+@@ -387,13 +528,30 @@ typedef struct opj_dparameters {
  	int decod_format;
  	/** output file format 0: PGX, 1: PxM, 2: BMP */
  	int cod_format;
@@ -25567,7 +25446,7 @@ index 53e9fac..988db72 100644
  	/** expected number of components */
  	int jpwl_exp_comps;
  	/** maximum number of tiles */
-@@ -397,59 +559,15 @@ typedef struct opj_dparameters {
+@@ -401,59 +559,15 @@ typedef struct opj_dparameters {
  	/*@}*/
  /* <<UniPG */
  
@@ -25581,9 +25460,9 @@ index 53e9fac..988db72 100644
 -
  	unsigned int flags;
 -} opj_dparameters_t;
--
--/** Common fields between JPEG-2000 compression and decompression master structs. */
  
+-/** Common fields between JPEG-2000 compression and decompression master structs. */
+-
 -#define opj_common_fields \
 -	opj_event_mgr_t *event_mgr;	/**< pointer to the event manager */\
 -	void * client_data;			/**< Available for use by application */\
@@ -25631,7 +25510,7 @@ index 53e9fac..988db72 100644
  
  /* 
  ==========================================================
-@@ -457,35 +575,43 @@ typedef struct opj_dinfo {
+@@ -461,35 +575,43 @@ typedef struct opj_dinfo {
  ==========================================================
  */
  
@@ -25662,6 +25541,11 @@ index 53e9fac..988db72 100644
 + * Callback function prototype for write function
 + */
 +typedef OPJ_SIZE_T (* opj_stream_write_fn) (void * p_buffer, OPJ_SIZE_T p_nb_bytes, void * p_user_data) ;
++
++/*
++ * Callback function prototype for skip function
++ */
++typedef OPJ_OFF_T (* opj_stream_skip_fn) (OPJ_OFF_T p_nb_bytes, void * p_user_data) ;
  
 -	/** open mode (read/write) either OPJ_STREAM_READ or OPJ_STREAM_WRITE */
 -	int openmode;
@@ -25670,14 +25554,14 @@ index 53e9fac..988db72 100644
 -	/** buffer size in bytes */
 -	int length;
 +/*
-+ * Callback function prototype for skip function
++ * Callback function prototype for seek function
 + */
-+typedef OPJ_OFF_T (* opj_stream_skip_fn) (OPJ_OFF_T p_nb_bytes, void * p_user_data) ;
++typedef OPJ_BOOL (* opj_stream_seek_fn) (OPJ_OFF_T p_nb_bytes, void * p_user_data) ;
 +
 +/*
-+ * Callback function prototype for seek function
++ * Callback function prototype for free user data function
 + */
-+typedef OPJ_BOOL (* opj_stream_seek_fn) (OPJ_OFF_T p_nb_bytes, void * p_user_data) ;
++typedef void (* opj_stream_free_user_data_fn) (void * p_user_data) ;
  
 -	/** pointer to the start of the stream */
 -	unsigned char *start;
@@ -25687,18 +25571,13 @@ index 53e9fac..988db72 100644
 -	unsigned char *bp;
 -} opj_cio_t;
 +/*
-+ * Callback function prototype for free user data function
-+ */
-+typedef void (* opj_stream_free_user_data_fn) (void * p_user_data) ;
-+
-+/*
 + * JPEG2000 Stream.
 + */
 +typedef void * opj_stream_t;
  
  /* 
  ==========================================================
-@@ -494,99 +620,104 @@ typedef struct opj_cio {
+@@ -498,99 +620,104 @@ typedef struct opj_cio {
  */
  
  /**
@@ -25842,7 +25721,7 @@ index 53e9fac..988db72 100644
  	/** packet distorsion */
  	double disto;
  } opj_packet_info_t;
-@@ -594,20 +725,20 @@ typedef struct opj_packet_info {
+@@ -598,20 +725,20 @@ typedef struct opj_packet_info {
  
  /* UniPG>> */
  /**
@@ -25868,7 +25747,7 @@ index 53e9fac..988db72 100644
  */
  typedef struct opj_tp_info {
  	/** start position of tile part */
-@@ -623,7 +754,7 @@ typedef struct opj_tp_info {
+@@ -627,7 +754,7 @@ typedef struct opj_tp_info {
  } opj_tp_info_t;
  
  /**
@@ -25877,7 +25756,7 @@ index 53e9fac..988db72 100644
  */
  typedef struct opj_tile_info {
  	/** value of thresh for each layer by tile cfr. Marcela   */
-@@ -663,7 +794,7 @@ typedef struct opj_tile_info {
+@@ -667,7 +794,7 @@ typedef struct opj_tile_info {
  } opj_tile_info_t;
  
  /**
@@ -25886,7 +25765,7 @@ index 53e9fac..988db72 100644
  */
  typedef struct opj_codestream_info {
  	/** maximum distortion reduction on the whole image (add for Marcela) */
-@@ -714,6 +845,197 @@ typedef struct opj_codestream_info {
+@@ -718,6 +845,197 @@ typedef struct opj_codestream_info {
  	opj_tile_info_t *tile;
  } opj_codestream_info_t;
  
@@ -26084,7 +25963,7 @@ index 53e9fac..988db72 100644
  #ifdef __cplusplus
  extern "C" {
  #endif
-@@ -725,6 +1047,7 @@ extern "C" {
+@@ -729,6 +1047,7 @@ extern "C" {
  ==========================================================
  */
  
@@ -26092,7 +25971,7 @@ index 53e9fac..988db72 100644
  OPJ_API const char * OPJ_CALLCONV opj_version(void);
  
  /* 
-@@ -734,20 +1057,33 @@ OPJ_API const char * OPJ_CALLCONV opj_version(void);
+@@ -738,20 +1057,33 @@ OPJ_API const char * OPJ_CALLCONV opj_version(void);
  */
  
  /**
@@ -26136,7 +26015,7 @@ index 53e9fac..988db72 100644
  /* 
  ==========================================================
     stream functions definitions
-@@ -755,100 +1091,314 @@ OPJ_API void OPJ_CALLCONV opj_image_destroy(opj_image_t *image);
+@@ -759,100 +1091,314 @@ OPJ_API void OPJ_CALLCONV opj_image_destroy(opj_image_t *image);
  */
  
  /**
@@ -26514,7 +26393,7 @@ index 53e9fac..988db72 100644
  /**
  Set encoding parameters to default values, that means : 
  <ul>
-@@ -871,36 +1421,135 @@ Set encoding parameters to default values, that means :
+@@ -875,36 +1421,135 @@ Set encoding parameters to default values, that means :
  @param parameters Compression parameters
  */
  OPJ_API void OPJ_CALLCONV opj_set_default_encoder_parameters(opj_cparameters_t *parameters);
@@ -26672,141 +26551,106 @@ index 53e9fac..988db72 100644
  
  
  #ifdef __cplusplus
-diff --git a/extern/libopenjpeg/opj_clock.c b/extern/libopenjpeg/opj_clock.c
-new file mode 100644
-index 0000000..0df99ef
---- /dev/null
+diff --git a/extern/libopenjpeg/j2k_lib.c b/extern/libopenjpeg/opj_clock.c
+similarity index 80%
+rename from extern/libopenjpeg/j2k_lib.c
+rename to extern/libopenjpeg/opj_clock.c
+index a66e31e..0df99ef 100644
+--- a/extern/libopenjpeg/j2k_lib.c
 +++ b/extern/libopenjpeg/opj_clock.c
-@@ -0,0 +1,64 @@
-+/*
+@@ -1,4 +1,9 @@
+ /*
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
 + * are granted under this license.
 + *
-+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
-+ */
-+
-+#ifdef _WIN32
-+#include <windows.h>
-+#else
-+#include <sys/time.h>
-+#include <sys/resource.h>
-+#include <sys/times.h>
-+#endif /* _WIN32 */
-+#include "opj_includes.h"
-+
+  * Copyright (c) 2005, Herve Drolon, FreeImage Team
+  * All rights reserved.
+  *
+@@ -33,7 +38,7 @@
+ #endif /* _WIN32 */
+ #include "opj_includes.h"
+ 
+-double opj_clock(void) {
 +OPJ_FLOAT64 opj_clock(void) {
-+#ifdef _WIN32
-+	/* _WIN32: use QueryPerformance (very accurate) */
-+    LARGE_INTEGER freq , t ;
-+    /* freq is the clock speed of the CPU */
-+    QueryPerformanceFrequency(&freq) ;
-+	/* cout << "freq = " << ((double) freq.QuadPart) << endl; */
-+    /* t is the high resolution performance counter (see MSDN) */
-+    QueryPerformanceCounter ( & t ) ;
+ #ifdef _WIN32
+ 	/* _WIN32: use QueryPerformance (very accurate) */
+     LARGE_INTEGER freq , t ;
+@@ -42,18 +47,18 @@ double opj_clock(void) {
+ 	/* cout << "freq = " << ((double) freq.QuadPart) << endl; */
+     /* t is the high resolution performance counter (see MSDN) */
+     QueryPerformanceCounter ( & t ) ;
+-    return ( t.QuadPart /(double) freq.QuadPart ) ;
 +    return ( t.QuadPart /(OPJ_FLOAT64) freq.QuadPart ) ;
-+#else
-+	/* Unix or Linux: use resource usage */
-+    struct rusage t;
+ #else
+ 	/* Unix or Linux: use resource usage */
+     struct rusage t;
+-    double procTime;
 +    OPJ_FLOAT64 procTime;
-+    /* (1) Get the rusage data structure at this moment (man getrusage) */
-+    getrusage(0,&t);
-+    /* (2) What is the elapsed time ? - CPU time = User time + System time */
-+	/* (2a) Get the seconds */
+     /* (1) Get the rusage data structure at this moment (man getrusage) */
+     getrusage(0,&t);
+     /* (2) What is the elapsed time ? - CPU time = User time + System time */
+ 	/* (2a) Get the seconds */
+-    procTime = t.ru_utime.tv_sec + t.ru_stime.tv_sec;
 +    procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
-+    /* (2b) More precisely! Get the microseconds part ! */
+     /* (2b) More precisely! Get the microseconds part ! */
+-    return ( procTime + (t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
 +    return ( procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
-+#endif
-+}
-+
-diff --git a/extern/libopenjpeg/opj_clock.h b/extern/libopenjpeg/opj_clock.h
-new file mode 100644
-index 0000000..6f5168b
---- /dev/null
+ #endif
+ }
+ 
+diff --git a/extern/libopenjpeg/j2k_lib.h b/extern/libopenjpeg/opj_clock.h
+similarity index 78%
+rename from extern/libopenjpeg/j2k_lib.h
+rename to extern/libopenjpeg/opj_clock.h
+index 5f3406e..6f5168b 100644
+--- a/extern/libopenjpeg/j2k_lib.h
 +++ b/extern/libopenjpeg/opj_clock.h
-@@ -0,0 +1,59 @@
-+/*
+@@ -1,4 +1,9 @@
+ /*
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
 + * are granted under this license.
 + *
-+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
-+ */
+  * Copyright (c) 2005, Herve Drolon, FreeImage Team
+  * All rights reserved.
+  *
+@@ -23,13 +28,13 @@
+  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  * POSSIBILITY OF SUCH DAMAGE.
+  */
+-#ifndef __J2K_LIB_H
+-#define __J2K_LIB_H
 +#ifndef __OPJ_CLOCK_H
 +#define __OPJ_CLOCK_H
-+/**
+ /**
+- at file j2k_lib.h
+- at brief Internal functions
 + at file opj_clock.h
 + at brief Internal function for timing
-+
+ 
+-The functions in J2K_LIB.C are internal utilities mainly used for timing.
 +The functions in OPJ_CLOCK.C are internal utilities mainly used for timing.
-+*/
-+
-+/** @defgroup MISC MISC - Miscellaneous internal functions */
-+/*@{*/
-+
-+/** @name Exported functions */
-+/*@{*/
-+/* ----------------------------------------------------------------------- */
-+
-+/**
-+Difference in successive opj_clock() calls tells you the elapsed time
-+ at return Returns time in seconds
-+*/
+ */
+ 
+ /** @defgroup MISC MISC - Miscellaneous internal functions */
+@@ -43,12 +48,12 @@ The functions in J2K_LIB.C are internal utilities mainly used for timing.
+ Difference in successive opj_clock() calls tells you the elapsed time
+ @return Returns time in seconds
+ */
+-double opj_clock(void);
 +OPJ_FLOAT64 opj_clock(void);
-+
-+/* ----------------------------------------------------------------------- */
-+/*@}*/
-+
-+/*@}*/
-+
+ 
+ /* ----------------------------------------------------------------------- */
+ /*@}*/
+ 
+ /*@}*/
+ 
+-#endif /* __J2K_LIB_H */
 +#endif /* __OPJ_CLOCK_H */
-+
+ 
 diff --git a/extern/libopenjpeg/opj_codec.h b/extern/libopenjpeg/opj_codec.h
 new file mode 100644
 index 0000000..4fdfa7d
@@ -26979,17 +26823,17 @@ index 0000000..4fdfa7d
 +#endif /* __OPJ_CODEC_H */
 +
 diff --git a/extern/libopenjpeg/opj_config.h b/extern/libopenjpeg/opj_config.h
-index 82e12be..815ed3d 100644
+index 5d0a877..815ed3d 100644
 --- a/extern/libopenjpeg/opj_config.h
 +++ b/extern/libopenjpeg/opj_config.h
-@@ -1,38 +1,5 @@
+@@ -1,39 +1,5 @@
 -/* for BLENDER - we hand-maintain this,
 - * for the original OpenJpeg package it is generated,
 - * the endian check is a blender define */
 +#define OPJ_HAVE_STDINT_H 		1
  
 -/* create config.h for CMake */
--#define PACKAGE_VERSION "1.5.0"
+-#define PACKAGE_VERSION "1.5.2"
 -
 -#define HAVE_INTTYPES_H
 -#define HAVE_MEMORY_H
@@ -27009,6 +26853,7 @@ index 82e12be..815ed3d 100644
 -/* #undef HAVE_LIBLCMS2 */
 -/* #undef HAVE_LCMS1_H */
 -/* #undef HAVE_LCMS2_H */
+-/* #undef USE_SYSTEM_GETOPT */
 -
 -/* Byte order.  */
 -/* All compilers that support Mac OS X define either __BIG_ENDIAN__ or
@@ -27038,7 +26883,7 @@ index 0000000..61f82ec
 +
 +// #define OPJ_HAVE_FSEEKO ON
 diff --git a/extern/libopenjpeg/opj_includes.h b/extern/libopenjpeg/opj_includes.h
-index 2b5866a..d9238b1 100644
+index e9194fd..d9238b1 100644
 --- a/extern/libopenjpeg/opj_includes.h
 +++ b/extern/libopenjpeg/opj_includes.h
 @@ -1,5 +1,12 @@
@@ -27132,7 +26977,7 @@ index 2b5866a..d9238b1 100644
  
  /* Are restricted pointers available? (C99) */
  #if (__STDC_VERSION__ != 199901L)
-@@ -86,8 +118,8 @@ Most compilers implement their own version of this keyword ...
+@@ -86,54 +118,63 @@ Most compilers implement their own version of this keyword ...
  	#endif
  #endif
  
@@ -27141,9 +26986,23 @@ index 2b5866a..d9238b1 100644
 +/* MSVC before 2013 and Borland C do not have lrintf */
 +#if defined(_MSC_VER) && (_MSC_VER < 1800) || defined(__BORLANDC__)
  static INLINE long lrintf(float f){
- #ifdef _M_X64
-     return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
-@@ -104,37 +136,45 @@ static INLINE long lrintf(float f){
+-#ifdef _M_IX86
+-    long int i;
++#ifdef _M_X64
++    return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
++#else
++    int i;
+  
+     _asm{
+         fld f
+         fistp i
+     };
++ 
+     return i;
+-#else
+-    return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f));
+-#endif /* _M_IX86 */
++#endif
  }
  #endif
  
@@ -27195,13 +27054,17 @@ index 2b5866a..d9238b1 100644
 +
 +
  #endif /* OPJ_INCLUDES_H */
-diff --git a/extern/libopenjpeg/opj_intmath.h b/extern/libopenjpeg/opj_intmath.h
-new file mode 100644
-index 0000000..dc89895
---- /dev/null
+diff --git a/extern/libopenjpeg/int.h b/extern/libopenjpeg/opj_intmath.h
+similarity index 54%
+rename from extern/libopenjpeg/int.h
+rename to extern/libopenjpeg/opj_intmath.h
+index 4e5fe08..dc89895 100644
+--- a/extern/libopenjpeg/int.h
 +++ b/extern/libopenjpeg/opj_intmath.h
-@@ -0,0 +1,178 @@
-+/*
+@@ -1,9 +1,15 @@
+ /*
+- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+- * Copyright (c) 2002-2007, Professor Benoit Macq
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
@@ -27209,53 +27072,36 @@ index 0000000..dc89895
 + *
 + * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
 + * Copyright (c) 2002-2014, Professor Benoit Macq
-+ * Copyright (c) 2001-2003, David Janssens
-+ * Copyright (c) 2002-2003, Yannick Verschueren
+  * Copyright (c) 2001-2003, David Janssens
+  * Copyright (c) 2002-2003, Yannick Verschueren
+- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
 + * Copyright (c) 2003-2007, Francois-Olivier Devaux 
 + * Copyright (c) 2003-2014, Antonin Descampe
-+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
-+ */
-+#ifndef __INT_H
-+#define __INT_H
-+/**
+  * Copyright (c) 2005, Herve Drolon, FreeImage Team
+  * All rights reserved.
+  *
+@@ -31,13 +37,13 @@
+ #ifndef __INT_H
+ #define __INT_H
+ /**
+- at file int.h
 + at file opj_intmath.h
-+ at brief Implementation of operations on integers (INT)
-+
+ @brief Implementation of operations on integers (INT)
+ 
+-The functions in INT.H have for goal to realize operations on integers.
 +The functions in OPJ_INTMATH.H have for goal to realize operations on integers.
-+*/
-+
+ */
+ 
+-/** @defgroup INT INT - Implementation of operations on integers */
 +/** @defgroup OPJ_INTMATH OPJ_INTMATH - Implementation of operations on integers */
-+/*@{*/
-+
-+/** @name Exported functions (see also openjpeg.h) */
-+/*@{*/
-+/* ----------------------------------------------------------------------- */
-+/**
-+Get the minimum of two integers
-+ at return Returns a if a < b else b
-+*/
+ /*@{*/
+ 
+ /** @name Exported functions (see also openjpeg.h) */
+@@ -47,16 +53,34 @@ The functions in INT.H have for goal to realize operations on integers.
+ Get the minimum of two integers
+ @return Returns a if a < b else b
+ */
+-static INLINE int int_min(int a, int b) {
 +static INLINE OPJ_INT32 opj_int_min(OPJ_INT32 a, OPJ_INT32 b) {
 +	return a < b ? a : b;
 +}
@@ -27265,16 +27111,17 @@ index 0000000..dc89895
 + at return Returns a if a < b else b
 +*/
 +static INLINE OPJ_UINT32 opj_uint_min(OPJ_UINT32 a, OPJ_UINT32 b) {
-+	return a < b ? a : b;
-+}
+ 	return a < b ? a : b;
+ }
 +
-+/**
-+Get the maximum of two integers
-+ at return Returns a if a > b else b
-+*/
+ /**
+ Get the maximum of two integers
+ @return Returns a if a > b else b
+ */
+-static INLINE int int_max(int a, int b) {
 +static INLINE OPJ_INT32 opj_int_max(OPJ_INT32 a, OPJ_INT32 b) {
-+	return (a > b) ? a : b;
-+}
+ 	return (a > b) ? a : b;
+ }
 +
 +/**
 +Get the maximum of two integers
@@ -27284,32 +27131,31 @@ index 0000000..dc89895
 +	return (a > b) ? a : b;
 +}
 +
-+/**
-+Clamp an integer inside an interval
-+ at return
-+<ul>
-+<li>Returns a if (min < a < max)
-+<li>Returns max if (a > max)
-+<li>Returns min if (a < min) 
-+</ul>
-+*/
+ /**
+ Clamp an integer inside an interval
+ @return
+@@ -66,7 +90,7 @@ Clamp an integer inside an interval
+ <li>Returns min if (a < min) 
+ </ul>
+ */
+-static INLINE int int_clamp(int a, int min, int max) {
 +static INLINE OPJ_INT32 opj_int_clamp(OPJ_INT32 a, OPJ_INT32 min, OPJ_INT32 max) {
-+	if (a < min)
-+		return min;
-+	if (a > max)
-+		return max;
-+	return a;
-+}
-+/**
-+ at return Get absolute value of integer
-+*/
+ 	if (a < min)
+ 		return min;
+ 	if (a > max)
+@@ -76,41 +100,76 @@ static INLINE int int_clamp(int a, int min, int max) {
+ /**
+ @return Get absolute value of integer
+ */
+-static INLINE int int_abs(int a) {
 +static INLINE OPJ_INT32 opj_int_abs(OPJ_INT32 a) {
-+	return a < 0 ? -a : a;
-+}
-+/**
-+Divide an integer and round upwards
-+ at return Returns a divided by b
-+*/
+ 	return a < 0 ? -a : a;
+ }
+ /**
+ Divide an integer and round upwards
+ @return Returns a divided by b
+ */
+-static INLINE int int_ceildiv(int a, int b) {
 +static INLINE OPJ_INT32 opj_int_ceildiv(OPJ_INT32 a, OPJ_INT32 b) {
 +  assert(b);
 +	return (a + b - 1) / b;
@@ -27320,34 +27166,39 @@ index 0000000..dc89895
 + at return Returns a divided by b
 +*/
 +static INLINE OPJ_UINT32  opj_uint_ceildiv(OPJ_UINT32  a, OPJ_UINT32  b) {
-+	return (a + b - 1) / b;
-+}
+ 	return (a + b - 1) / b;
+ }
 +
-+/**
-+Divide an integer by a power of 2 and round upwards
-+ at return Returns a divided by 2^b
-+*/
+ /**
+ Divide an integer by a power of 2 and round upwards
+ @return Returns a divided by 2^b
+ */
+-static INLINE int int_ceildivpow2(int a, int b) {
+-	return (a + (1 << b) - 1) >> b;
 +static INLINE OPJ_INT32 opj_int_ceildivpow2(OPJ_INT32 a, OPJ_INT32 b) {
 +	return (OPJ_INT32)((a + (OPJ_INT64)(1 << b) - 1) >> b);
-+}
-+/**
-+Divide an integer by a power of 2 and round downwards
-+ at return Returns a divided by 2^b
-+*/
+ }
+ /**
+ Divide an integer by a power of 2 and round downwards
+ @return Returns a divided by 2^b
+ */
+-static INLINE int int_floordivpow2(int a, int b) {
 +static INLINE OPJ_INT32 opj_int_floordivpow2(OPJ_INT32 a, OPJ_INT32 b) {
-+	return a >> b;
-+}
-+/**
-+Get logarithm of an integer and round downwards
-+ at return Returns log2(a)
-+*/
+ 	return a >> b;
+ }
+ /**
+ Get logarithm of an integer and round downwards
+ @return Returns log2(a)
+ */
+-static INLINE int int_floorlog2(int a) {
+-	int l;
 +static INLINE OPJ_INT32 opj_int_floorlog2(OPJ_INT32 a) {
 +	OPJ_INT32 l;
-+	for (l = 0; a > 1; l++) {
-+		a >>= 1;
-+	}
-+	return l;
-+}
+ 	for (l = 0; a > 1; l++) {
+ 		a >>= 1;
+ 	}
+ 	return l;
+ }
 +/**
 +Get logarithm of an integer and round downwards
 + at return Returns log2(a)
@@ -27373,47 +27224,39 @@ index 0000000..dc89895
 +    return (OPJ_INT32) (temp >> 13) ;
 +}
 +
-+/* ----------------------------------------------------------------------- */
-+/*@}*/
-+
-+/*@}*/
-+
-+#endif
-diff --git a/extern/libopenjpeg/opj_inttypes.h b/extern/libopenjpeg/opj_inttypes.h
-new file mode 100644
-index 0000000..e74aed6
---- /dev/null
+ /* ----------------------------------------------------------------------- */
+ /*@}*/
+ 
+diff --git a/extern/libopenjpeg/license.txt b/extern/libopenjpeg/opj_inttypes.h
+similarity index 66%
+rename from extern/libopenjpeg/license.txt
+rename to extern/libopenjpeg/opj_inttypes.h
+index d1e5b6a..e74aed6 100644
+--- a/extern/libopenjpeg/license.txt
 +++ b/extern/libopenjpeg/opj_inttypes.h
-@@ -0,0 +1,48 @@
-+/*
+@@ -1,10 +1,10 @@
+ /*
+- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+- * Copyright (c) 2002-2007, Professor Benoit Macq
+- * Copyright (c) 2001-2003, David Janssens
+- * Copyright (c) 2002-2003, Yannick Verschueren
+- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+- * Copyright (c) 2005, Herve Drolon, FreeImage Team
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
 + * are granted under this license.
 + *
 + * Copyright (c) 2012, Mathieu Malaterre <mathieu.malaterre at gmail.com>
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
+  * All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+@@ -27,4 +27,22 @@
+  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  * POSSIBILITY OF SUCH DAMAGE.
+- */
+\ No newline at end of file
 + */
 +#ifndef OPJ_INTTYPES_H
 +#define OPJ_INTTYPES_H
@@ -27434,7 +27277,7 @@ index 0000000..e74aed6
 +
 +#endif /* OPJ_INTTYPES_H */
 diff --git a/extern/libopenjpeg/opj_malloc.h b/extern/libopenjpeg/opj_malloc.h
-index 87493f4..d321054 100644
+index aef2ee3..5007b0c 100644
 --- a/extern/libopenjpeg/opj_malloc.h
 +++ b/extern/libopenjpeg/opj_malloc.h
 @@ -1,4 +1,9 @@
@@ -27475,7 +27318,7 @@ index 87493f4..d321054 100644
  
  /**
  Allocate memory aligned to a 16 byte boundry
-@@ -137,8 +152,13 @@ Reallocate memory blocks.
+@@ -139,8 +154,13 @@ Reallocate memory blocks.
  #ifdef ALLOC_PERF_OPT
  void * OPJ_CALLCONV opj_realloc(void * m, size_t s);
  #else
@@ -27489,45 +27332,41 @@ index 87493f4..d321054 100644
  
  /**
  Deallocates or frees a memory block.
-diff --git a/extern/libopenjpeg/opj_stdint.h b/extern/libopenjpeg/opj_stdint.h
-new file mode 100644
-index 0000000..b8556a1
---- /dev/null
+diff --git a/extern/libopenjpeg/fix.h b/extern/libopenjpeg/opj_stdint.h
+similarity index 56%
+rename from extern/libopenjpeg/fix.h
+rename to extern/libopenjpeg/opj_stdint.h
+index bcb2acb..b8556a1 100644
+--- a/extern/libopenjpeg/fix.h
 +++ b/extern/libopenjpeg/opj_stdint.h
-@@ -0,0 +1,52 @@
-+/*
+@@ -1,10 +1,10 @@
+ /*
+- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
+- * Copyright (c) 2002-2007, Professor Benoit Macq
+- * Copyright (c) 2001-2003, David Janssens
+- * Copyright (c) 2002-2003, Yannick Verschueren
+- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+- * Copyright (c) 2005, Herve Drolon, FreeImage Team
 + * The copyright in this software is being made available under the 2-clauses 
 + * BSD License, included below. This software may be subject to other third 
 + * party and contributor rights, including patent rights, and no such rights
 + * are granted under this license.
 + *
 + * Copyright (c) 2012, Mathieu Malaterre <mathieu.malaterre at gmail.com>
-+ * All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    notice, this list of conditions and the following disclaimer in the
-+ *    documentation and/or other materials provided with the distribution.
-+ *
-+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-+ * POSSIBILITY OF SUCH DAMAGE.
-+ */
+  * All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+@@ -28,37 +28,25 @@
+  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+  * POSSIBILITY OF SUCH DAMAGE.
+  */
+-#ifndef __FIX_H
+-#define __FIX_H
 +#ifndef OPJ_STDINT_H
 +#define OPJ_STDINT_H
-+
+ 
+-#if defined(_MSC_VER) || defined(__BORLANDC__)
+-#define int64 __int64
 +#include "opj_config.h"
 +#ifdef OPJ_HAVE_STDINT_H
 +#include <stdint.h>
@@ -27541,11 +27380,37 @@ index 0000000..b8556a1
 +typedef unsigned __int32  uint32_t;
 +typedef   signed __int64  int64_t;
 +typedef unsigned __int64  uint64_t;
-+#else
+ #else
+-#define int64 long long
 +#error unsupported platform
 +#endif
-+#endif
-+
+ #endif
+ 
+-/**
+- at file fix.h
+- at brief Implementation of operations of specific multiplication (FIX)
+-
+-The functions in FIX.H have for goal to realize specific multiplication.
+-*/
+-
+-/** @defgroup FIX FIX - Implementation of operations of specific multiplication */
+-/*@{*/
+-
+-/**
+-Multiply two fixed-precision rational numbers.
+- at param a
+- at param b
+- at return Returns a * b
+-*/
+-static INLINE int fix_mul(int a, int b) {
+-    int64 temp = (int64) a * (int64) b ;
+-    temp += temp & 4096;
+-    return (int) (temp >> 13) ;
+-}
+-
+-/*@}*/
+-
+-#endif /* __FIX_H */
 +#endif /* OPJ_STDINT_H */
 diff --git a/extern/libopenjpeg/phix_manager.c b/extern/libopenjpeg/phix_manager.c
 index 60a0281..5a3e883 100644
@@ -30662,7 +30527,7 @@ index 3c4b372..572c666 100644
  /*@}*/
  
 diff --git a/extern/libopenjpeg/t1.c b/extern/libopenjpeg/t1.c
-index 4777204..0d6c2f6 100644
+index ed9cdc3..0d6c2f6 100644
 --- a/extern/libopenjpeg/t1.c
 +++ b/extern/libopenjpeg/t1.c
 @@ -1,9 +1,15 @@
@@ -33032,7 +32897,7 @@ index 4777204..0d6c2f6 100644
  								t1,
  								cblk,
  								band->bandno,
-@@ -1481,104 +1540,218 @@ void t1_encode_cblks(
+@@ -1481,105 +1540,218 @@ void t1_encode_cblks(
  								band->stepsize,
  								tccp->cblksty,
  								tile->numcomps,
@@ -33188,6 +33053,7 @@ index 4777204..0d6c2f6 100644
 -					opj_free(cblk->segs);
 -				} /* cblkno */
 -				opj_free(precinct->cblks.dec);
+-                precinct->cblks.dec = NULL;
 -			} /* precno */
 -		} /* bandno */
 -	} /* resno */
@@ -33805,7 +33671,7 @@ index e5e33f6..37776b6 100644
    0x1880, 0x1780, 0x1700, 0x1600, 0x1500, 0x1480, 0x1380, 0x1300, 
    0x1200, 0x1180, 0x1080, 0x1000, 0x0f00, 0x0e80, 0x0e00, 0x0d00, 
 diff --git a/extern/libopenjpeg/t2.c b/extern/libopenjpeg/t2.c
-index 232a543..37f9814 100644
+index 2585c3d..37f9814 100644
 --- a/extern/libopenjpeg/t2.c
 +++ b/extern/libopenjpeg/t2.c
 @@ -1,10 +1,18 @@
@@ -33830,7 +33696,15 @@ index 232a543..37f9814 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -37,47 +45,104 @@
+@@ -30,7 +38,6 @@
+  */
+ 
+ #include "opj_includes.h"
+-#include <assert.h>
+ 
+ /** @defgroup T2 T2 - Implementation of a tier-2 coding */
+ /*@{*/
+@@ -38,47 +45,104 @@
  /** @name Local static functions */
  /*@{*/
  
@@ -33863,17 +33737,17 @@ index 232a543..37f9814 100644
 - at param cstr_info Codestream information structure 
 - at param tileno Number of the tile encoded
 - at return 
-+ at param cstr_info Codestream information structure
-+ at return
- */
+-*/
 -static int t2_encode_packet(opj_tcd_tile_t *tile, opj_tcp_t *tcp, opj_pi_iterator_t *pi, unsigned char *dest, int len, opj_codestream_info_t *cstr_info, int tileno);
 -/**
 - at param cblk
 - at param index
 - at param cblksty
 - at param first
--*/
--static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
++ at param cstr_info Codestream information structure
++ at return
+ */
+-static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first);
 +static OPJ_BOOL opj_t2_encode_packet(   OPJ_UINT32 tileno,
 +                                        opj_tcd_tile_t *tile,
 +                                        opj_tcp_t *tcp,
@@ -33957,29 +33831,22 @@ index 232a543..37f9814 100644
  
  /*@}*/
  
-@@ -86,708 +151,1194 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
+@@ -87,739 +151,1194 @@ static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_t
  /* ----------------------------------------------------------------------- */
  
  /* #define RESTART 0x04 */
--
--static void t2_putcommacode(opj_bio_t *bio, int n) {
--	while (--n >= 0) {
--		bio_write(bio, 1, 1);
--	}
--	bio_write(bio, 0, 1);
 +static void opj_t2_putcommacode(opj_bio_t *bio, OPJ_INT32 n) {
 +        while (--n >= 0) {
 +                opj_bio_write(bio, 1, 1);
 +        }
 +        opj_bio_write(bio, 0, 1);
- }
++}
  
--static int t2_getcommacode(opj_bio_t *bio) {
--	int n;
--	for (n = 0; bio_read(bio, 1); n++) {
--		;
+-static void t2_putcommacode(opj_bio_t *bio, int n) {
+-	while (--n >= 0) {
+-		bio_write(bio, 1, 1);
 -	}
--	return n;
+-	bio_write(bio, 0, 1);
 +OPJ_UINT32 opj_t2_getcommacode(opj_bio_t *bio) 
 +{
 +    OPJ_UINT32 n = 0;
@@ -33989,18 +33856,12 @@ index 232a543..37f9814 100644
 +    return n;
  }
  
--static void t2_putnumpasses(opj_bio_t *bio, int n) {
--	if (n == 1) {
--		bio_write(bio, 0, 1);
--	} else if (n == 2) {
--		bio_write(bio, 2, 2);
--	} else if (n <= 5) {
--		bio_write(bio, 0xc | (n - 3), 4);
--	} else if (n <= 36) {
--		bio_write(bio, 0x1e0 | (n - 6), 9);
--	} else if (n <= 164) {
--		bio_write(bio, 0xff80 | (n - 37), 16);
+-static int t2_getcommacode(opj_bio_t *bio) {
+-	int n;
+-	for (n = 0; bio_read(bio, 1); n++) {
+-		;
 -	}
+-	return n;
 +void opj_t2_putnumpasses(opj_bio_t *bio, OPJ_UINT32 n) {
 +        if (n == 1) {
 +                opj_bio_write(bio, 0, 1);
@@ -34015,17 +33876,18 @@ index 232a543..37f9814 100644
 +        }
  }
  
--static int t2_getnumpasses(opj_bio_t *bio) {
--	int n;
--	if (!bio_read(bio, 1))
--		return 1;
--	if (!bio_read(bio, 1))
--		return 2;
--	if ((n = bio_read(bio, 2)) != 3)
--		return (3 + n);
--	if ((n = bio_read(bio, 5)) != 31)
--		return (6 + n);
--	return (37 + bio_read(bio, 7));
+-static void t2_putnumpasses(opj_bio_t *bio, int n) {
+-	if (n == 1) {
+-		bio_write(bio, 0, 1);
+-	} else if (n == 2) {
+-		bio_write(bio, 2, 2);
+-	} else if (n <= 5) {
+-		bio_write(bio, 0xc | (n - 3), 4);
+-	} else if (n <= 36) {
+-		bio_write(bio, 0x1e0 | (n - 6), 9);
+-	} else if (n <= 164) {
+-		bio_write(bio, 0xff80 | (n - 37), 16);
+-	}
 +OPJ_UINT32 opj_t2_getnumpasses(opj_bio_t *bio) {
 +        OPJ_UINT32 n;
 +        if (!opj_bio_read(bio, 1))
@@ -34039,6 +33901,140 @@ index 232a543..37f9814 100644
 +        return (37 + opj_bio_read(bio, 7));
  }
  
+-static int t2_getnumpasses(opj_bio_t *bio) {
+-	int n;
+-	if (!bio_read(bio, 1))
+-		return 1;
+-	if (!bio_read(bio, 1))
+-		return 2;
+-	if ((n = bio_read(bio, 2)) != 3)
+-		return (3 + n);
+-	if ((n = bio_read(bio, 5)) != 31)
+-		return (6 + n);
+-	return (37 + bio_read(bio, 7));
++/* ----------------------------------------------------------------------- */
++
++OPJ_BOOL opj_t2_encode_packets( opj_t2_t* p_t2,
++                                OPJ_UINT32 p_tile_no,
++                                opj_tcd_tile_t *p_tile,
++                                OPJ_UINT32 p_maxlayers,
++                                OPJ_BYTE *p_dest,
++                                OPJ_UINT32 * p_data_written,
++                                OPJ_UINT32 p_max_len,
++                                opj_codestream_info_t *cstr_info,
++                                OPJ_UINT32 p_tp_num,
++                                OPJ_INT32 p_tp_pos,
++                                OPJ_UINT32 p_pino,
++                                J2K_T2_MODE p_t2_mode)
++{
++        OPJ_BYTE *l_current_data = p_dest;
++        OPJ_UINT32 l_nb_bytes = 0;
++        OPJ_UINT32 compno;
++        OPJ_UINT32 poc;
++        opj_pi_iterator_t *l_pi = 00;
++        opj_pi_iterator_t *l_current_pi = 00;
++        opj_image_t *l_image = p_t2->image;
++        opj_cp_t *l_cp = p_t2->cp;
++        opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
++        OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K)? 2: 1;
++        OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ? l_image->numcomps : 1;
++        OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
++
++        l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
++        if (!l_pi) {
++                return OPJ_FALSE;
++        }
++
++        * p_data_written = 0;
++
++        if (p_t2_mode == THRESH_CALC ){ /* Calculating threshold */
++                l_current_pi = l_pi;
++
++                for     (compno = 0; compno < l_max_comp; ++compno) {
++                        OPJ_UINT32 l_comp_len = 0;
++                        l_current_pi = l_pi;
++
++                        for (poc = 0; poc < pocno ; ++poc) {
++                                OPJ_UINT32 l_tp_num = compno;
++
++                                /* TODO MSD : check why this function cannot fail (cf. v1) */
++                                opj_pi_create_encode(l_pi, l_cp,p_tile_no,poc,l_tp_num,p_tp_pos,p_t2_mode);
++
++                                while (opj_pi_next(l_current_pi)) {
++                                        if (l_current_pi->layno < p_maxlayers) {
++                                                l_nb_bytes = 0;
++
++                                                if (! opj_t2_encode_packet(p_tile_no,p_tile, l_tcp, l_current_pi, l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
++                                                        opj_pi_destroy(l_pi, l_nb_pocs);
++                                                        return OPJ_FALSE;
++                                                }
++
++                                                l_comp_len += l_nb_bytes;
++                                                l_current_data += l_nb_bytes;
++                                                p_max_len -= l_nb_bytes;
++
++                                                * p_data_written += l_nb_bytes;
++                                        }
++                                }
++
++                                if (l_cp->m_specific_param.m_enc.m_max_comp_size) {
++                                        if (l_comp_len > l_cp->m_specific_param.m_enc.m_max_comp_size) {
++                                                opj_pi_destroy(l_pi, l_nb_pocs);
++                                                return OPJ_FALSE;
++                                        }
++                                }
++
++                                ++l_current_pi;
++                        }
++                }
++        }
++        else {  /* t2_mode == FINAL_PASS  */
++                opj_pi_create_encode(l_pi, l_cp,p_tile_no,p_pino,p_tp_num,p_tp_pos,p_t2_mode);
++
++                l_current_pi = &l_pi[p_pino];
++
++                while (opj_pi_next(l_current_pi)) {
++                        if (l_current_pi->layno < p_maxlayers) {
++                                l_nb_bytes=0;
++
++                                if (! opj_t2_encode_packet(p_tile_no,p_tile, l_tcp, l_current_pi, l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
++                                        opj_pi_destroy(l_pi, l_nb_pocs);
++                                        return OPJ_FALSE;
++                                }
++
++                                l_current_data += l_nb_bytes;
++                                p_max_len -= l_nb_bytes;
++
++                                * p_data_written += l_nb_bytes;
++
++                                /* INDEX >> */
++                                if(cstr_info) {
++                                        if(cstr_info->index_write) {
++                                                opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
++                                                opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
++                                                if (!cstr_info->packno) {
++                                                        info_PK->start_pos = info_TL->end_header + 1;
++                                                } else {
++                                                        info_PK->start_pos = ((l_cp->m_specific_param.m_enc.m_tp_on | l_tcp->POC)&& info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1;
++                                                }
++                                                info_PK->end_pos = info_PK->start_pos + l_nb_bytes - 1;
++                                                info_PK->end_ph_pos += info_PK->start_pos - 1;  /* End of packet header which now only represents the distance
++                                                                                                                                                                                                                                                   to start of packet is incremented by value of start of packet*/
++                                        }
++
++                                        cstr_info->packno++;
++                                }
++                                /* << INDEX */
++                                ++p_tile->packno;
++                        }
++                }
++        }
++
++        opj_pi_destroy(l_pi, l_nb_pocs);
++
++        return OPJ_TRUE;
+ }
+ 
 -static int t2_encode_packet(opj_tcd_tile_t * tile, opj_tcp_t * tcp, opj_pi_iterator_t *pi, unsigned char *dest, int length, opj_codestream_info_t *cstr_info, int tileno) {
 -	int bandno, cblkno;
 -	unsigned char *c = dest;
@@ -34204,132 +34200,53 @@ index 232a543..37f9814 100644
 -	}
 -	
 -	return (c - dest);
-+/* ----------------------------------------------------------------------- */
-+
-+OPJ_BOOL opj_t2_encode_packets( opj_t2_t* p_t2,
++/* see issue 80 */
++#if 0
++#define JAS_FPRINTF fprintf
++#else
++/* issue 290 */
++static void opj_null_jas_fprintf(FILE* file, const char * format, ...)
++{
++  (void)file;
++  (void)format;
+ }
++#define JAS_FPRINTF opj_null_jas_fprintf
++#endif
+ 
+-static opj_bool t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
+-	opj_tcd_seg_t* seg;
+-    opj_tcd_seg_t* segs;
+-    segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
++OPJ_BOOL opj_t2_decode_packets( opj_t2_t *p_t2,
 +                                OPJ_UINT32 p_tile_no,
 +                                opj_tcd_tile_t *p_tile,
-+                                OPJ_UINT32 p_maxlayers,
-+                                OPJ_BYTE *p_dest,
-+                                OPJ_UINT32 * p_data_written,
++                                OPJ_BYTE *p_src,
++                                OPJ_UINT32 * p_data_read,
 +                                OPJ_UINT32 p_max_len,
-+                                opj_codestream_info_t *cstr_info,
-+                                OPJ_UINT32 p_tp_num,
-+                                OPJ_INT32 p_tp_pos,
-+                                OPJ_UINT32 p_pino,
-+                                J2K_T2_MODE p_t2_mode)
++                                opj_codestream_index_t *p_cstr_index)
 +{
-+        OPJ_BYTE *l_current_data = p_dest;
-+        OPJ_UINT32 l_nb_bytes = 0;
-+        OPJ_UINT32 compno;
-+        OPJ_UINT32 poc;
++        OPJ_BYTE *l_current_data = p_src;
 +        opj_pi_iterator_t *l_pi = 00;
-+        opj_pi_iterator_t *l_current_pi = 00;
++        OPJ_UINT32 pino;
 +        opj_image_t *l_image = p_t2->image;
 +        opj_cp_t *l_cp = p_t2->cp;
-+        opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
-+        OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K)? 2: 1;
-+        OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ? l_image->numcomps : 1;
++        opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
++        OPJ_UINT32 l_nb_bytes_read;
 +        OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
-+
-+        l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
-+        if (!l_pi) {
-+                return OPJ_FALSE;
-+        }
-+
-+        * p_data_written = 0;
-+
-+        if (p_t2_mode == THRESH_CALC ){ /* Calculating threshold */
-+                l_current_pi = l_pi;
-+
-+                for     (compno = 0; compno < l_max_comp; ++compno) {
-+                        OPJ_UINT32 l_comp_len = 0;
-+                        l_current_pi = l_pi;
-+
-+                        for (poc = 0; poc < pocno ; ++poc) {
-+                                OPJ_UINT32 l_tp_num = compno;
-+
-+                                /* TODO MSD : check why this function cannot fail (cf. v1) */
-+                                opj_pi_create_encode(l_pi, l_cp,p_tile_no,poc,l_tp_num,p_tp_pos,p_t2_mode);
-+
-+                                while (opj_pi_next(l_current_pi)) {
-+                                        if (l_current_pi->layno < p_maxlayers) {
-+                                                l_nb_bytes = 0;
-+
-+                                                if (! opj_t2_encode_packet(p_tile_no,p_tile, l_tcp, l_current_pi, l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
-+                                                        opj_pi_destroy(l_pi, l_nb_pocs);
-+                                                        return OPJ_FALSE;
-+                                                }
-+
-+                                                l_comp_len += l_nb_bytes;
-+                                                l_current_data += l_nb_bytes;
-+                                                p_max_len -= l_nb_bytes;
-+
-+                                                * p_data_written += l_nb_bytes;
-+                                        }
-+                                }
-+
-+                                if (l_cp->m_specific_param.m_enc.m_max_comp_size) {
-+                                        if (l_comp_len > l_cp->m_specific_param.m_enc.m_max_comp_size) {
-+                                                opj_pi_destroy(l_pi, l_nb_pocs);
-+                                                return OPJ_FALSE;
-+                                        }
-+                                }
-+
-+                                ++l_current_pi;
-+                        }
-+                }
-+        }
-+        else {  /* t2_mode == FINAL_PASS  */
-+                opj_pi_create_encode(l_pi, l_cp,p_tile_no,p_pino,p_tp_num,p_tp_pos,p_t2_mode);
-+
-+                l_current_pi = &l_pi[p_pino];
-+
-+                while (opj_pi_next(l_current_pi)) {
-+                        if (l_current_pi->layno < p_maxlayers) {
-+                                l_nb_bytes=0;
-+
-+                                if (! opj_t2_encode_packet(p_tile_no,p_tile, l_tcp, l_current_pi, l_current_data, &l_nb_bytes, p_max_len, cstr_info)) {
-+                                        opj_pi_destroy(l_pi, l_nb_pocs);
-+                                        return OPJ_FALSE;
-+                                }
-+
-+                                l_current_data += l_nb_bytes;
-+                                p_max_len -= l_nb_bytes;
-+
-+                                * p_data_written += l_nb_bytes;
-+
-+                                /* INDEX >> */
-+                                if(cstr_info) {
-+                                        if(cstr_info->index_write) {
-+                                                opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
-+                                                opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
-+                                                if (!cstr_info->packno) {
-+                                                        info_PK->start_pos = info_TL->end_header + 1;
-+                                                } else {
-+                                                        info_PK->start_pos = ((l_cp->m_specific_param.m_enc.m_tp_on | l_tcp->POC)&& info_PK->start_pos) ? info_PK->start_pos : info_TL->packet[cstr_info->packno - 1].end_pos + 1;
-+                                                }
-+                                                info_PK->end_pos = info_PK->start_pos + l_nb_bytes - 1;
-+                                                info_PK->end_ph_pos += info_PK->start_pos - 1;  /* End of packet header which now only represents the distance
-+                                                                                                                                                                                                                                                   to start of packet is incremented by value of start of packet*/
-+                                        }
-+
-+                                        cstr_info->packno++;
-+                                }
-+                                /* << INDEX */
-+                                ++p_tile->packno;
-+                        }
-+                }
-+        }
-+
-+        opj_pi_destroy(l_pi, l_nb_pocs);
-+
-+        return OPJ_TRUE;
- }
++        opj_pi_iterator_t *l_current_pi = 00;
++#ifdef TODO_MSD
++        OPJ_UINT32 curtp = 0;
++        OPJ_UINT32 tp_start_packno;
++#endif 
++        opj_packet_info_t *l_pack_info = 00;
++        opj_image_comp_t* l_img_comp = 00;
  
--static void t2_init_seg(opj_tcd_cblk_dec_t* cblk, int index, int cblksty, int first) {
--	opj_tcd_seg_t* seg;
--	cblk->segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, (index + 1) * sizeof(opj_tcd_seg_t));
+-    if (segs == NULL)
+-    {
+-        return OPJ_FALSE;
+-    }
+-    cblk->segs = segs;
+-
 -	seg = &cblk->segs[index];
 -	seg->data = NULL;
 -	seg->dataindex = 0;
@@ -34347,18 +34264,10 @@ index 232a543..37f9814 100644
 -	} else {
 -		seg->maxpasses = 109;
 -	}
-+/* see issue 80 */
-+#if 0
-+#define JAS_FPRINTF fprintf
-+#else
-+/* issue 290 */
-+static void opj_null_jas_fprintf(FILE* file, const char * format, ...)
-+{
-+  (void)file;
-+  (void)format;
- }
-+#define JAS_FPRINTF opj_null_jas_fprintf
-+#endif
+-
+-    return OPJ_TRUE;
+-}
++        OPJ_ARG_NOT_USED(p_cstr_index);
  
 -static int t2_decode_packet(opj_t2_t* t2, unsigned char *src, int len, opj_tcd_tile_t *tile, 
 -														opj_tcp_t *tcp, opj_pi_iterator_t *pi, opj_packet_info_t *pack_info) {
@@ -34372,13 +34281,15 @@ index 232a543..37f9814 100644
 -	int precno = pi->precno;	/* precinct value */
 -	int layno  = pi->layno;		/* quality layer value */
 -
--	opj_tcd_resolution_t* res = &tile->comps[compno].resolutions[resno];
--
 -	unsigned char *hd = NULL;
 -	int present;
 -	
 -	opj_bio_t *bio = NULL;	/* BIO component */
--	
+-
+-	opj_tcd_resolution_t* res;
+-	assert(&tile->comps[compno] != NULL);
+-	res = &tile->comps[compno].resolutions[resno];
+-
 -	if (layno == 0) {
 -		for (bandno = 0; bandno < res->numbands; bandno++) {
 -			opj_tcd_band_t *band = &res->bands[bandno];
@@ -34504,12 +34415,48 @@ index 232a543..37f9814 100644
 -			cblk->numlenbits += increment;
 -			segno = 0;
 -			if (!cblk->numsegs) {
--				t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1);
+-                if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 1))
++#ifdef TODO_MSD
++        if (p_cstr_index) {
++                l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
++        }
++#endif
++
++        /* create a packet iterator */
++        l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
++        if (!l_pi) {
++                return OPJ_FALSE;
++        }
++
++
++        l_current_pi = l_pi;
++
++        for     (pino = 0; pino <= l_tcp->numpocs; ++pino) {
++
++                /* if the resolution needed is too low, one dim of the tilec could be equal to zero
++                 * and no packets are used to decode this resolution and
++                 * l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
++                 * and no l_img_comp->resno_decoded are computed
++                 */
++                OPJ_BOOL* first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));
++                if (!first_pass_failed)
+                 {
+-                    opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
+-                    bio_destroy(bio);
+-                    return -999;
++                    opj_pi_destroy(l_pi,l_nb_pocs);
++                    return OPJ_FALSE;
+                 }
 -			} else {
 -				segno = cblk->numsegs - 1;
 -				if (cblk->segs[segno].numpasses == cblk->segs[segno].maxpasses) {
 -					++segno;
--					t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
+-                    if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
+-                    {
+-                        opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
+-                        bio_destroy(bio);
+-                        return -999;
+-                    }
 -				}
 -			}
 -			n = cblk->numnewpasses;
@@ -34520,7 +34467,12 @@ index 232a543..37f9814 100644
 -				n -= cblk->segs[segno].numnewpasses;
 -				if (n > 0) {
 -					++segno;
--					t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0);
+-                    if (!t2_init_seg(cblk, segno, tcp->tccps[compno].cblksty, 0))
+-                    {
+-                        opj_event_msg(t2->cinfo, EVT_ERROR, "Out of memory\n");
+-                        bio_destroy(bio);
+-                        return -999;
+-                    }
 -				}
 -			} while (n > 0);
 -		}
@@ -34589,29 +34541,7 @@ index 232a543..37f9814 100644
 -				if (c + seg->newlen > src + len) {
 -					return -999;
 -				}
-+OPJ_BOOL opj_t2_decode_packets( opj_t2_t *p_t2,
-+                                OPJ_UINT32 p_tile_no,
-+                                opj_tcd_tile_t *p_tile,
-+                                OPJ_BYTE *p_src,
-+                                OPJ_UINT32 * p_data_read,
-+                                OPJ_UINT32 p_max_len,
-+                                opj_codestream_index_t *p_cstr_index)
-+{
-+        OPJ_BYTE *l_current_data = p_src;
-+        opj_pi_iterator_t *l_pi = 00;
-+        OPJ_UINT32 pino;
-+        opj_image_t *l_image = p_t2->image;
-+        opj_cp_t *l_cp = p_t2->cp;
-+        opj_tcp_t *l_tcp = &(p_t2->cp->tcps[p_tile_no]);
-+        OPJ_UINT32 l_nb_bytes_read;
-+        OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;
-+        opj_pi_iterator_t *l_current_pi = 00;
-+#ifdef TODO_MSD
-+        OPJ_UINT32 curtp = 0;
-+        OPJ_UINT32 tp_start_packno;
-+#endif 
-+        opj_packet_info_t *l_pack_info = 00;
-+        opj_image_comp_t* l_img_comp = 00;
++                memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));
  
 -#ifdef USE_JPWL
 -			/* we need here a j2k handle to verify if making a check to
@@ -34630,7 +34560,9 @@ index 232a543..37f9814 100644
 -					opj_event_msg(t2->cinfo, EVT_WARNING, "      - truncating segment to %d\n", seg->newlen);
 -					break;
 -				};
-+        OPJ_ARG_NOT_USED(p_cstr_index);
++                while (opj_pi_next(l_current_pi)) {
++                  JAS_FPRINTF( stderr, "packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\n\n",
++                    l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno, l_current_pi->precno, l_current_pi->layno );
  
 -#endif /* USE_JPWL */
 -				
@@ -34654,40 +34586,6 @@ index 232a543..37f9814 100644
 -	}
 -	
 -	return (c - src);
-+#ifdef TODO_MSD
-+        if (p_cstr_index) {
-+                l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
-+        }
-+#endif
-+
-+        /* create a packet iterator */
-+        l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
-+        if (!l_pi) {
-+                return OPJ_FALSE;
-+        }
-+
-+
-+        l_current_pi = l_pi;
-+
-+        for     (pino = 0; pino <= l_tcp->numpocs; ++pino) {
-+
-+                /* if the resolution needed is too low, one dim of the tilec could be equal to zero
-+                 * and no packets are used to decode this resolution and
-+                 * l_current_pi->resno is always >= p_tile->comps[l_current_pi->compno].minimum_num_resolutions
-+                 * and no l_img_comp->resno_decoded are computed
-+                 */
-+                OPJ_BOOL* first_pass_failed = (OPJ_BOOL*)opj_malloc(l_image->numcomps * sizeof(OPJ_BOOL));
-+                if (!first_pass_failed)
-+                {
-+                    opj_pi_destroy(l_pi,l_nb_pocs);
-+                    return OPJ_FALSE;
-+                }
-+                memset(first_pass_failed, OPJ_TRUE, l_image->numcomps * sizeof(OPJ_BOOL));
-+
-+                while (opj_pi_next(l_current_pi)) {
-+                  JAS_FPRINTF( stderr, "packet offset=00000166 prg=%d cmptno=%02d rlvlno=%02d prcno=%03d lyrno=%02d\n\n",
-+                    l_current_pi->poc.prg1, l_current_pi->compno, l_current_pi->resno, l_current_pi->precno, l_current_pi->layno );
-+
 +                        if (l_tcp->num_layers_to_decode > l_current_pi->layno
 +                                        && l_current_pi->resno < p_tile->comps[l_current_pi->compno].minimum_num_resolutions) {
 +                                l_nb_bytes_read = 0;
@@ -34907,7 +34805,11 @@ index 232a543..37f9814 100644
 -			} else {
 -				e = 0;
 -			}
--			if(e == -999) return -999;
+-            if(e == -999)
+-            {
+-                pi_destroy(pi, cp, tileno);
+-                return -999;
+-            }
 -			/* progression in resolution */
 -			image->comps[pi[pino].compno].resno_decoded =	
 -				(e > 0) ? 
@@ -34980,11 +34882,19 @@ index 232a543..37f9814 100644
 +        OPJ_UINT32 l_nb_total_bytes_read = 0;
 +
 +        *p_data_read = 0;
-+
+ 
+-opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) {
+-	/* create the tcd structure */
+-	opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
+-	if(!t2) return NULL;
+-	t2->cinfo = cinfo;
+-	t2->image = image;
+-	t2->cp = cp;
 +        if (! opj_t2_read_packet_header(p_t2,p_tile,p_tcp,p_pi,&l_read_data,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
+-	return t2;
 +        p_src += l_nb_bytes_read;
 +        l_nb_total_bytes_read += l_nb_bytes_read;
 +        p_max_length -= l_nb_bytes_read;
@@ -34996,18 +34906,10 @@ index 232a543..37f9814 100644
 +                if (! opj_t2_read_packet_data(p_t2,p_tile,p_pi,p_src,&l_nb_bytes_read,p_max_length,p_pack_info)) {
 +                        return OPJ_FALSE;
 +                }
- 
--opj_t2_t* t2_create(opj_common_ptr cinfo, opj_image_t *image, opj_cp_t *cp) {
--	/* create the tcd structure */
--	opj_t2_t *t2 = (opj_t2_t*)opj_malloc(sizeof(opj_t2_t));
--	if(!t2) return NULL;
--	t2->cinfo = cinfo;
--	t2->image = image;
--	t2->cp = cp;
++
 +                l_nb_total_bytes_read += l_nb_bytes_read;
 +        }
- 
--	return t2;
++
 +        *p_data_read = l_nb_total_bytes_read;
 +
 +        return OPJ_TRUE;
@@ -35285,9 +35187,9 @@ index 232a543..37f9814 100644
 +        *p_data_read = l_nb_total_bytes_read;
 +
 +        return OPJ_TRUE;
-+}
-+
-+
+ }
+ 
+ 
 +OPJ_BOOL opj_t2_read_packet_header( opj_t2_t* p_t2,
 +                                    opj_tcd_tile_t *p_tile,
 +                                    opj_tcp_t *p_tcp,
@@ -35369,7 +35271,7 @@ index 232a543..37f9814 100644
 +        if (! l_bio) {
 +                return OPJ_FALSE;
 +        }
-+
+ 
 +        if (l_cp->ppm == 1) { /* PPM */
 +                l_header_data_start = &l_cp->ppm_data;
 +                l_header_data = *l_header_data_start;
@@ -35537,13 +35439,13 @@ index 232a543..37f9814 100644
 +                        l_header_data += 2;
 +                }
 +        }
-+
+ 
 +        l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start);
 +        JAS_FPRINTF( stderr, "hdrlen=%d \n", l_header_length );
 +        JAS_FPRINTF( stderr, "packet body\n");
 +        *l_modified_length_ptr -= l_header_length;
 +        *l_header_data_start += l_header_length;
-+
+ 
 +        /* << INDEX */
 +        /* End of packet header position. Currently only represents the distance to start of packet
 +         Will be updated later by incrementing with packet start value */
@@ -35781,9 +35683,9 @@ index 232a543..37f9814 100644
 +        }
 +
 +        return OPJ_TRUE;
- }
- 
- 
++}
++
++
 +OPJ_BOOL opj_t2_init_seg(   opj_tcd_cblk_dec_t* cblk,
 +                            OPJ_UINT32 index, 
 +                            OPJ_UINT32 cblksty, 
@@ -35791,11 +35693,11 @@ index 232a543..37f9814 100644
 +{
 +        opj_tcd_seg_t* seg = 00;
 +        OPJ_UINT32 l_nb_segs = index + 1;
- 
++
 +        if (l_nb_segs > cblk->m_current_max_segs) {
 +                opj_tcd_seg_t* new_segs;
 +                cblk->m_current_max_segs += OPJ_J2K_DEFAULT_NB_SEGS;
- 
++
 +                new_segs = (opj_tcd_seg_t*) opj_realloc(cblk->segs, cblk->m_current_max_segs * sizeof(opj_tcd_seg_t));
 +                if(! new_segs) {
 +                        opj_free(cblk->segs);
@@ -35806,7 +35708,7 @@ index 232a543..37f9814 100644
 +                }
 +                cblk->segs = new_segs;
 +        }
- 
++
 +        seg = &cblk->segs[index];
 +        memset(seg,0,sizeof(opj_tcd_seg_t));
 +
@@ -35952,7 +35854,7 @@ index 2151ba6..931141e 100644
  /* ----------------------------------------------------------------------- */
  /*@}*/
 diff --git a/extern/libopenjpeg/tcd.c b/extern/libopenjpeg/tcd.c
-index 18cdbc7..79262fc 100644
+index 62904eb..79262fc 100644
 --- a/extern/libopenjpeg/tcd.c
 +++ b/extern/libopenjpeg/tcd.c
 @@ -1,11 +1,19 @@
@@ -35978,9 +35880,13 @@ index 18cdbc7..79262fc 100644
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
-@@ -32,1493 +40,2090 @@
+@@ -30,1572 +38,2092 @@
+  * POSSIBILITY OF SUCH DAMAGE.
+  */
  
+-#define _ISOC99_SOURCE /* lrintf is C99 */
  #include "opj_includes.h"
+-#include <assert.h>
  
 +/* ----------------------------------------------------------------------- */
 +
@@ -37019,6 +36925,36 @@ index 18cdbc7..79262fc 100644
 +OPJ_MACRO_TCD_ALLOCATE(opj_tcd_init_decode_tile, opj_tcd_cblk_dec_t, 0.5f, dec, opj_tcd_code_block_dec_allocate)
 +
 +#undef OPJ_MACRO_TCD_ALLOCATE
++
++/**
++ * Allocates memory for an encoding code block.
++ */
++OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block)
++{
++        if (! p_code_block->data) {
++
++                p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE*2); /*why +1 ?*/
++                if(! p_code_block->data) {
++                        return OPJ_FALSE;
++                }
++
++                p_code_block->data[0] = 0;
++                p_code_block->data+=1;
++
++                /* no memset since data */
++                p_code_block->layers = (opj_tcd_layer_t*) opj_malloc(100 * sizeof(opj_tcd_layer_t));
++                if (! p_code_block->layers) {
++                        return OPJ_FALSE;
++                }
++
++                p_code_block->passes = (opj_tcd_pass_t*) opj_malloc(100 * sizeof(opj_tcd_pass_t));
++                if (! p_code_block->passes) {
++                        return OPJ_FALSE;
++                }
++        }
++
++        memset(p_code_block->layers,0,100 * sizeof(opj_tcd_layer_t));
++        memset(p_code_block->passes,0,100 * sizeof(opj_tcd_pass_t));
  
 -void tcd_malloc_encode(opj_tcd_t *tcd, opj_image_t * image, opj_cp_t * cp, int curtileno) {
 -	int tileno, compno, resno, bandno, precno, cblkno;
@@ -37147,7 +37083,9 @@ index 18cdbc7..79262fc 100644
 -					cbgwidthexpn = pdx - 1;
 -					cbgheightexpn = pdy - 1;
 -				}
--				
+-        (void)brcbgyend;
+-        (void)brcbgxend;
+-
 -				cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
 -				cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
 -				
@@ -37231,8 +37169,10 @@ index 18cdbc7..79262fc 100644
 -							cblk->y0 = int_max(cblkystart, prc->y0);
 -							cblk->x1 = int_min(cblkxend, prc->x1);
 -							cblk->y1 = int_min(cblkyend, prc->y1);
--							cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
+-							cblk->data = (unsigned char*) opj_calloc(9728+2, sizeof(unsigned char));
 -							/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
+-							cblk->data[0] = 0;
+-							cblk->data[1] = 0;
 -							cblk->data += 2;
 -							cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
 -							cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -37244,36 +37184,6 @@ index 18cdbc7..79262fc 100644
 -	}
 -	
 -	/* tcd_dump(stdout, tcd, &tcd->tcd_image); */
-+/**
-+ * Allocates memory for an encoding code block.
-+ */
-+OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block)
-+{
-+        if (! p_code_block->data) {
-+
-+                p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE*2); /*why +1 ?*/
-+                if(! p_code_block->data) {
-+                        return OPJ_FALSE;
-+                }
-+
-+                p_code_block->data[0] = 0;
-+                p_code_block->data+=1;
-+
-+                /* no memset since data */
-+                p_code_block->layers = (opj_tcd_layer_t*) opj_malloc(100 * sizeof(opj_tcd_layer_t));
-+                if (! p_code_block->layers) {
-+                        return OPJ_FALSE;
-+                }
-+
-+                p_code_block->passes = (opj_tcd_pass_t*) opj_malloc(100 * sizeof(opj_tcd_pass_t));
-+                if (! p_code_block->passes) {
-+                        return OPJ_FALSE;
-+                }
-+        }
-+
-+        memset(p_code_block->layers,0,100 * sizeof(opj_tcd_layer_t));
-+        memset(p_code_block->passes,0,100 * sizeof(opj_tcd_pass_t));
-+
 +        return OPJ_TRUE;
  }
  
@@ -37469,6 +37379,8 @@ index 18cdbc7..79262fc 100644
 -					cbgwidthexpn = pdx - 1;
 -					cbgheightexpn = pdy - 1;
 -				}
+-        (void)brcbgyend;
+-        (void)brcbgxend;
 -				
 -				cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
 -				cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -37554,6 +37466,8 @@ index 18cdbc7..79262fc 100644
 -							cblk->y1 = int_min(cblkyend, prc->y1);
 -							cblk->data = (unsigned char*) opj_calloc(8192+2, sizeof(unsigned char));
 -							/* FIXME: mqc_init_enc and mqc_byteout underrun the buffer if we don't do this. Why? */
+-							cblk->data[0] = 0;
+-							cblk->data[1] = 0;
 -							cblk->data += 2;
 -							cblk->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
 -							cblk->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
@@ -37605,7 +37519,7 @@ index 18cdbc7..79262fc 100644
 -	tcd->image = image;
 -	tcd->tcd_image->tw = cp->tw;
 -	tcd->tcd_image->th = cp->th;
--	tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_malloc(cp->tw * cp->th * sizeof(opj_tcd_tile_t));
+-    tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(cp->tw * cp->th, sizeof(opj_tcd_tile_t));
 -
 -	/* 
 -	Allocate place to store the decoded data = final image
@@ -37763,6 +37677,12 @@ index 18cdbc7..79262fc 100644
 -		opj_tccp_t *tccp = &tcp->tccps[compno];
 -		opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
 -		
+-		if (tccp->numresolutions <= 0)
+-		{
+-			cp->tileno[tileno] = -1;
+-			return;
+-		}
+-
 -		/* border of each tile component (global) */
 -		tilec->x0 = int_ceildiv(tile->x0, image->comps[compno].dx);
 -		tilec->y0 = int_ceildiv(tile->y0, image->comps[compno].dy);
@@ -37822,6 +37742,8 @@ index 18cdbc7..79262fc 100644
 -				cbgwidthexpn = pdx - 1;
 -				cbgheightexpn = pdy - 1;
 -			}
+-      (void)brcbgyend;
+-      (void)brcbgxend;
 -			
 -			cblkwidthexpn = int_min(tccp->cblkw, cbgwidthexpn);
 -			cblkheightexpn = int_min(tccp->cblkh, cbgheightexpn);
@@ -38769,73 +38691,6 @@ index 18cdbc7..79262fc 100644
 +        if (! l_tcp->mct) {
 +                return OPJ_TRUE;
 +        }
-+
-+        l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0));
-+
-+        if (l_tile->numcomps >= 3 ){
-+                /* testcase 1336.pdf.asan.47.376 */
-+                if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||
-+                    (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||
-+                    (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {
-+                        fprintf(stderr, "Tiles don't all have the same dimension. Skip the MCT step.\n");
-+                        return OPJ_FALSE;
-+                }
-+                else if (l_tcp->mct == 2) {
-+                        OPJ_BYTE ** l_data;
-+
-+                        if (! l_tcp->m_mct_decoding_matrix) {
-+                                return OPJ_TRUE;
-+                        }
-+
-+                        l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*));
-+                        if (! l_data) {
-+                                return OPJ_FALSE;
-+                        }
-+
-+                        for (i=0;i<l_tile->numcomps;++i) {
-+                                l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
-+                                ++l_tile_comp;
-+                        }
-+
-+                        if (! opj_mct_decode_custom(/* MCT data */
-+                                                                        (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
-+                                                                        /* size of components */
-+                                                                        l_samples,
-+                                                                        /* components */
-+                                                                        l_data,
-+                                                                        /* nb of components (i.e. size of pData) */
-+                                                                        l_tile->numcomps,
-+                                                                        /* tells if the data is signed */
-+                                                                        p_tcd->image->comps->sgnd)) {
-+                                opj_free(l_data);
-+                                return OPJ_FALSE;
-+                        }
-+
-+                        opj_free(l_data);
-+                }
-+                else {
-+                        if (l_tcp->tccps->qmfbid == 1) {
-+                                opj_mct_decode(     l_tile->comps[0].data,
-+                                                        l_tile->comps[1].data,
-+                                                        l_tile->comps[2].data,
-+                                                        l_samples);
-+                        }
-+                        else {
-+                            opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
-+                                                (OPJ_FLOAT32*)l_tile->comps[1].data,
-+                                                (OPJ_FLOAT32*)l_tile->comps[2].data,
-+                                                l_samples);
-+                        }
-+                }
-+        }
-+        else {
-+                /* FIXME need to use opj_event_msg function */
-+                fprintf(stderr,"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps);
-+        }
-+
-+        return OPJ_TRUE;
-+}
-+
  
 -opj_bool tcd_decode_tile(opj_tcd_t *tcd, unsigned char *src, int len, int tileno, opj_codestream_info_t *cstr_info) {
 -	int l;
@@ -38891,16 +38746,92 @@ index 18cdbc7..79262fc 100644
 -	if (l == -999) {
 -		eof = 1;
 -		opj_event_msg(tcd->cinfo, EVT_ERROR, "tcd_decode: incomplete bistream\n");
+-    return OPJ_FALSE;
 -	}
 -	
 -	/*------------------TIER1-----------------*/
 -	
 -	t1_time = opj_clock();	/* time needed to decode a tile */
 -	t1 = t1_create(tcd->cinfo);
+-    if (t1 == NULL)
+-    {
+-        opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
+-        t1_destroy(t1);
+-        return OPJ_FALSE;
+-    }
+-
 -	for (compno = 0; compno < tile->numcomps; ++compno) {
 -		opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
 -		/* The +3 is headroom required by the vectorized DWT */
 -		tilec->data = (int*) opj_aligned_malloc((((tilec->x1 - tilec->x0) * (tilec->y1 - tilec->y0))+3) * sizeof(int));
+-        if (tilec->data == NULL)
+-        {
+-            opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
+-            t1_destroy(t1);
+-            return OPJ_FALSE;
++        l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0));
++
++        if (l_tile->numcomps >= 3 ){
++                /* testcase 1336.pdf.asan.47.376 */
++                if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||
++                    (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||
++                    (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {
++                        fprintf(stderr, "Tiles don't all have the same dimension. Skip the MCT step.\n");
++                        return OPJ_FALSE;
++                }
++                else if (l_tcp->mct == 2) {
++                        OPJ_BYTE ** l_data;
++
++                        if (! l_tcp->m_mct_decoding_matrix) {
++                                return OPJ_TRUE;
++                        }
++
++                        l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*));
++                        if (! l_data) {
++                                return OPJ_FALSE;
++                        }
++
++                        for (i=0;i<l_tile->numcomps;++i) {
++                                l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++                                ++l_tile_comp;
++                        }
++
++                        if (! opj_mct_decode_custom(/* MCT data */
++                                                                        (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
++                                                                        /* size of components */
++                                                                        l_samples,
++                                                                        /* components */
++                                                                        l_data,
++                                                                        /* nb of components (i.e. size of pData) */
++                                                                        l_tile->numcomps,
++                                                                        /* tells if the data is signed */
++                                                                        p_tcd->image->comps->sgnd)) {
++                                opj_free(l_data);
++                                return OPJ_FALSE;
++                        }
++
++                        opj_free(l_data);
++                }
++                else {
++                        if (l_tcp->tccps->qmfbid == 1) {
++                                opj_mct_decode(     l_tile->comps[0].data,
++                                                        l_tile->comps[1].data,
++                                                        l_tile->comps[2].data,
++                                                        l_samples);
++                        }
++                        else {
++                            opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
++                                                (OPJ_FLOAT32*)l_tile->comps[1].data,
++                                                (OPJ_FLOAT32*)l_tile->comps[2].data,
++                                                l_samples);
++                        }
++                }
++        }
++        else {
++                /* FIXME need to use opj_event_msg function */
++                fprintf(stderr,"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps);
+         }
+ 
 -		t1_decode_cblks(t1, tilec, &tcd->tcp->tccps[compno]);
 -	}
 -	t1_destroy(t1);
@@ -38915,13 +38846,15 @@ index 18cdbc7..79262fc 100644
 -		int numres2decode;
 -
 -		if (tcd->cp->reduce != 0) {
--			tcd->image->comps[compno].resno_decoded =
--				tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
--			if (tcd->image->comps[compno].resno_decoded < 0) {				
+-			if ( tile->comps[compno].numresolutions < ( tcd->cp->reduce - 1 ) ) {				
 -				opj_event_msg(tcd->cinfo, EVT_ERROR, "Error decoding tile. The number of resolutions to remove [%d+1] is higher than the number "
 -					" of resolutions in the original codestream [%d]\nModify the cp_reduce parameter.\n", tcd->cp->reduce, tile->comps[compno].numresolutions);
 -				return OPJ_FALSE;
 -			}
+-      else {
+-		  	tcd->image->comps[compno].resno_decoded =
+-				tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
+-      }
 -		}
 -
 -		numres2decode = tcd->image->comps[compno].resno_decoded + 1;
@@ -38942,6 +38875,13 @@ index 18cdbc7..79262fc 100644
 -		int n = (tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0);
 -
 -		if (tile->numcomps >= 3 ){
+-      /* testcase 1336.pdf.asan.47.376 */
+-      if ((tile->comps[0].x1 - tile->comps[0].x0) * (tile->comps[0].y1 - tile->comps[0].y0) < n ||
+-        (  tile->comps[1].x1 - tile->comps[1].x0) * (tile->comps[1].y1 - tile->comps[1].y0) < n ||
+-        (  tile->comps[2].x1 - tile->comps[2].x0) * (tile->comps[2].y1 - tile->comps[2].y0) < n) {
+-        opj_event_msg(tcd->cinfo, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n");
+-        return OPJ_FALSE;
+-      }
 -			if (tcd->tcp->tccps[0].qmfbid == 1) {
 -				mct_decode(
 -						tile->comps[0].data,
@@ -38973,42 +38913,30 @@ index 18cdbc7..79262fc 100644
 -		int tw = tilec->x1 - tilec->x0;
 -		int w = imagec->w;
 -
+-		int i, j;
 -		int offset_x = int_ceildivpow2(imagec->x0, imagec->factor);
 -		int offset_y = int_ceildivpow2(imagec->y0, imagec->factor);
+-    /* NR-DEC-2977.pdf.asan.67.2198.jp2-52-decode */
+-    if( res->x0 - offset_x < 0 || res->x1 - offset_x < 0
+-     || res->y0 - offset_y < 0 || res->y1 - offset_y < 0 )
+-      {
+-      opj_event_msg(tcd->cinfo, EVT_ERROR, "Impossible offsets %d / %d\n", offset_x, offset_y);
+-      return OPJ_FALSE;
+-      }
+-    assert( 0 <= res->x0 - offset_x && 0 <= res->x1 - offset_x );
+-    assert( 0 <= res->y0 - offset_y && 0 <= res->y1 - offset_y );
 -
--		int i, j;
 -		if(!imagec->data){
 -			imagec->data = (int*) opj_malloc(imagec->w * imagec->h * sizeof(int));
 -		}
--		if(tcd->tcp->tccps[compno].qmfbid == 1) {
--			for(j = res->y0; j < res->y1; ++j) {
--				for(i = res->x0; i < res->x1; ++i) {
--					int v = tilec->data[i - res->x0 + (j - res->y0) * tw];
--					v += adjust;
--					imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
--				}
--			}
--		}else{
--			for(j = res->y0; j < res->y1; ++j) {
--				for(i = res->x0; i < res->x1; ++i) {
--					float tmp = ((float*)tilec->data)[i - res->x0 + (j - res->y0) * tw];
--					int v = lrintf(tmp);
--					v += adjust;
--					imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
--				}
--			}
--		}
--		opj_aligned_free(tilec->data);
--	}
--
--	tile_time = opj_clock() - tile_time;	/* time needed to decode a tile */
--	opj_event_msg(tcd->cinfo, EVT_INFO, "- tile decoded in %f s\n", tile_time);
--
--	if (eof) {
--		return OPJ_FALSE;
--	}
--	
--	return OPJ_TRUE;
+-        if (!imagec->data)
+-        {
+-            opj_event_msg(tcd->cinfo, EVT_ERROR, "Out of memory\n");
+-            return OPJ_FALSE;
++        return OPJ_TRUE;
++}
++
++
 +OPJ_BOOL opj_tcd_dc_level_shift_decode ( opj_tcd_t *p_tcd )
 +{
 +        OPJ_UINT32 compno;
@@ -39069,16 +38997,52 @@ index 18cdbc7..79262fc 100644
 +                ++l_img_comp;
 +                ++l_tccp;
 +                ++l_tile_comp;
-+        }
+         }
+-		if(tcd->tcp->tccps[compno].qmfbid == 1) {
+-			for(j = res->y0; j < res->y1; ++j) {
+-				for(i = res->x0; i < res->x1; ++i) {
+-					int v = tilec->data[i - res->x0 + (j - res->y0) * tw];
+-					v += adjust;
+-          /*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
+-					imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
+-				}
+-			}
+-		}else{
+-			for(j = res->y0; j < res->y1; ++j) {
+-				for(i = res->x0; i < res->x1; ++i) {
+-					float tmp = ((float*)tilec->data)[i - res->x0 + (j - res->y0) * tw];
+-					int v = lrintf(tmp);
+-					v += adjust;
+-          /*assert( (i - offset_x) + (j - offset_y) * w >= 0 );*/
+-					imagec->data[(i - offset_x) + (j - offset_y) * w] = int_clamp(v, min, max);
+-				}
+-			}
+-		}
+-		opj_aligned_free(tilec->data);
+-	}
+-
+-	tile_time = opj_clock() - tile_time;	/* time needed to decode a tile */
+-	opj_event_msg(tcd->cinfo, EVT_INFO, "- tile decoded in %f s\n", tile_time);
+-
+-	if (eof) {
+-		return OPJ_FALSE;
+-	}
+-	
+-	return OPJ_TRUE;
 +
 +        return OPJ_TRUE;
  }
  
 -void tcd_free_decode(opj_tcd_t *tcd) {
 -	opj_tcd_image_t *tcd_image = tcd->tcd_image;	
+-    int i = 0;
+-    for (i = 0; i < tcd_image->tw * tcd_image->th; i++)
+-    {
+-        tcd_free_decode_tile(tcd, i);
+-    }
+ 
 -	opj_free(tcd_image->tiles);
 +
-+
 +/**
 + * Deallocates the encoding data of the given precinct.
 + */
@@ -39115,8 +39079,30 @@ index 18cdbc7..79262fc 100644
 +                opj_free(p_precinct->cblks.dec);
 +                p_precinct->cblks.dec = 00;
 +        }
-+}
-+
+ }
+ 
+-void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno) {
+-    int compno,resno,bandno,precno,cblkno;
+-
+-	opj_tcd_image_t *tcd_image = tcd->tcd_image;
+-
+-	opj_tcd_tile_t *tile = &tcd_image->tiles[tileno];
+-    if (tile->comps != NULL) {
+-        for (compno = 0; compno < tile->numcomps; compno++) {
+-            opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
+-            for (resno = 0; resno < tilec->numresolutions; resno++) {
+-                opj_tcd_resolution_t *res = &tilec->resolutions[resno];
+-                for (bandno = 0; bandno < res->numbands; bandno++) {
+-                    opj_tcd_band_t *band = &res->bands[bandno];
+-                    for (precno = 0; precno < res->ph * res->pw; precno++) {
+-                        opj_tcd_precinct_t *prec = &band->precincts[precno];
+-                        if (prec->cblks.dec != NULL) {
+-                            for (cblkno = 0; cblkno < prec->cw * prec->ch; ++cblkno) {
+-                                opj_tcd_cblk_dec_t* cblk = &prec->cblks.dec[cblkno];
+-                                opj_free(cblk->data);
+-                                opj_free(cblk->segs);
+-                            }
+-                            opj_free(prec->cblks.dec);
 +/**
 + * Deallocates the encoding data of the given precinct.
 + */
@@ -39137,7 +39123,20 @@ index 18cdbc7..79262fc 100644
 +                        if (l_code_block->layers) {
 +                                opj_free(l_code_block->layers );
 +                                l_code_block->layers = 00;
-+                        }
+                         }
+-                        if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
+-                        if (prec->incltree != NULL) tgt_destroy(prec->incltree);
+-
+-
+-                    }
+-                    opj_free(band->precincts);
+-				}
+-			}
+-            opj_free(tilec->resolutions);
+-		}
+-        opj_free(tile->comps);
+-        tile->comps = NULL;
+-	}
 +
 +                        if (l_code_block->passes) {
 +                                opj_free(l_code_block->passes );
@@ -39219,8 +39218,8 @@ index 18cdbc7..79262fc 100644
 +        }
 +
 +        return OPJ_TRUE;
-+}
-+
+ }
+ 
 +OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd )
 +{
 +        opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
@@ -39233,7 +39232,7 @@ index 18cdbc7..79262fc 100644
 +        if(!p_tcd->tcp->mct) {
 +                return OPJ_TRUE;
 +        }
-+
+ 
 +        if (p_tcd->tcp->mct == 2) {
 +                if (! p_tcd->tcp->m_mct_coding_matrix) {
 +                        return OPJ_TRUE;
@@ -39274,31 +39273,8 @@ index 18cdbc7..79262fc 100644
 +        }
 +
 +        return OPJ_TRUE;
- }
++}
  
--void tcd_free_decode_tile(opj_tcd_t *tcd, int tileno) {
--	int compno,resno,bandno,precno;
--
--	opj_tcd_image_t *tcd_image = tcd->tcd_image;
--
--	opj_tcd_tile_t *tile = &tcd_image->tiles[tileno];
--	for (compno = 0; compno < tile->numcomps; compno++) {
--		opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
--		for (resno = 0; resno < tilec->numresolutions; resno++) {
--			opj_tcd_resolution_t *res = &tilec->resolutions[resno];
--			for (bandno = 0; bandno < res->numbands; bandno++) {
--				opj_tcd_band_t *band = &res->bands[bandno];
--				for (precno = 0; precno < res->ph * res->pw; precno++) {
--					opj_tcd_precinct_t *prec = &band->precincts[precno];
--					if (prec->imsbtree != NULL) tgt_destroy(prec->imsbtree);
--					if (prec->incltree != NULL) tgt_destroy(prec->incltree);
--				}
--				opj_free(band->precincts);
--			}
--		}
--		opj_free(tilec->resolutions);
--	}
--	opj_free(tile->comps);
 +OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd )
 +{
 +        opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
@@ -39323,8 +39299,8 @@ index 18cdbc7..79262fc 100644
 +        }
 +
 +        return OPJ_TRUE;
- }
- 
++}
++
 +OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd )
 +{
 +        opj_t1_t * l_t1;
@@ -39358,7 +39334,7 @@ index 18cdbc7..79262fc 100644
 +
 +        return OPJ_TRUE;
 +}
- 
++
 +OPJ_BOOL opj_tcd_t2_encode (opj_tcd_t *p_tcd,
 +                                                OPJ_BYTE * p_dest_data,
 +                                                OPJ_UINT32 * p_data_written,
@@ -39395,7 +39371,7 @@ index 18cdbc7..79262fc 100644
 +        /*---------------CLEAN-------------------*/
 +        return OPJ_TRUE;
 +}
- 
++
 +
 +OPJ_BOOL opj_tcd_rate_allocate_encode(  opj_tcd_t *p_tcd,
 +                                                                            OPJ_BYTE * p_dest_data,
@@ -41008,7 +40984,7 @@ index 3d3e8a0..7ffb575 100644
  #ifdef WITH_DDS
  	{NULL, NULL, imb_is_a_dds, NULL, imb_ftype_default, imb_load_dds, NULL, NULL, NULL, 0, IMB_FTYPE_DDS, COLOR_ROLE_DEFAULT_BYTE},
 diff --git a/source/blender/imbuf/intern/jp2.c b/source/blender/imbuf/intern/jp2.c
-index 570ca5b..09a8a9e 100644
+index 390f250..923318f 100644
 --- a/source/blender/imbuf/intern/jp2.c
 +++ b/source/blender/imbuf/intern/jp2.c
 @@ -38,7 +38,7 @@
@@ -41020,7 +40996,7 @@ index 570ca5b..09a8a9e 100644
  
  static const char JP2_HEAD[] = {0x0, 0x0, 0x0, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A};
  static const char J2K_HEAD[] = {0xFF, 0x4F, 0xFF, 0x51, 0x00};
-@@ -73,6 +73,19 @@ static int check_j2k(const unsigned char *mem) /* J2K_CFMT */
+@@ -73,6 +73,19 @@ static bool check_j2k(const unsigned char *mem) /* J2K_CFMT */
  	return memcmp(J2K_HEAD, mem, sizeof(J2K_HEAD)) ? 0 : 1;
  }
  
@@ -41290,7 +41266,7 @@ index 570ca5b..09a8a9e 100644
  	unsigned int i, i_next, w, h, planes;
  	unsigned int y;
  	int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */
--	int is_jp2, is_j2k;
+-	bool is_jp2, is_j2k;
  	
  	opj_dparameters_t parameters;   /* decompression parameters */
  	
diff --git a/debian/patches/0008-make_blender_reproducible.patch b/debian/patches/0008-make_blender_reproducible.patch
deleted file mode 100644
index 54fc5a7..0000000
--- a/debian/patches/0008-make_blender_reproducible.patch
+++ /dev/null
@@ -1,81 +0,0 @@
-From: Campbell Barton <ideasman42 at gmail.com>
-Date: Wed, 11 May 2016 02:43:58 +1000
-Subject: make_blender_reproducible
-
----
- CMakeLists.txt                    |  4 ++++
- build_files/cmake/buildinfo.cmake | 26 +++++++++++++++++++-------
- source/creator/CMakeLists.txt     |  3 +++
- 3 files changed, 26 insertions(+), 7 deletions(-)
-
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index fa05865..d285df9 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -221,6 +221,10 @@ if(${CMAKE_VERSION} VERSION_LESS 2.8.8)
- 	# add_library OBJECT arg unsupported
- 	set(WITH_BUILDINFO OFF)
- endif()
-+set(BUILDINFO_OVERRIDE_DATE "" CACHE STRING "Use instead of the current date for reproducable builds (empty string disables this option)")
-+set(BUILDINFO_OVERRIDE_TIME "" CACHE STRING "Use instead of the current time for reproducable builds (empty string disables this option)")
-+mark_as_advanced(BUILDINFO_OVERRIDE_DATE)
-+mark_as_advanced(BUILDINFO_OVERRIDE_TIME)
- 
- option(WITH_IK_ITASC      "Enable ITASC IK solver (only disable for development & for incompatible C++ compilers)" ON)
- option(WITH_IK_SOLVER     "Enable Legacy IK solver (only disable for development)" ON)
-diff --git a/build_files/cmake/buildinfo.cmake b/build_files/cmake/buildinfo.cmake
-index d292b35..d3b6d10 100644
---- a/build_files/cmake/buildinfo.cmake
-+++ b/build_files/cmake/buildinfo.cmake
-@@ -1,5 +1,10 @@
--# This is called by cmake as an extermal process from
-+# This is called by cmake as an external process from
- # ./source/creator/CMakeLists.txt to write ./source/creator/buildinfo.h
-+# Caller must define:
-+#   SOURCE_DIR
-+# Optional overrides:
-+#   BUILD_DATE
-+#   BUILD_TIME
- 
- # Extract working copy information for SOURCE_DIR into MY_XXX variables
- # with a default in case anything fails, for example when using git-svn
-@@ -134,12 +139,19 @@ endif()
- # BUILD_PLATFORM and BUILD_PLATFORM are taken from CMake
- # but BUILD_DATE and BUILD_TIME are platform dependent
- if(UNIX)
--	execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
--	execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
--endif()
--if(WIN32)
--	execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
--	execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
-+	if(NOT BUILD_DATE)
-+		execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
-+	endif()
-+	if(NOT BUILD_TIME)
-+		execute_process(COMMAND date "+%H:%M:%S" OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
-+	endif()
-+elseif(WIN32)
-+	if(NOT BUILD_DATE)
-+		execute_process(COMMAND cmd /c date /t OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE)
-+	endif()
-+	if(NOT BUILD_TIME)
-+		execute_process(COMMAND cmd /c time /t OUTPUT_VARIABLE BUILD_TIME OUTPUT_STRIP_TRAILING_WHITESPACE)
-+	endif()
- endif()
- 
- # Write a file with the BUILD_HASH define
-diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt
-index e1e72d2..aa60c17 100644
---- a/source/creator/CMakeLists.txt
-+++ b/source/creator/CMakeLists.txt
-@@ -182,6 +182,9 @@ if(WITH_BUILDINFO)
- 	add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/_buildinfo.h
- 		COMMAND ${CMAKE_COMMAND}
- 		-DSOURCE_DIR=${CMAKE_SOURCE_DIR}
-+		# overrides only used when non-empty strings
-+		-DBUILD_DATE=${BUILDINFO_OVERRIDE_DATE}
-+		-DBUILD_TIME=${BUILDINFO_OVERRIDE_TIME}
- 		-P ${CMAKE_SOURCE_DIR}/build_files/cmake/buildinfo.cmake)
- 
- 	# buildinfo.h is a generated file
diff --git a/debian/patches/0010-fix_manpage_creation.patch b/debian/patches/0010-fix_manpage_creation.patch
deleted file mode 100644
index 50f2f73..0000000
--- a/debian/patches/0010-fix_manpage_creation.patch
+++ /dev/null
@@ -1,18 +0,0 @@
-From: "Matteo F. Vescovi" <mfv at debian.org>
-Date: Mon, 25 Jul 2016 16:58:26 +0200
-Subject: fix_manpage_creation
-
----
- doc/manpage/blender.1.py | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/doc/manpage/blender.1.py b/doc/manpage/blender.1.py
-index cdd2d7c..5285671 100755
---- a/doc/manpage/blender.1.py
-+++ b/doc/manpage/blender.1.py
-@@ -1,4 +1,4 @@
--#!/usr/bin/env python
-+#!/usr/bin/env python3
- 
- # ##### BEGIN GPL LICENSE BLOCK #####
- #
diff --git a/debian/patches/0011-fix_ld-gold_issue.patch b/debian/patches/0011-fix_ld-gold_issue.patch
deleted file mode 100644
index 8e61f24..0000000
--- a/debian/patches/0011-fix_ld-gold_issue.patch
+++ /dev/null
@@ -1,31 +0,0 @@
-From: "Matteo F. Vescovi" <mfv at debian.org>
-Date: Tue, 27 Sep 2016 22:08:42 +0200
-Subject: fix_ld-gold_issue
-
----
- CMakeLists.txt | 12 ------------
- 1 file changed, 12 deletions(-)
-
-diff --git a/CMakeLists.txt b/CMakeLists.txt
-index d285df9..fd9f657 100644
---- a/CMakeLists.txt
-+++ b/CMakeLists.txt
-@@ -1192,18 +1192,6 @@ if(UNIX AND NOT APPLE)
- 	if(CMAKE_COMPILER_IS_GNUCC)
- 		set(PLATFORM_CFLAGS "-pipe -fPIC -funsigned-char -fno-strict-aliasing")
- 
--		# use ld.gold linker if available, could make optional
--		execute_process(
--		        COMMAND ${CMAKE_C_COMPILER} -fuse-ld=gold -Wl,--version
--		        ERROR_QUIET OUTPUT_VARIABLE LD_VERSION)
--		if("${LD_VERSION}" MATCHES "GNU gold")
--			set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fuse-ld=gold")
--			set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=gold")
--		else()
--			message(STATUS "GNU gold linker isn't available, using the default system linker.")
--		endif()
--		unset(LD_VERSION)
--
- 	# CLang is the same as GCC for now.
- 	elseif(CMAKE_C_COMPILER_ID MATCHES "Clang")
- 		set(PLATFORM_CFLAGS "-pipe -fPIC -funsigned-char -fno-strict-aliasing")
diff --git a/debian/patches/series b/debian/patches/series
index e3ead8a..0c67f45 100644
--- a/debian/patches/series
+++ b/debian/patches/series
@@ -4,8 +4,4 @@
 0004-update_manpages.patch
 0005-do_not_use_version_number_in_system_path.patch
 0006-look_for_dejavu_ttf_with_fontconfig.patch
-0007-fix_FTBFS_on_armel.patch
-0008-make_blender_reproducible.patch
-0009-fix_OpenJPEG2_build.patch
-0010-fix_manpage_creation.patch
-0011-fix_ld-gold_issue.patch
+0007-fix_OpenJPEG2_build.patch

-- 
blender packaging



More information about the pkg-multimedia-commits mailing list